Agent Startup Architecture and Multi-Agent Extension Design
This article outlines a runtime architecture for Agents that begins with launch-mode routing and process initialization, moves into explicit session assembly, and then applies controlled tool execution, layered permissions, structured multi-agent protocols, and observable task scheduling. It distills engineering principles for building maintainable and extensible Agent systems.
Agent Startup Architecture and Multi-Agent Extension Design
Over time, the evolution path of Agent systems has often looked highly similar: at first there is only a single dialogue loop that receives user input, calls the model, executes tools, and returns the result. The codebase is small, and debugging is direct.
But once the system gradually adds file operations, command execution, code search, background tasks, session recovery, permission approval, remote access, and multi-agent collaboration, the real difficulty appears. The problem is usually not that an individual tool is poorly implemented. It is that the runtime as a whole lacks clear boundaries:
- The startup entry begins to take on every responsibility.
- Different operating modes each maintain their own context.
- Tool calls directly modify global state.
- Foreground sessions and background tasks interfere with each other.
- Permission checks are scattered across business code.
- Extension modules are integrated through numerous special cases.
- When something goes wrong, it is impossible to tell whether the model, a tool, permissions, or the scheduler caused it.
Therefore, the key to building a long-term maintainable Agent is not to keep stacking features, but to first design a runtime architecture that can absorb complexity. Using general intelligent coding tools and enterprise Agents as the background, this article breaks down a relatively robust design path: starting from process launch, moving through operating-mode identification and environment initialization, then into session assembly, and finally reaching the tool execution and multi-agent extension layer.
1. Core Tasks of the Startup Layer: Identify Boundaries Before Creating the Runtime
Many projects complete configuration reading, model initialization, tool registration, session creation, and task execution directly in the entry function. This approach is highly efficient at the prototype stage, but it gradually turns the entry point into a “system manager.” Every new feature requires modifying the entry point, and every operating mode requires adding conditional branches.
A more reliable approach is to divide the startup process into three stages:
- Entry routing: determine which operating mode the current request belongs to.
- Process-level initialization: load infrastructure related to the process lifecycle.
- Session-level assembly: create an independent runtime context for the current task.
This can be abstracted as:
Start process├─ Parse basic arguments├─ Identify operating mode├─ Initialize process-level facilities├─ Construct session context├─ Assemble tools and permission policies└─ Enter the corresponding execution loop
The most important principle here is: the startup layer is only responsible for deciding “how to run,” not for deciding “how a specific task is completed.”
For example, local interactive mode requires input/output handling, terminal rendering, and a persistent session; headless mode may only need to read a task, execute the workflow, and output structured results; background mode focuses more on task state, cancellation mechanisms, and recovery capabilities. They can reuse lower-level capabilities, but they should not share an identical execution loop.
2. Entry Routing: Avoid a Fragile Shared Path for All Modes
An Agent usually has at least the following operating forms:
- Interactive sessions
- Single-task execution
- Batch or automated invocation
- Background tasks
- Session recovery
- Remote request access
- Multi-agent internal calls
If all modes enter the same super-loop, the system can easily develop semantic confusion. For example, an interactive session allows the user to confirm midway, while an automated task may require unattended operation; a foreground task can directly output process information, while a background task needs to persist state; a recovered session needs to load historical context, but a new session should not inherit temporary state from an old task.
Therefore, entry routing is not merely a performance optimization. It is runtime semantic isolation.
Mode identification can be abstracted into an immutable launch description:
LaunchSpec├─ mode├─ inputSource├─ outputPolicy├─ sessionPolicy├─ permissionPolicy└─ lifecyclePolicy
Downstream components depend only on this description and no longer repeatedly read command-line arguments, environment variables, or global flags. This has three benefits.
First, the operating mode is determined early in the system, so it does not keep branching deep inside business code.
Second, different entry points can reuse the same session constructor without duplicating the entire initialization logic.
Third, tests can directly construct different launch descriptions to verify runtime behavior without relying on a real terminal or external environment.
3. Process-Level and Session-Level Initialization Must Be Separated
A mature Agent system usually contains two types of state at the same time.
1. Process-level state
The lifecycle of process-level state usually covers the entire program run, for example:
- Configuration file loaders
- Logging and metrics facilities
- Telemetry switches
- Signal handling
- Exit cleanup logic
- Connection pools or shared caches
- Global resource limits
- External configuration refresh mechanisms
These facilities are suitable for creation early in startup, but they should not directly carry the task state of a specific session.
2. Session-level state
Session-level state belongs only to one specific task or a group of related tasks, for example:
- The current working directory
- Conversation history
- The current task objective
- Tool call records
- Authorization results
- Temporary files
- The current Agent role
- Interruption and recovery information
Mixing the two creates very subtle problems. For example, one session changes the working directory, but another session unexpectedly inherits it; a permission approval is cached as a global result, causing subsequent tasks to be incorrectly allowed; context written by a background task pollutes the foreground conversation.
Therefore, it is advisable to distinguish them explicitly:
ProcessRuntime├─ ConfigService├─ Logger├─ Metrics├─ ResourceManager└─ ShutdownManagerSessionRuntime├─ SessionState├─ ContextManager├─ ToolExecutor├─ PermissionEvaluator└─ ConversationLoop
Process-level objects can be shared by multiple sessions, but session-level state must have clear ownership. What is shared is capability; unconstrained mutable state should not be shared.
4. Session Assembly: Make Runtime Context an Explicit Object
Many problems in Agent systems come from context not being explicitly modeled. Engineering code often contains many implicit dependencies: a function reads the current directory by default, a tool uses a global permission object by default, or an extension obtains a task identifier from environment variables by default.
A more maintainable approach is to define an explicit session context:
SessionContext├─ sessionId├─ parentSessionId├─ workspace├─ task├─ modelPolicy├─ toolRegistry├─ permissionPolicy├─ cancellationToken├─ eventSink└─ persistenceAdapter
Several fields are especially important.
Session identity
Each session should have a unique identifier and support parent-child relationships. This makes it possible to track multiple subtasks derived from one user request and also helps with log correlation, state recovery, and problem diagnosis.
Workspace
The workspace should not be merely a string path. It should also include read/write scope, temporary directories, resource limits, and information about whether access to the external environment is allowed.
Cancellation token
Model calls, tool execution, and subtask scheduling can all be time-consuming. Without a unified cancellation mechanism, the underlying task may continue modifying files or executing commands after the user clicks stop. The cancellation token should run through the entire call chain, and tool implementations must actively respond to it.
Event output
Sessions should not depend directly on terminal output internally. A better approach is to produce structured events, for example:
TaskStartedModelThinkingToolRequestedPermissionRequiredToolCompletedTaskPausedTaskFinishedTaskFailed
An interactive interface can render events as text, background mode can write events to logs or a message queue, and remote calls can convert them into streaming responses. In this way, execution logic and presentation logic are not bound to each other.
5. Tool Layer Design: Tools Are Controlled Capabilities, Not a Collection of Functions
The tool layer is often where Agent extensions most easily get out of control. An early implementation may simply be a mapping table:
toolName -> function
But once the system enters production, tool calls need to consider at least:
- Parameter validation
- Permission checks
- Timeout control
- Concurrency limits
- Resource quotas
- Output truncation
- Retry policies
- Audit records
- Error classification
- Cancellability
Therefore, a tool is better modeled as a capability object with metadata:
ToolDefinition├─ name├─ description├─ inputSchema├─ outputSchema├─ riskLevel├─ requiredPermissions├─ timeoutPolicy├─ concurrencyPolicy└─ executor
The model can only submit a call request; it cannot directly gain execution authority. The complete flow should be:
Model submits request→ Parameter validation→ Permission evaluation→ Risk confirmation→ Resource scheduling→ Tool execution→ Result normalization→ Audit logging→ Return to model
This flow separates “the model’s intent” from “system execution.” The model can suggest deleting a file, but whether deletion is ultimately allowed should be decided by the permission policy and risk control layer. It cannot be guaranteed by the prompt alone.
6. Permission System: Do Not Put Security Boundaries in Prompts
Prompts can describe rules, but they cannot become the only security mechanism. The reason is simple: model output is probabilistic, tool arguments may be polluted by context, and external files may contain persuasive content.
Permission control should include at least three layers.
Layer 1: Capability-level permissions
Determine whether the current session has a certain type of capability, such as file reading, file writing, command execution, network access, or process management.
Layer 2: Resource-level permissions
Even if a session has file-writing capability, that does not mean it can write to any location. The system needs to further evaluate the path, file type, workspace scope, and sensitive directories.
Layer 3: Operation-level approval
High-risk operations require user confirmation or stricter policy evaluation. Examples include batch deletion, modifying critical configuration, accessing external networks, or executing irreversible operations.
A permission decision can be abstracted as:
Decision = Evaluate(session,tool,arguments,resource,policy)
The result should not be limited to allow and deny. It can also include:
- Allow execution
- Require user confirmation
- Allow but log
- Allow simulation only
- Deny with a reason
This design is not only safer, but also better for debugging and auditing.
7. Multi-Agent Extension: Control Complexity with Role Boundaries
Multi-agent systems are not simply about launching multiple model instances. The real difficulty is defining responsibilities, communication, and resource boundaries among them.
A scalable multi-agent system should at least clarify the following:
- What each Agent is responsible for
- Which tools it can call
- Which context it can read
- Which subtasks it can create
- How it reports to the parent task
- Who handles it after failure
- Whether it is allowed to modify shared resources
It is advisable to define an Agent as a constrained execution unit:
AgentProfile├─ role├─ objective├─ allowedTools├─ contextScope├─ outputContract├─ resourceLimits└─ failurePolicy
For example, a code analysis Agent can read the project and generate diagnostic results but has no write permission; a modification Agent can submit patches but cannot directly execute high-risk commands; a validation Agent can run tests, but its output should be returned as evidence rather than directly changing the task objective.
Collaboration among multiple agents should also not rely on a shared global conversation. A better approach is to use structured task protocols:
SubtaskRequest├─ taskId├─ objective├─ inputArtifacts├─ constraints└─ deadlineSubtaskResult├─ taskId├─ status├─ outputArtifacts├─ evidence└─ failureReason
This avoids unbounded context growth and gives every subtask clear input and output boundaries.
8. Background Tasks and Foreground Sessions: Share Scheduling Capabilities, Not Interaction State
Foreground sessions emphasize immediate feedback, while background tasks emphasize reliable execution. The two can reuse models, tools, and permission modules, but they should not share the same interaction state.
Background tasks additionally need:
- Persistent task state
- Recoverable execution
- Retries and backoff
- Progress events
- Timeout handling
- Idempotent design
- Failure alerts
- Resource quotas
A reasonable task state machine can be:
Created→ Queued→ Running→ WaitingApproval→ Paused→ Resumed→ Succeeded / Failed / Cancelled
State transitions must be controlled and cannot be directly modified by arbitrary tools. All state changes should produce events to support recovery, auditing, and monitoring.
9. Observability: Record the Decision Chain, Not Just Final Results
When an Agent system has problems, looking only at the final answer is usually not enough to locate the cause. The truly valuable diagnostic information includes:
- Which operating mode was used
- Where the session was created
- Which tool requests the model made
- Which requests were rejected
- What the permission decision was based on
- How long the tool actually executed
- How subtasks were derived
- At which stage a timeout occurred
- Which evidence supported the final result
Therefore, logs should be designed around the “decision chain” rather than only recording strings. It is advisable to associate the following identifiers with each execution:
traceIdsessionIdtaskIdparentTaskIdtoolCallId
At the same time, sensitive content should be redacted to avoid introducing new data leakage risks in the name of observability.
10. Engineering Principles Worth Adopting
The design above yields several principles applicable to self-built Agents.
1. Keep the entry thin and assembly explicit
The entry point is only responsible for routing and constructing the runtime. It should not carry specific business logic.
2. Lifecycles must be clear
Processes, sessions, tasks, tool calls, and sub-agents should have different lifecycles and should not all depend on global variables.
3. Separate capability from execution
The model can express intent, the policy layer decides whether to execute, and the tool layer performs the actual operation.
4. Integrate extensions through protocols
New tools and Agents should follow unified descriptions, unified events, unified errors, and unified permission protocols, avoiding special cases added to the main loop.
5. Share capabilities, not mutable state
Sharing model clients, logging facilities, and resource managers is usually reasonable; sharing task context, temporary authorization, and tool execution state requires caution.
6. Design failure paths first
A reliable system must consider not only successful execution but also timeouts, cancellation, rejection, partial success, duplicate execution, and recovery policies.
Conclusion
The complexity of an Agent system does not disappear just because a few modules are omitted. It only moves to more hidden places. The effective approach is to establish boundaries at startup, assemble explicitly at the session stage, enforce constraints at the tool stage, define protocols at the multi-agent stage, and expose the entire decision chain through events and auditing.
If an Agent is viewed as a runtime system, then the model is only one decision-making component within it. What determines whether the system can evolve over the long term is startup routing, context isolation, permission governance, task scheduling, tool protocols, and failure recovery.
This is also the most valuable lesson from complex Agent architectures: do not rely on prompts to hide system problems, do not rely on global state for short-term efficiency, and do not turn every new requirement into a special branch in the main loop. Only by identifying complexity upfront, modeling it explicitly, and constraining it through institutionalized boundaries can an Agent grow from a one-off demonstration into a truly maintainable and extensible engineering system.
