Agent Plugin Architecture Explained: Runtime Plugin Graph and Event Stream in Two-Systems Design

    This article breaks down the architecture of a plugin-based AI agent framework built on two cooperating systems: a runtime plugin graph that resolves capabilities and an append-only event stream that records execution history, with the agent loop acting as the bridge between them. It covers the five problems a runtime plugin container must solve, including capability visibility through scope chains, lazy dependency activation, multiple implementations of the same capability, lifecycle cleanup and resource rollback, and projection from static configuration to a runtime plugin tree. It also explains how the event stream enables context projection, traceable compaction and summarization, and first-class recovery and forking, followed by a productization checklist and common implementation pitfalls.

    Agent Plugin Architecture Explained: Runtime Plugin Graph and Event Stream Working Together

    1. Background: Why “Lots of Plugins” Does Not Explain a Production-Grade Framework

    In discussions about AI agent framework design, “everything is a plugin” has become almost a default slogan. But after actually reading the source code of a mature framework, one fact stands out: a large number of plugins, plus a unified loading entry point exposed by every module, are only surface characteristics. They fall far short of explaining the framework’s real complexity.

    A minimal working agent loop is in fact very simple: assemble a prompt, call the model, parse tool calls from the model output, execute the tools, write the results back into the context, and continue to the next round. A few hundred lines of code are enough to make that run. Between “it runs” and “production-grade,” however, lies an entire field of combinatorial complexity:

    • How models and credentials are managed, and how multiple model services are adapted;
    • How sessions are resumed and how history is compacted when it grows too long;
    • Whether tool calls require policy checks and human approval;
    • Whether code execution runs locally or in a sandbox, and whether remote execution is needed;
    • How the same logic can serve a CLI, a desktop host, and a web interface at once;
    • How sub-agents are spawned and reaped;
    • How plugins can be started and stopped dynamically without breaking tasks already running;
    • How a user interface can observe and intervene in the same body of runtime facts.

    What these problems have in common is that they are orthogonal to each other, yet all of them must hold simultaneously inside a single process. Packing all of them into the agent loop turns the loop body into an unmaintainable giant conditional tree; implementing each one independently means capability discovery, dependency management, and cleanup logic get reimplemented many times over.

    The answer a mature plugin-based framework gives is this: split “what the system is currently composed of” from “what the system just did” into two systems that run in parallel, then place the agent loop between them as a bridge. This article takes that architectural pattern as its core and unfolds its design logic layer by layer.

    2. Two Systems at a Glance: One Graph and One Stream

    A framework of this kind can be understood as two systems running at the same time.

    System one: the runtime plugin graph. It is a directed graph whose nodes are plugins and whose edges are capability dependencies. The graph maintains the following information: which capabilities (services) are currently registered, what each plugin depends on, the scope in which those capabilities take effect, and which registrations must be reclaimed when a plugin is unloaded.

    System two: the append-only event stream. It is a log that is append-only and never modified, recording one by one what actually happened during a unit of agent work: user input, model responses, tool call requests, tool execution results, approval decisions, errors, and retries. This log simultaneously projects three things: the context sent to the model, the execution trace shown in the interface, and the history data needed for recovery and forking.

    The bridge layer: the agent loop. At startup it resolves the model service, tool catalog, prompt service, and session service from the plugin graph; while running it writes every step as an event into the event stream; when a new capability is needed, it issues another resolution request to the plugin graph.

    In one sentence: the plugin graph answers “what the system is composed of right now,” and the event stream answers “what the system just did.” The former is the assembly relationship along the spatial dimension; the latter is the causal chain along the temporal dimension. Neither side is complete on its own: a graph without a stream leaves the system unable to recover or be audited, and a stream without a graph leaves the system unable to be replaced or extended.

    3. Five Key Problems the Plugin Graph Must Solve

    A simple container that only knows “register and look up” cannot support production-grade requirements. A runtime container with real distinguishing power must handle the following five problems, which are usually treated in isolation.

    3.1 Capability Visibility: What a Plugin Can See from Where It Sits

    Different plugins should have different visibility over capabilities. A plugin in the core scope can see all registered capabilities; a plugin in a given session scope should only see the tools and models declared within that session. The usual implementation introduces the notion of a “scope”: when a plugin resolves a dependency, the resolver walks up the scope chain, returns on a hit, and keeps walking up on a miss. This avoids global namespace pollution and also makes “why is this tool not visible in the current session” an explainable question.

    Illustrative code:

    1. resolve(serviceName, scope):
    2. for s in scope.chain: # walk the scope chain from inner to outer
    3. if serviceName in s.providers:
    4. return s.providers[serviceName]
    5. return NOT_FOUND

    3.2 Lazy Dependency Activation: What If a Required Capability Is Not There Yet

    If the container requires that “dependencies must be ready before loading is allowed,” startup order becomes hard-coded and implicit temporal coupling forms between plugins. A more robust approach is declarative dependencies: a plugin only declares “I need a certain capability,” and the container takes responsibility for waiting. Once the capability appears, the waiting plugin is automatically woken up and completes initialization; when the capability disappears, the plugins depending on it are suspended or unloaded. This mechanism makes “the system degrades gracefully when an optional component is missing and fills itself in automatically once core components are in place” a natural outcome, rather than something piled up with large amounts of null checks.

    3.3 Multiple Implementations of the Same Capability and Scope Resolution

    Resolving the same capability name to different implementations in different scopes is a key design of this kind of framework. For example, a “storage service” may point to a persistent implementation in the global scope and to an in-memory implementation in a temporary session scope; a “model service” may bind to different models and different credentials in different sessions. The container must guarantee that resolution results are deterministic and traceable: given a plugin and a scope, the resolution path is unique and can be recorded in logs, which makes it easier to investigate “why was this implementation used.”

    3.4 Lifecycle and Resource Cleanup: Who Rolls Back Registrations

    Cleanup when a plugin exits is the most underestimated part. Over its lifetime a plugin may have registered services, subscribed to events, spawned child processes, opened file handles, and created timers. If the plugin is left to clean up each item itself, omissions are almost inevitable. A sound design assigns cleanup responsibility to the container: when a plugin registers any resource, it also registers the corresponding release action, and on unload the container executes them all in reverse registration order. This makes “unload means clean” a structural guarantee rather than something that depends on developer discipline.

    1. onDispose(plugin):
    2. for entry in reverse(plugin.registeredEntries):
    3. entry.release() # unregister services, unbind listeners, terminate processes, close handles
    4. removeFromGraph(plugin)

    3.5 Projecting Static Configuration into a Runtime Plugin Tree

    A configuration file is a static declaration, while the runtime needs a plugin tree that can be updated and inspected. The container must perform a projection: read the configuration, instantiate plugins, establish dependency edges, and form a tree structure. Afterward, configuration changes can be projected again to produce a diff and apply it incrementally. Inspectable means the tree can be fully exported: the state of every node, whether its dependencies are satisfied, and the scope it belongs to are all visible. This capability directly determines the framework’s observability and debuggability.

    4. The Event Stream: The Carrier of Historical Continuity

    The key design point of the event stream is “append-only.” Every state change is expressed as a new event instead of a modification to an old record. Three direct benefits follow.

    Context projection can be rebuilt. What is sent to the model is not a string rewritten over and over, but a result projected from the event stream according to rules. Changing the projection rules (for example, a truncation policy or a summarization policy) requires no changes to the historical data.

    Compaction and summarization stay traceable. When history grows too long, a “summary event” can be appended and the covered range replaced by the summary during projection. The original events remain, so auditing and retrospection are unaffected.

    Recovery and forking become first-class capabilities. After a process restart, replaying the event stream restores the point of interruption; deriving a new branch from any event position yields an experiment in “what if a different path had been chosen then.” Neither requires copy-pasting session state.

    An event entry usually contains a sequence number, a type, a timestamp, the owning session identifier, a payload, and optional causal references (for example, which call produced a given tool result). Causal references make a trace graph possible rather than only a linear log.

    5. The Agent Loop as the Bridge Layer

    The responsibility of the loop body should be strictly limited to “resolve capabilities, write events,” with no assembly logic inside:

    1. loop(session):
    2. services = graph.resolveFor(session.scope) # model, tools, prompt, session
    3. while not session.finished:
    4. prompt = services.prompt.build(session.projection())
    5. resp = services.model.call(prompt, services.tools.specs())
    6. session.append(Event.ModelResponse(resp))
    7. for call in resp.toolCalls:
    8. if services.policy.needsApproval(call):
    9. session.append(Event.ApprovalRequested(call)); continue
    10. result = services.tools.execute(call, services.sandbox)
    11. session.append(Event.ToolResult(call.id, result))

    The value of writing it this way: replacing the model only requires changing a variable binding; adding approval only requires inserting a policy service; switching sandboxes only requires swapping the executor. The loop body itself stays stable, and all complexity is pushed down into the plugin graph.

    6. Productization Checklist: How the Two Systems Cover Combinatorial Complexity

    Mapping the mechanisms above against product requirements yields a clear correspondence:

    • Models and credentials → model adapter plugins plus a scoped model service;
    • Session recovery and compaction → event stream replay plus summary events;
    • Tool policy and approval → a policy service plus approval events;
    • Sandbox and remote execution → executor plugins, swapped per scope;
    • Multiple hosts and interface observation → the interface subscribes to the event stream without intruding on the loop;
    • Sub-agents → derived scopes and independent event streams, with the parent referencing their results;
    • Plugin start and stop → lazy dependency activation plus reverse-order cleanup.

    7. Implementation Advice and Common Pitfalls

    First, do not write cleanup logic back inside plugins; insist on unified reclamation by the container, otherwise leaks are inevitable over long-running operation. Second, do not allow events to be modified in place; once rewriting is allowed, “recoverable” and “auditable” fail at the same time. Third, scope chain resolution must be traceable; writing the resolution path into logs saves a great deal of production troubleshooting time. Fourth, configuration projection should support diff output, so that “what changed and which nodes are affected” becomes an answerable question. Fifth, keep the loop body thin; any change of the “let me just initialize this here while I’m at it” kind turns into architectural debt half a year later.

    8. Conclusion

    The real barrier of a plugin-based framework is not the number of plugins, but whether one unified mechanism can answer five assembly questions and one history question at the same time. The runtime plugin graph handles spatial assembly and reclamation, the append-only event stream handles temporal causality and recovery, and the agent loop only bridges the two. Understanding this division of labor captures the main body of such an architecture, and provides the basis for judging how to compose general-purpose capabilities such as model services, storage, containers, and monitoring and alerting on demand in environments like Baidu AI Cloud to build your own agent runtime.