Agent Runtime Architecture: From Startup Routing to Multi-Agent Scaling
A well-behaved agent demo can fall apart in production as the main loop bloats, tools pollute each other's state, background tasks interfere with foreground sessions, and extensions become a pile of special cases. This article examines the root cause—unclear runtime boundaries—and walks through a layered runtime architecture: startup routing and deferred loading, process-level initialization, session assembly, host decoupling, declarative tool registration with pre-dispatch permission checks, a thin main loop, and isolation between background tasks and foreground sessions. It explains how these boundaries keep an agent system maintainable as it grows.
1. Where Agents Start to Fall Apart
In the demo stage, an agent typically consists of one model, two or three tools, and a loop—and it works fine. Once it enters real-world scenarios, problems emerge along several paths at once:
- The main loop keeps growing. Every new mode or edge case adds another conditional branch to the loop. Eventually the loop handles scheduling, fallbacks, retries, and UI output all at once.
- Tools pollute each other. Tools share global state. If one tool changes the working directory or environment variables, another tool’s results become unpredictable.
- Foreground and background interfere with each other. Background tasks and the user’s active session share the same mutable state, leading to race conditions and conflicting writes.
- Extension becomes a collection of special cases. When a new capability is added, the team inserts a conditional branch into the core code, and the extension points lose their boundaries.
The common root of these problems is that runtime responsibility boundaries were never drawn clearly early on. Model capability determines what an agent can do; the runtime determines whether the system is still maintainable six months later. Two systems built on the same model can have dramatically different lifespans, and the difference usually lies in the runtime.
2. The Startup Layer: Route First, Then Assemble, Then Enter the Session
The startup phase is the most easily overlooked, yet it determines whether each host type grows its own private semantics. A mature agent typically supports interactive local use, headless execution, SDK invocation, remote access, background session management, and session resumption. If each of these entry points spins up its own runtime, the system quickly fractures into several behaviorally inconsistent versions.
A more robust approach is to split startup into three stages.
2.1 Entry Routing
The entry layer only determines which execution mode this launch belongs to and decides which modules need to be loaded. Lightweight requests such as version queries or configuration checks should go straight through a fast path, without loading the model client or the tool registry.
main(args):mode = classify(args) # interactive | headless | sdk | remote | background | fastif mode == FAST:return run_fast_path(args)runtime = load_runtime_for(mode) # load dynamically on demandreturn runtime.start()
The value of dynamic loading is controlling startup cost. Each module class only enters memory when needed, so startup time decouples from the number of features.
2.2 Process-Level Initialization
This layer handles the execution environment: reading global configuration, initializing telemetry, fetching remote settings, and registering cleanup callbacks for process exit. Its key constraint is that it must not touch session-specific semantics. Process-level state describes only “how this machine runs,” not “what state this conversation is in.” Once the two are mixed together, implementing session resumption or parallel multi-session support later becomes extremely difficult.
2.3 Session Assembly
Only at this stage does the system begin assembling the objects a session needs: permission policies, context sources, the tool registry, and the model adapter. The result of assembly is an explicit session object, and all subsequent logic revolves around it.
3. Decoupling Sessions from Hosts
Different hosts have very different I/O requirements. Terminals need character-by-character rendering, headless mode needs structured output, and remote access needs disconnect-reconnect support. If the core logic is directly aware of these differences, the core code must change every time a new host is added.
The correct boundary is: hosts are responsible only for I/O adaptation, and the core runtime accepts only a unified session interface.
interface Session:submit(user_input) # submit one turn of inputsubscribe(event_type, handler) # subscribe to events: text deltas, tool calls, permission requests, completioncancel()snapshot() -> SessionState # for resumption and migrationterminal_host -> renders events into a UIheadless_host -> writes events to structured logs or standard outputremote_host -> sends events to clients; can restore from snapshot after disconnection
The session thus becomes the single carrier of state. Hosts can be swapped out while session semantics remain stable. Resumption relies on the snapshot, with no need to guess internal state.
4. The Tool Layer: Declarative Registration and Upfront Permissions
As the number of tools grows, the main risks come from two places: invisible side effects between tools, and permission checks scattered inside each tool’s implementation.
Each tool should carry a unified declaration containing at least the following:
- Name and purpose description, so the model can judge when to call it;
- Structured parameter descriptions, used for validation before invocation;
- Side-effect level, such as read-only, writes local files, accesses the network, or executes arbitrary commands;
- Concurrency properties, indicating whether it can run alongside other tools;
- Default permission requirements.
ToolSpec:name: "read_file"params: { path: string }effect: READ_ONLYconcurrency: SAFEpermission: AUTOToolSpec:name: "run_command"params: { cmd: string }effect: EXECUTEconcurrency: EXCLUSIVEpermission: ASK_USER
Permission decisions should be made centrally before dispatch. The dispatcher reads the tool declarations and the current policy, then decides whether to execute directly, request confirmation, or reject. Tool implementations need no knowledge of policy details, so permission rules can evolve independently. All decisions pass through a single exit point, which also makes auditing easier.
5. Keep the Main Loop Thin
The main loop does only four things: call the model, dispatch tool calls, update session state, and evaluate termination conditions. Capabilities such as context compression, logging, interrupt handling, and progress display are attached through event hooks rather than written into the loop body.
loop(session):while not session.done():response = session.model.call(session.context())emit(TEXT_DELTA, response)for call in response.tool_calls:decision = policy.check(call, session)result = dispatch(call, decision)session.append(result)emit(TOOL_RESULT, result)session.apply_hooks(AFTER_TURN)
The thinner the loop, the lower the cost of adding new capabilities, and the more concentrated error localization becomes. To decide where a requirement belongs, first ask whether it changes the loop’s scheduling logic. If it does not, it should exist as a hook or plugin.
6. Isolating Background Tasks from Foreground Sessions
Background tasks are typically long-running builds, indexing jobs, tests, or data synchronization. Their conflicts with foreground sessions mainly stem from shared mutable state.
