Plugin-Based AI Agent Framework Architecture: Composition vs. History
This article breaks down the two-layer architecture behind production-grade AI agent frameworks: a runtime plugin graph that manages system composition and an append-only event stream that manages execution history. It explains five problems a plugin runtime must solve at once (visibility, readiness semantics, same-name resolution, lifecycle cleanup, and config-to-graph assembly), how layered configuration and hot updates produce an inspectable plugin tree, and how model context, UI traces, and recovery checkpoints are all projected from one shared event log. It closes with a practical build order and guidance for evaluating fast-moving frameworks.
1. Why Production Agents Need More Than a Main Loop
A minimal working agent loop is not complicated: assemble the prompt, call the model once, parse the tool calls in the response, execute the tools, feed the results back to the model, and repeat until the task is done. This logic fits in a few dozen lines of code, and it is where most introductory tutorials start.
Put the same loop into a real product, though, and the problems multiply immediately. How are models and credentials managed? How does a session recover after an interruption? How is context compressed when it grows too long? Do tool calls require approval? Does code execution run locally or in a remote sandbox? How does one kernel embed itself in a CLI, a desktop app, and a web app at the same time? How are sub-agents spawned and reaped? How do plugins hot-swap? And how does the UI observe “the same run facts” the model sees?
These complexities share one trait: almost none of them are about the loop itself, yet all of them end up intruding into the code where the loop lives. Write them directly into the main loop and within weeks the code degrades into a giant web of conditionals that is hard to test, hard to replace, and hard to observe. The mature approach is to pull that complexity out of the loop and hand it to two kinds of infrastructure: one that answers “what capabilities make up the system right now,” and one that answers “what did the system just do.”
2. Two-Layer Architecture: A Runtime Plugin Graph and an Append-Only Event Stream
A framework of this kind can be understood as two systems running at the same time.
The first is a runtime plugin graph. It describes which capabilities are currently available, what each one depends on, the scope in which it takes effect, and who is responsible for cleanup when it is unloaded. It manages composition.
The second is an append-only event stream. It records, in time order, what actually happened during an agent run, and from it the framework projects the model context, the UI trace, and the data needed for recovery and forking. It manages history.
The main loop sits between the two: it obtains the model, tools, prompts, and session services from the plugin graph, and writes the result of each step back to the event stream. Composition and history together form the body of the framework. The immediate payoff of this split is that swapping a model adapter does not touch the history format, changing the UI does not touch dependency wiring, and replay or auditing only needs to read the event stream.
3. Five Problems a Plugin Runtime Must Solve at Once
“Having many plugins” does not explain the value of a plugin-based framework. What makes such a runtime distinctive is whether it handles the following five problems together, problems that are usually treated separately.
Visibility: which capabilities a plugin can see from its current position. If every plugin can see every capability, module boundaries collapse quickly. The workable approach is to declare a visible set per scope, making dependencies explicit.
Readiness semantics: whether a plugin should start when a required capability has not appeared yet. A clear choice has to be made between “wait for dependencies” and “run in degraded mode,” and that choice belongs in metadata rather than scattered across business logic.
Same-name resolution: whether services with the same name can resolve to different implementations in different sessions or scopes. In multi-tenant, multi-session scenarios, a globally singleton service makes isolation impossible.
Lifecycle cleanup: who releases registrations, event listeners, child processes, and file handles when a plugin exits. Without unified reclamation, long-running processes inevitably leak handles and leave ghost listeners behind.
Config to runtime graph: how static configuration becomes a runtime plugin tree that can be updated and inspected. Configuration is not a constant read once; it is a declaration that can be layered and hot-updated continuously.
Schematically, a plugin declaration can look like this (structure only):
// Declarative plugin: inject dependencies, declare scope, register cleanup hookexport const toolRegistry = {inject: ['model', 'session', 'policy'], // readiness semantics: what happens when a dependency is missingscope: 'session', // same-name resolution: session-level isolationapply(ctx) {ctx.tools.register('read_file', handler); // registrationconst timer = setInterval(sweep, 1000); // external resourcereturn () => { clearInterval(timer); }; // called by the runtime on unload}};
4. From Config to Runtime Graph: Layered Assembly and Hot Updates
Startup should not construct a fixed application instance directly. Instead, the loader reads the base configuration layer, layers optional capability packs on top, then layers user patches, mounting configuration entries one by one into plugin instances. The value of this layering is that the base layer guarantees out-of-the-box usability, capability packs determine the product shape, and user patches carry personalization, without any of the three overwriting the implementation details of the others.
Three practices are worth following during assembly: configuration declares only “what is wanted,” not “how to construct it”; load order is derived from dependencies rather than from the order things are written; and every mount produces an inspectable tree, which makes it easy to print, compare, and roll back at runtime. When configuration changes, the runtime only needs to mount and unmount the diff instead of restarting the process.
5. Sessions as an Append-Only Event Stream
The core constraint of the event stream is “append only, never modify.” Each event carries at least a sequence number, a type, a timestamp, and a payload. Types can cover user input, model output, tool calls, tool results, policy decisions, compression summaries, and errors. Because events are immutable, any derived view can be rebuilt at any time, which gives auditing, replay, and debugging a single entry point.
Projecting upward from the event stream yields three kinds of views: the context for the model, generated according to compression and trimming policies; the trace for the UI, aggregated as rendering requires; and the checkpoints for recovery and forking logic, located by sequence number. All three share the same facts, which structurally eliminates the mismatch between “what the UI displays” and “what the model sees.”
// Event append and view projection (structure only)function append(event) {log.push({ seq: log.length, ts: Date.now(), ...event });}function projectContext(log, policy) {return policy.compress(log).map(toModelMessage);}
6. How the Main Loop Cooperates with the Two Infrastructures
The main loop’s responsibility should be reduced to the minimum: read the context projection, call the model, parse tool intent, request permission from the policy service, submit the task to the execution service, and append the result back to the event stream. Every judgment about “is this allowed,” “where does this execute,” and “how do we retry after a failure” is pushed down into plugin capabilities. As a result, the main loop can be fully replaced with a stub in tests, and the same code can be reused in both the web app and the CLI.
7. Implementation Recommendations
A workable order is: first define the event schema and its version number, then implement a minimal plugin graph with dependency resolution, then wire in the model adapter and tool registration, and finally add approval, sandboxing, and UI projection. If cloud-side capabilities are needed, generic categories can express them, for example using object storage for session archives, a message queue to decouple long-running tasks, a container platform for remote sandboxes, and logging plus monitoring and alerting services to observe runtime quality.
One caveat: frameworks of this kind are often evolving quickly, so interfaces and default behaviors may change. Evaluate them against the source code and tests, and reserve a version migration path for the event schema and plugin metadata. Handing composition to the plugin graph and history to the event stream is the most transferable part of this architecture, and the key starting point for building agent infrastructure that can evolve.
