Agent Runtime Architecture: Plugin Graphs and Event Streams for Long-Running Systems

    Long-running agent products often fail at composition rather than at a single model call. This article describes an architecture that separates two concerns: a runtime plugin graph that defines what the system is made of, and an append-only event stream that records what happened during a task. It covers unified registration and lifecycle management across tools, models, prompts, storage, sandboxes, interfaces, and run modes; scope resolution; readiness and teardown; failure handling; event projections for model context, UI, recovery, and forks; the thin loop between graph and stream; host plugins; observability; and a review checklist. The goal is an agent runtime that is easier to replace, recover, audit, and operate.

    When an agent product becomes a long-running system, the hard part is usually not a single model call. The hard part is composition. Model adapters, system prompts, tool catalogs, session storage, execution sandboxes, human interfaces, subtask delegation, and multiple run modes can all become difficult to start, stop, recover, and explain if they are hard-coded into the main loop. A more robust approach separates two running lines: what the system is made of now, and what happened during the current piece of work.

    Why the minimal loop is not enough

    A minimal agent loop does four things: assemble context, request the model, execute tools according to an agreement, and send results back to the model until the task ends or a turn limit is reached. That can demonstrate capability, but it cannot explain product-level questions:

    • How do credentials switch by environment?
    • How are long sessions compacted without losing key facts?
    • How are dangerous tools approved?
    • How is execution confined to an isolated environment?
    • How does the same logic run in a CLI, a service process, and a web interface?
    • How does work resume from a consistent state after an interruption?
    • How do operators see the same facts as the model instead of a separate post-hoc log?

    The foundation therefore needs to answer two kinds of questions at the same time. The first is structural: which capabilities are enabled, what do they depend on, in which scope do they take effect, and who releases registrations, listeners, and external handles when they are shut down. The second is historical: which inputs, decisions, tool calls, and errors actually occurred during a task, and how can those records be projected into model context, UI traces, and the data needed for recovery or forking.

    The former is a good fit for a runtime plugin graph. The latter is a good fit for an append-only event stream. The loop sits between them: it asks the graph for models, tools, prompts, and session services, and writes execution back to the event stream.

    One composition mechanism for more than tools

    Having many plugins is not the differentiator. What matters is that tools, model adapters, prompt templates, storage, sandbox policies, interface adapters, and even run modes all use the same registration, dependency, and lifecycle mechanism as much as possible. Tools should not use one plugin system while everything else is scattered across conditional branches.

    Run modes can be understood as different cuts of the same graph. An execution-oriented mode tightens tools and context. A planning-oriented mode keeps more intermediate reasoning. An interactive mode strengthens approvals and observable output. The mode itself should also be a mountable unit, not a global switch inside the main program.

    This unification brings three direct benefits. Replacing an implementation does not require changing the loop. Disabling a capability for an environment can make dependent units refuse to start instead of failing halfway through a run. Reviewing the system can produce a list of capabilities that are actually active at the moment, instead of requiring a reading of all source code and a guess.

    Five problems a graph must solve

    A runtime graph has to solve several problems at once.

    Visibility. A plugin should only see capabilities explicitly exposed at its position. It should not be able to grab global singletons freely. Visibility boundaries serve both security and testing: a UI plugin should not directly hold model credentials, and a tool plugin should not rewrite another session’s storage.

    Readiness. When a required capability is not present, a plugin should wait or refuse to start and report the missing dependency, rather than running with an empty object. Startup order should therefore be determined by dependencies, not by the accidental line order of a configuration file.

    Scope resolution. The same service name may resolve to different implementations in different sessions, users, or tasks. For example, a model router may point to an internal inference service in an internal environment and to a different quota and audit policy in a restricted environment. File execution may resolve to a local sandbox or to an isolated remote job. The caller depends only on the service name and contract.

    Teardown. When a plugin stops, registrations, event listeners, child processes, temporary directories, and network handles must be reclaimed through a unified lifecycle. Missing any category can appear in a long-running process as handle exhaustion, duplicate callbacks, or tools from a previous task being exposed to the next one.

    Configuration to runtime graph. At startup, do not instantiate a fixed application directly. Read base configuration and feature bundles, then apply environment or user patches. A loader should mount configuration rows as plugin instances, forming a tree that can be updated and inspected. The smallest unit of hot update should be a subtree remount, not a restart of the whole process in the hope that it works.

    The following sketch describes this graph. It is not an interface from a specific product; it only shows the relationships:

    1. profile + bundles + patches
    2. │
    3. ▼
    4. loader.mount(row) → plugin instance
    5. │
    6. ├─ provides: service(name, scope)
    7. ├─ requires: service(name)
    8. ├─ onStart / onStop
    9. └─ children: nested plugins

    When inspecting the runtime graph, it should be possible to answer: who provides a service, what scope is active, whether dependencies are satisfied, and what the stop order is. If those questions cannot be answered, the plugin system is only dynamic import.

    Scopes and same-name services

    Scopes should not be arbitrary string labels. They should correspond to real isolation boundaries. Common boundaries include:

    • Process level: credentials and model adapters.
    • Tenant or user level: quota and approval policy.
    • Session level: tool permissions and memory.
    • Task level: temporary directories for a single subagent.

    Resolution rules should be stable and testable: search upward from the current task, use the first implementation that satisfies the contract, and do not peek downward across sessions.

    Different implementations under the same name must be compatible at the contract level. A contract should include at least input and output, error categories, whether side effects occur, timeout, and idempotency semantics. If two “search” services are one read-only service and one service that mutates external systems, they should not share a service name. Scope answers which one to use; contract answers whether it can be replaced.

    A subagent is better represented as a subgraph with an independent scope than as a copy of an entire process. The parent graph provides shared models and auditing. The child graph narrows the tool set and file root, and writes subtask events back to the same correlated event stream. Parent and child are connected by causal identifiers, not implicit global variables.

    Lifecycle and failure strategy

    A recommended mount order is: validate configuration, create instances, resolve dependencies, run start hooks, and publish services. The unmount order is the reverse: stop accepting new calls, wait for or cancel in-flight work, run stop hooks, unregister services, and release external resources. If startup fails, already-started sibling nodes should be rolled back so that a half-built graph is not left behind.

    Missing dependencies, contract mismatches, and scope conflicts are startup-time errors. They should fail fast and point to the configuration row. Tool timeouts, model rate limits, and sandbox denials are runtime errors. They should be written to the event stream, and the loop should decide whether to retry, ask a human, or terminate. Do not mix these two classes into a single exception that is thrown upward.

    Cleanup must cover four resource classes: in-memory registries and listeners, processes and containers, files and temporary credentials, and external subscriptions or callbacks. Tests should at least construct two paths: start successfully and immediately unmount, and cancel halfway through execution. Only when these pass is the lifecycle more than documentation.

    Event streams are responsible for continuity

    The plugin graph describes composition. It is not responsible for remembering the process. A session should maintain an append-only event stream: user input, system injection, model responses, tool requests and results, approval decisions, errors, and compaction markers. Events are appended, not rewritten in place. When history needs correction, append a compensating or branch event instead of erasing the old record.

    Projections are read-only derivations. The model context projection selects, truncates, and compacts so that goals, constraints, and key tool results remain in the window. The UI projection provides a timeline, diffs, and pending approvals. The recovery projection rebuilds in-memory state from a sequence number. The fork projection copies the references needed after a given event as a root, rather than copying the entire process. If multiple projections each write their own truth, the UI, recovery, and model context will diverge. The event stream should be the single source of truth, and projections should be rebuildable.

    Compaction is a projection policy, not event deletion. Raw events remain available for auditing and replay. The model receives a summarized view, and the event stream records where the compaction came from and what the summary is, so that constraints can be checked later.

    How the loop sits between the two lines

    Each loop round should be fixed: resolve the model, prompt assembler, and allowed tool catalog from the current scope; project the current context from the event stream; call the model; if tools are needed, pass through policy and approval, then enter a sandbox or remote execution; whether the result is success, refusal, or failure, write the event first and then decide whether to continue, wait for a human, or finish. The loop does not hold business truth. It holds only control state for the current round, such as turn count, cancellation flag, and pending approval. After a process crash, recovery can use the event stream plus the still-valid plugin graph instead of relying on a half-finished conversation in memory.

    Tool policy belongs to a service on the graph: it decides visible tools by scope, validates parameters, and determines whether human confirmation is required. The executor is also a service: a local sandbox, a remote job, or a read-only simulation can be substituted, and the loop only sees “execute this call and return the result.” Extracting policy and execution from the loop keeps the loop short and testable.

    Multiple hosts and observability

    A CLI, a background service, and a web interface should be host plugins on the graph, subscribing to different projections of the same event stream. The interface must not keep a private copy of state that is inconsistent with the event stream; otherwise the approvals users see and the tools the model actually executes will not match. Metrics and logs should also be derived from events and lifecycle hooks. Mount failures, dependency waits, tool refusals, sandbox timeouts, and context compaction counts are operational signals, not things to guess afterward from text logs with regular expressions.

    Object storage can hold large tool outputs and snapshots. Message queues can carry cross-process cancellation and approvals. Container platforms can host isolated execution. Logging and monitoring systems handle retention and alerting. These are general infrastructure categories. The foundation depends on capabilities such as appendability, sequence-based reads, isolated execution, and reclaimability, not on binding to one specific implementation.

    A checklist for implementation

    Design reviews can use the following questions instead of piling up feature lists:

    • Can current capabilities be exported as an inspectable graph, rather than existing only in startup scripts?
    • When a dependency is missing, does the system refuse to start or continue with an empty implementation?
    • Does a same-name service always resolve to the expected implementation in two different sessions?
    • After unmount, are registries, listeners, processes, and temporary files all gone?
    • Can model context and the UI be rebuilt by replaying the event stream alone, without relying on memory?
    • Does compaction preserve raw events and the source of each summary?
    • If cancellation occurs midway through tool execution, does the event stream leave an explainable terminal state?
    • Do subtasks have narrower scopes, and can their results be correlated back to the parent task?

    If most of these questions cannot be answered clearly, prioritize the runtime graph and event stream instead of adding more branches to the loop. Agent differentiation will show up in models and tools, but operability comes from composition. The graph answers what the system is now. The event stream answers what the system just did. The loop is only the thin, strict scheduler between them.