Multi-Mode Agent Runtime Architecture: From Startup Flow to Multi-Agent Extension
This article explains how to design a scalable runtime for agents used in developer tools, automation systems, and enterprise assistants. It covers why startup logic, mode handling, and main loops become hard to maintain as features grow, and how to address these problems through layered startup, separated state, explicit session contracts, a state-machine main loop, enforced permissions, a unified task model, role-based multi-agent design, stable extension protocols, and observability.
In developer tools, automation operations, and enterprise assistants, agents often follow a similar path of growth. At first, there is a single chat entry point and one or two tools, with a simple main loop and a clear call path. Then file reading and writing, command execution, code analysis, knowledge retrieval, background tasks, permission approval, and multiple run modes get added one by one. The system soon develops structural problems.
The most common symptoms include:
- The startup function takes on too many responsibilities. It parses arguments and also initializes the model, tools, sessions, and logging.
- Interactive mode, headless mode, and remote invocation mode each maintain their own run logic.
- Tools share a large amount of implicit state, so adding a new tool can affect existing capabilities.
- Foreground sessions and background tasks compete for resources, and cancellation, timeout, and recovery logic become tangled together.
- After multiple agents are integrated, the main loop fills with conditional branches.
- Permission control depends on prompts or informal team conventions, so there is no reliable security boundary.
On the surface, these problems look like code complexity. The underlying cause is that the runtime lacks clear layering. For a mature agent system, the core competitive advantage is not only the quality of model answers. It is also the system’s ability to sustain tools, tasks, permissions, state, and extension mechanisms over time.
The rest of this article starts with the startup flow and walks through how an extensible agent runtime should be designed.
1. The Entry Layer Should Decide What to Run, Not Start Everything Immediately
Many programs initialize every component during startup. They load the model client, open database connections, register all tools, and create background threads, and only then check which mode is active. This approach speeds up early development, but it raises startup cost, blurs mode boundaries, and makes components that the current run does not need take part in it anyway.
A more reliable approach splits startup into three stages:
- Entry identification
- Process-level initialization
- Session-level assembly
The entry identification stage answers a few questions:
- Is this an interactive session or a headless task?
- Does it need to restore a previous session?
- Should it start a background task or remote execution?
- Is it a test, diagnostic, or lightweight command path?
- What permissions and resource boundaries does the caller have?
This stage should not load the full agent. Its job is to determine the run context and choose an assembly plan for the rest of startup.
The structure can be represented as follows:
Entry point├── Parse arguments and environment├── Identify run mode├── Build process-level context└── Assemble session runtime based on mode├── Interactive session├── Headless task├── Background task└── Session restore
This design matters because the run mode is determined early, not discovered deep inside the system. The earlier the mode is fixed, the less likely different entry points are to evolve into several incompatible agents.
2. Process-Level Infrastructure Must Be Separated from Session Semantics
Startup usually handles two kinds of state.
The first kind is process-level state, including:
- global configuration;
- logging and monitoring;
- telemetry switches;
- temporary directories;
- exit cleanup callbacks;
- network connection pools;
- unified error handling;
- resource limits and signal handling.
The second kind is session-level state, including:
- the current working directory;
- conversation history;
- the current task goal;
- authorized tools;
- the current model context;
- tool call results;
- session variables;
- the identity and responsibilities of the current agent.
When these two kinds of state are mixed, subtle problems follow. For example, if one session changes the working directory, other sessions may be affected. If a background task modifies global configuration, a foreground interactive session may then behave unpredictably.
For this reason, the runtime context should separate the two clearly:
ProcessContext├── Global configuration├── Logging system├── Monitoring system├── Connection pools└── Process lifecycle managementSessionContext├── Session ID├── User and permissions├── Working directory├── Conversation state├── Tool registry└── Task cancellation signal
Process-level objects can be shared across sessions, but session-level objects need explicit isolation boundaries. In systems that run concurrently, it also helps to separate read-only shared resources from mutable session state. This avoids a heavy reliance on mutable global variables.
3. Session Assembly Establishes a Runtime Contract, Not Just Object Creation
After the run mode is determined, the system moves into session assembly. This stage should do more than call a constructor. It should establish an explicit runtime contract.
A complete session needs at least the following decisions.
1. Model Access Policy
This covers the model client, context length policy, retry mechanism, timeout mechanism, and the fallback behavior when the model is unavailable. Model calls should not be scattered across individual tools or agents. A unified model access layer should handle them.
2. Tool Set
Tools should be registered dynamically based on the current mode and permissions, rather than exposing every capability unconditionally. For example, a headless task may only be allowed to read and analyze, while an interactive session may execute modifications only after approval.
3. State Storage
The system needs to define which information stays in memory and which must be persisted. Short-term reasoning state can remain in memory. Session summaries, task progress, and key operation records can be written to persistent storage.
4. Interaction Adapters
Interactive mode handles user input, streaming output, confirmation prompts, and interrupt signals. Headless mode focuses on structured results, exit codes, and logs. For this reason, the interaction layer should not be embedded directly in the core reasoning loop. It should provide input and output capabilities through adapters.
5. Cancellation and Timeout Control
Each session should have its own cancellation signal. Tool calls, model requests, and subtasks all need to respond to cancellation. Otherwise, even after the user stops a task, the underlying work may keep consuming resources.
4. The Core of the Main Loop Is Driving State Transitions, Not Just Continuous Dialogue
An agent’s main loop is easy to write as one continuous sequence:
Read user inputCall modelExecute toolPass result to modelCall model againOutput final answer
This representation works for explaining the concept, but it does not support a complex system well. In an engineering implementation, the main loop should be treated as a state machine.
A simplified set of states could be:
Idle↓Planning↓WaitingForApproval↓ExecutingTool↓ObservingResult↓Completed / Failed / Cancelled
Each model output, tool return, user confirmation, or system interrupt triggers a state transition. This has several clear benefits:
- Each step can be recorded.
- Execution can resume after an interruption.
- Different states can enforce different permissions.
- Timeouts, failures, and retries can be handled consistently.
- Background tasks can report progress.
- Boundary conditions are easier to test.
A state machine does not require a complex framework. What matters is that states and events exist explicitly, rather than being hidden in a long chain of conditional checks.
5. The Tool System Needs Clear Boundaries, Descriptions, and Lifecycles
Tools are the main source of agent capability, and they are also where complexity most easily gets out of control. A mature tool system should record at least the following information:
- the tool name and purpose;
- the input parameter schema;
- parameter validation rules;
- required permissions;
- whether concurrent execution is allowed;
- whether it has side effects;
- timeout;
- whether it can be retried;
- output structure;
- audit information.
It is especially important to distinguish read-only tools from tools that produce side effects.
Reading files, analyzing text, and querying status can usually run with lower permissions. Modifying files, executing commands, and submitting changes need stricter approval, sandboxing, or resource limits.
The tool call flow can be summarized as follows:
Model proposes a call↓Validate parameters↓Check permissions↓Assess risk↓User confirmation or policy approval↓Execute tool↓Record result and audit event
Do not leave permission decisions to the model. Prompts can help the model understand the rules, but they cannot replace enforcement in the runtime. Real security boundaries must be enforced by code, the execution environment, and resource policies together.
6. Foreground Sessions and Background Tasks Should Share a Unified Task Model
When foreground interaction and background execution use two different task abstractions, the system gradually accumulates duplicate logic. One abstraction handles progress, another handles retries, and a third handles cancellation. Eventually, managing them as a whole becomes difficult.
A better approach is to build a unified task model:
Task├── taskId├── parentTaskId├── status├── priority├── input├── output├── cancellation├── timeout└── event stream
A foreground session simply subscribes to task events in real time. A background task writes its events to persistent storage, and other clients can subscribe to them later if needed. This way, the interaction styles differ, but the task lifecycle stays the same.
Task states should distinguish at least:
- waiting to run;
- running;
- waiting for approval;
- paused;
- completed;
- failed;
- cancelled;
- expired.
A unified task model also makes it easier to implement queue scheduling, concurrency limits, and resource quotas. This prevents background tasks from growing without bound.
7. Multi-Agent Extension Depends on Role Isolation, Not Copied Main Loops
A multi-agent system is not just several identical instances started at once. The real work is defining role division, communication methods, and responsibility boundaries.
A robust design usually includes:
- Coordinator agent: understands the goal, splits tasks, and combines results.
- Analysis agent: handles retrieval, reading, and reasoning.
- Execution agent: calls tools with side effects.
- Validation agent: checks results, finds omissions, and verifies constraints.
- Domain agents: provide specialized strategies for specific tasks.
Each agent should have clearly defined:
- input format;
- output format;
- available tools;
- permission scope;
- maximum execution time;
- context boundaries;
- failure handling.
The coordinator should not hold permissions for every tool. Otherwise, it becomes another “super main loop.” A better approach is for the coordinator to call specialized roles through a task protocol:
Coordinator├── Create analysis task├── Wait for structured result├── Create execution task├── Request validation└── Assemble final output
Agents should communicate mainly through structured messages, rather than sharing large amounts of implicit context. The more context they share, the tighter the coupling becomes, and the harder debugging gets.
8. Extension Layers Should Rely on Stable Protocols Instead of Modifying the Core Loop
When a system needs to add a new agent, tool, or external task source, a common mistake is to modify the core main loop directly and add a special branch for each extension. This works in the short term, but over time it makes the core logic hard to maintain.
A better extension layer is built around stable protocols:
- agent registration protocol;
- tool description protocol;
- task submission protocol;
- event subscription protocol;
- permission declaration protocol;
- result return protocol;
- error and cancellation protocol.
The core runtime only needs to understand the protocols, not where each extension comes from. Extensions can be local modules, remote services, or separate processes, as long as they follow the shared conventions.
For example, an extension agent can be abstracted as:
register()→ Declare identity, capabilities, inputs, outputs, and permissionsinvoke(task)→ Receive a structured taskstream(event)→ Continuously send progress, requests, or intermediate resultscancel(taskId)→ Respond to a cancellation request
Once the protocols are stable, extension developers do not need to understand the internal details of the core loop, and the platform can add capabilities without changing the core code.
9. Observability Is a Debugging Foundation for Agents, Not an Add-On
Traditional applications can be debugged with request logs and error stack traces. An agent task, however, often includes multiple rounds of model calls, several tool executions, and several subtasks. Recording only the final result is far from enough.
At minimum, the system should record:
- session ID;
- task ID;
- agent role;
- state transitions;
- number of model calls;
- summaries of tool call parameters;
- tool execution duration;
- approval records;
- retry count;
- cancellation reason;
- final result and failure reason.
Sensitive information also needs to be redacted. User code, keys, and private content should not be written directly to logs.
Observability should also support product improvement. For example, when a certain type of task repeatedly goes through replanning, the context organization may have a problem. When a tool often times out, the tool or the scheduling policy may need optimization. When users frequently reject a certain type of permission request, the task breakdown or risk warnings may need work.
10. Principles Worth Adopting When Building Your Own Agent Platform
Based on the design above, several engineering principles are broadly applicable.
Principle 1: Determine the run mode first, then assemble the runtime
Do not let different entry points grow into separate systems. Mode identification should happen early in startup, and runtime assembly should be built around the detected mode.
Principle 2: Separate process-level resources from session-level state
Share stable resources, and isolate mutable state. Every state that can affect a user’s task should have a clear owner.
Principle 3: Design the main loop as a state machine
Make events, states, cancellation, failure, and recovery explicit. Avoid maintaining complex flows through nested conditional branches.
Principle 4: The runtime must enforce permissions
The model can suggest actions, but it cannot grant itself permissions. Tool calls must pass through policy checks, approval, and execution environment constraints.
Principle 5: Use a task model to unify foreground and background work
The interface is only one observer of a task. It should not determine the task’s lifecycle.
Principle 6: Coordinate multiple agents through protocols
Roles should have clear boundaries, communication should use structured messages, and extensions should depend on stable interfaces instead of copies of the main loop.
Principle 7: Use observability to support long-term evolution
Without event records, state tracking, and failure analysis, an agent system can only be maintained by guesswork.
Conclusion: The Ceiling of an Agent Is Set by Its Runtime
When an agent moves from a demo to a production system, the main additions are not a few more prompts. They are mode management, permission control, task scheduling, state persistence, tool governance, concurrency isolation, and extension protocols.
So when designing an agent, the question is not only whether the model can complete the task. Teams also need to ask:
- How does a task start and resume?
- How should the system retry after a tool failure?
- How does the user interrupt a task?
- How are multiple tasks isolated from each other?
- How is permission enforced?
- Does adding a new agent require changes to core code?
- How can the system explain a wrong decision?
- As the scale grows, which resources will become bottlenecks?
If these questions can only be answered with prompts, global variables, and informal conventions, the system will soon lose control. By formalizing the startup flow, session context, task state, tool permissions, and extension protocols, the agent can keep growing in capability while its structure stays stable.
This is the most useful direction for building enterprise AI applications. The model handles reasoning, the runtime enforces order, the extension layer supports growth, and the observability system keeps the whole system explainable, maintainable, and able to evolve.
