The Runtime Architecture of a Plugin-Based Agent Harness: Plugin Graph, Event Stream, and the Agent Loop

    The phrase "everything is a plugin" describes the outcome but not the mechanism. This article explains why a production-grade agent harness is really two parallel, interlocking systems: a runtime plugin graph that describes what the system is currently composed of, and an append-only event stream that records what it just did, with the agent loop sitting between them. It details the five problems the plugin graph must solve—capability visibility, dependency readiness, scope resolution, teardown cleanup, and updatable, checkable configuration—shows how a single event stream powers model context, UI traces, recovery, and forking, and explains why the agent loop alone is far from enough. It closes with practical principles for building an agent runtime that is extensible, recoverable, and observable rather than just a script that runs a demo.

    1. Starting from “Everything Is a Plugin”: Why It Falls Short

    Almost every agent framework that claims to be pluggable sums itself up with a single line: “everything is a plugin.” That line describes the outcome, not the mechanism. When the source code is in front of you, the observation that “there are many plugins, and each one has an initialization function” is nowhere near enough to explain why this system can support a production-grade agent runtime.

    The question worth asking is this: when one component wants to replace another at runtime, how does the system keep dependencies, lifecycle, and state from falling apart? If you pack model adapters, prompts, tool registries, sessions, storage, sandboxes, the execution loop, and even the UI into the same plugin mechanism, then that mechanism has to solve five problems that are usually split across different systems:

    1. What capabilities a plugin can actually see from its current position;
    2. Whether it should start when the capabilities it depends on haven’t appeared yet;
    3. Whether capabilities with the same name can resolve to different implementations across different sessions or scopes;
    4. Who cleans up the entries, listeners, child processes, and file handles a plugin registered once it exits;
    5. How a static configuration becomes a runtime plugin tree that can be updated dynamically and checked for consistency.

    Only when all five are answered does “everything is a plugin” stop being a slogan and become an architecture that actually runs.

    2. The Core Perspective: Two Systems Running in Parallel

    The best way to understand this kind of framework is not as a single execution pipeline, but as two parallel threads that run alongside and interlock with each other.

    The first is the runtime plugin graph. It describes “what the system is currently composed of”: which capabilities are available, who each one depends on, which scope it takes effect in, and how it should be reclaimed on unload. This is a live dependency graph, not a fixed manifest locked in at compile time.

    The second is the append-only event stream. It records “what the system just did”: every step that actually happened during one agent run—user input, model calls, tool execution, results written back—settled as an append-only, never-rewritten log, from which the model context, the UI trace, and the data needed for recovery and forking are projected.

    Sandwiched between the two is the agent loop. It pulls the model, tools, prompts, and session service out of the plugin graph, drives round after round of the “think—act—observe” cycle, and writes the progress of each step back into the event stream.

    In one sentence: the plugin graph answers “what it’s currently made of,” the event stream answers “what it just did,” and the agent loop is the execution engine that turns the facts of the former into the records of the latter. Together, these two threads form a complete running system.

    3. The Five Separation Problems the Plugin Graph Must Solve

    3.1 Capability Visibility: A Plugin Sees Only What It Should

    If every plugin could freely access everything globally, the system would degrade into a web where anyone can touch anyone, making it impossible to test or reason about. The mature approach is to let the container manage “visibility boundaries”: a plugin declares what capabilities it needs at initialization, and the container injects the matching implementation. The plugin doesn’t need to know where the implementation comes from or who constructs it.

    1. // A plugin declares its dependencies; the container injects them; the plugin doesn't care about implementation details
    2. const toolServicePlugin = definePlugin({
    3. name: 'tool-service',
    4. inject: ['model', 'logger'], // only these capabilities are visible to me
    5. apply(ctx) {
    6. ctx.provide('tool', buildTool()); // expose a new capability to the outside
    7. ctx.on('session:start', onStart); // register a listener; the container reclaims it later
    8. },
    9. });

    The benefit is that dependencies become explicit, a plugin’s behavior becomes predictable, and when any plugin is swapped for a test stub, the rest needs no changes.

    3.2 Dependency Readiness: Wait, or Fail

    Plugins in the real world don’t all arrive at the same time. Storage may still be connecting, a sandbox may still be spinning up, while some feature is already queued waiting to start. The container needs a policy: when a required capability hasn’t appeared yet, does it defer activation and automatically bring it up once the dependency is ready, or does it declare startup failure outright? The former corresponds to “activate as soon as capabilities are ready,” the latter to “fail fast under hard constraints.” Expressing this “dependency + readiness” relationship declaratively, and letting the system auto-assemble in dependency order, is the key capability that sets the plugin graph apart from ordinary function calls.

    3.3 Scope Resolution: Multiple Identities for the Same-Named Capability

    This is where the power of the plugin graph shows most clearly. The same logical capability—say, logging, configuration, or session context—often needs to resolve to a different implementation at the global level, within a session, and within a subtask. A sub-agent should have its own tool allowlist and context, not share the global one. With scoped resolution, the container can bind a same-named capability to different entities at different levels, isolating them while still allowing inheritance.

    1. globalScope.get('logger'); // global logger
    2. sessionScope.get('logger'); // session-specific, carrying session ID context
    3. subAgentScope.get('tool'); // the sub-agent's restricted tool set

    This layered resolution naturally supports production needs like sub-agents, multi-tenancy, and multi-session isolation, without building a separate setup for each scenario.

    3.4 Teardown Cleanup: Whoever Registers, Undoes

    When a plugin is unloaded, if the listeners it registered, the child processes it started, the file handles it opened, and the timers it left pending aren’t reclaimed, the system accumulates a large number of leaks after long running and eventually becomes unusable. A reliable container binds “registration” and “undo” together: everything a plugin registers within a scope hangs on this scope tree, and when the plugin exits, the whole subtree is destroyed in a cascade. Developers don’t have to hand-write cleanup code; resource lifecycle is uniformly backstopped by the container.

    3.5 From Static Configuration to Runtime Tree: Updatable and Checkable

    A config file describes “the desired composition,” but what actually runs is a plugin tree. The container needs to interpret the static configuration into this tree and support safely adding and removing nodes at runtime—hot-plugging a tool, temporarily suspending a sandbox, replacing a model adapter. Going a step further, it can run consistency checks across the whole tree: which capabilities are missing, where circular dependencies appear, which plugin is stuck in an unready, dangling state. Updatable plus checkable is what makes “configuration-driven” real.

    4. The Event Stream: Recording “What Just Happened”

    If the plugin graph is “current composition” on the spatial dimension, the event stream is “the course of events” on the temporal dimension. It records every fact during an agent run in an append-only way—append only, never modify—thereby guaranteeing that history is trustworthy and replayable.

    1. type RunEvent =
    2. | { type: 'user_input'; payload: unknown }
    3. | { type: 'model_call'; payload: unknown }
    4. | { type: 'tool_call'; payload: unknown }
    5. | { type: 'tool_result'; payload: unknown };
    6. // Read-only append; any subscriber can build its own projection from it
    7. function append(e: RunEvent) {
    8. log.push(e);
    9. for (const p of projections) p.apply(e);
    10. }

    The value of this log lies in “projection”: the same set of facts can be projected into different views.

    • Model context: fold the event stream by rules into the current message sequence sent to the model, with compression support to control length;
    • UI trace: render the same batch of events into a user-visible execution process;
    • Recovery: after a process restart or session interruption, replaying the event stream reconstructs the scene;
    • Forking: copying a new log from a given event point lets you derive a parallel exploration of “what if we did it another way.”

    The division of labor between the plugin graph and the event stream becomes clear here: the former decides “which capabilities to do it with,” the latter faithfully records “what was actually done.” The reason the UI, recovery, and forking can all see the same runtime facts is precisely that they share the same event stream, rather than each maintaining its own conflicting state.

    5. The Agent Loop: The Engine That Connects the Two Structures

    The agent loop itself isn’t complex; its classic form needs only four steps: assemble the prompt, call the model, parse out the tool call, execute the tool and write the result back, then loop. Its real difficulty lies in its position—it draws capabilities from the plugin graph and writes facts into the event stream.

    1. async function loop(scope, session) {
    2. for (;;) {
    3. const prompt = session.projectContext(); // project context from the event stream
    4. const decision = await scope.get('model').invoke(prompt);
    5. if (decision.isFinal) return finalize(session, decision);
    6. const result = await scope.get('tool').call(decision.tool, decision.args);
    7. session.append({ type: 'tool_result', payload: result }); // write back to the event stream
    8. }
    9. }

    It’s worth emphasizing: the loop doesn’t itself “own” the model, tools, or prompts; they all come from the plugin graph. This means that replacing a model, adding a set of tools, or switching to a different prompt strategy can leave the loop’s code completely untouched. The loop’s stability and the variability of capabilities are cleanly separated by this boundary.

    6. Why a Production-Grade Harness Can’t Look at Just the Agent Loop

    A minimal loop is indeed simple, but the gap from demo to production falls entirely outside the loop. What really consumes engineering effort are the capabilities that unfold around it:

    • Models and credentials: multi-vendor model adapters, authentication, rate limiting, and fallback;
    • Session recovery and compression: summarization and truncation strategies when the context grows too long;
    • Tool policies and approvals: which tools can run automatically, which need manual confirmation;
    • Sandboxes and remote execution: isolated runtime environments that prevent untrusted code from crossing boundaries;
    • Multi-host: reusing the same runtime facts across forms like CLI, server, and desktop;
    • Sub-agents: deriving capability-restricted subordinate executors within a scope;
    • Plugin start/stop: dynamically adding and removing capabilities at runtime;
    • Observable UI: letting the UI observe a runtime process that stays consistent with the event stream.

    These capabilities map exactly onto the five problems the plugin graph must solve and the multiple projections the event stream must carry. This also explains the conclusion at the start of the article: looking only at the loop severely underestimates a harness’s true complexity.

    7. Practical Recommendations

    If you want to borrow this approach in your own system, you can start from a few principles:

    1. Declarative capability injection: let components declare “what they need” rather than “where to get it,” making dependencies explicit;
    2. Scoped resolution: design layered capability resolution for the global, session, and subtask levels, naturally supporting both isolation and inheritance;
    3. Registration bound to reclamation: every registration has a corresponding cascading undo, handing resource lifecycle to the container;
    4. Facts appended one way: runtime state is governed by an append-only event stream, and every view is a projection of it, avoiding multiple conflicting states;
    5. Configuration-driven plus consistency checks: static configuration generates an updatable runtime tree that can report missing, circular, and dangling conditions;
    6. Cloud-side support: in a real cloud environment, this kind of foundation usually works alongside common categories like object storage, message queues, container platforms, logging services, and monitoring/alerting—each handling state persistence, asynchronous decoupling, runtime isolation, and observability respectively—so that the plugin graph and event stream run stably in production.

    8. Conclusion

    Simply understanding this kind of framework as “many plugins” misses its essence. Its real design tension lies in maintaining two structures at the same time: one that describes “what the system is currently composed of” as a runtime plugin graph, and one that records “what the system just did” as an append-only event stream; and the agent loop sits between them, turning the former’s capabilities into the latter’s records. Once you grasp this main thread, along with the five problems the plugin graph must solve—capability visibility, dependency readiness, scope resolution, teardown cleanup, and configuration hot-update—you can design an agent runtime foundation that is both extensible and recoverable, both flexible and observable, rather than just another script that only runs a demo.