Agent System Architecture: From Task Orchestration to Execution Infrastructure
This article explains why AI agent systems need a clearer separation between task orchestration and execution infrastructure. It covers a four-layer architecture, sandbox and file-system design, resource lifecycle management, middleware pipelines, context and long-term memory governance, sub-agent collaboration, reliability, observability, and a behavior-compatible approach to refactoring. The goal is to help teams build agent systems that are safer, more stable, traceable, and operable rather than merely demonstrable.
1. Why Agent Systems Need a Fresh Look at Architecture
Many agent applications begin with a simple flow: receive a question, call a model, execute tools based on the model output, and pass the results back to the model for consolidation. This approach is useful for validating requirements, but it is difficult to use directly for long-running operation, multi-user concurrency, and complex task collaboration.
When the system starts handling research, file processing, code execution, or multi-step business operations, the problems expand quickly:
- How should files generated in one session be stored, and can other sessions access them?
- If tool execution is interrupted, should the system rerun it or continue from a checkpoint?
- When context becomes too long, which information can be compressed, and which must be preserved in full?
- When multiple sub-agents work at the same time, how should permissions, cost, and result conflicts be controlled?
- Should operations proposed by the model be executed immediately, and which actions require human confirmation?
These questions show that agent applications are moving from “model-calling programs” to “task systems with execution infrastructure.”
The key to architectural upgrades is therefore not adding more prompts. It is separating task orchestration from the execution infrastructure: the former describes how a task progresses, while the latter ensures that the task runs safely, stably, and traceably.
2. Distinguishing Task Orchestration from Execution Infrastructure
2.1 Task orchestration handles process semantics
Graph-based orchestration typically represents processing steps as nodes and transitions between steps as edges. Nodes can perform model inference, tool calls, result validation, or human confirmation; edges express sequence, conditional branches, and loops.
It is suited to answering questions such as:
- What stage is the current task in?
- What conditions must be met before moving to the next step?
- Which steps can run in parallel, and which must wait?
- After a failure, should the system retry, roll back, or terminate?
However, a flow diagram does not automatically provide secure file access, controlled command execution, long-term memory, or multi-tenant isolation. These capabilities require independent design.
2.2 Execution infrastructure handles runtime constraints
Execution infrastructure deals with resources, permissions, state, and lifecycle management. It needs to know who owns a task, which tools the task can use, which directories it can access, how long it may run, and how execution results are persisted.
The relationship can be understood as follows:
Orchestration defines “what to do next,” while execution infrastructure constrains “where this step runs, with what permissions, and how failures are handled.”
The term “agent operating system” is better understood as an architectural metaphor. It emphasizes providing a unified runtime environment for agents. It does not mean replacing a traditional operating system, nor does it imply that complete security isolation is available by default.
3. Responsibilities of a Four-Layer Architecture
A common logical division includes an entry layer, an interaction layer, a business gateway layer, and an agent runtime layer. These four layers can be deployed as independent services or combined in early-stage deployments. Whether to split them into microservices should depend on team size, load characteristics, and operational capabilities.
3.1 Entry layer: unified access and traffic governance
The entry layer handles request forwarding, connection management, transport security, and basic traffic control. For systems that need to continuously return execution events, connection timeouts and buffering policies must be configured appropriately so that long-running tasks are not treated as ordinary short requests.
One point needs special attention: a client disconnect should not be directly equated with task cancellation. Browser refreshes, network fluctuations, and explicit user cancellation are different events. Task lifecycle should be managed explicitly by the server.
3.2 Interaction layer: show the task process, not just the final answer
Agent tasks often do not follow a one-request, one-response pattern. The frontend should display task stages, tool execution status, artifact lists, pending confirmation actions, and failure reasons.
Interaction design should also distinguish “the system is executing,” “the system is waiting for external resources,” and “the system needs user input.” Otherwise, users only see a continuous loading state and cannot tell whether the task is healthy.
User identifiers, resource paths, and permission claims passed from the frontend cannot be used directly as authorization evidence. Identity and access permissions must be verified by the server.
3.3 Business gateway layer: centralize identity and policy
The business gateway can handle authentication, access authorization, task creation, resource ownership validation, quota control, and audit entry points.
After a task is created, the gateway should generate a stable task identifier and associate it with the tenant, user, session, and resource scope. When a client reads progress, downloads artifacts, or cancels a task, access rights must be revalidated. Data should not be obtained solely by presenting a task identifier.
The gateway should not take on all long-running execution work. Otherwise, task execution will compete with ordinary request processing for resources and increase the scope of failure propagation.
3.4 Agent runtime layer: carry task state and execution process
The runtime layer advances tasks, calls tools, manages subtasks, and records checkpoints. It should have explicit lifecycle management so that resources can be released after a task completes, fails, is cancelled, or times out.
For long-running tasks, asynchronous scheduling or work queues usually make load management easier. Whether to introduce a queue should be judged based on task duration and reliability requirements, rather than treating it as a mandatory component for every system.
4. Execution Environment: Sandbox, File System, and Resource Lifecycle
4.1 Sandboxes should be designed around the threat model
Letting a model generate and run code, or letting an agent process external files, introduces untrusted input. The goal of a sandbox is to limit the impact of these operations on the host environment and other tasks.
The design should at least clarify:
- Which directories can be read and written;
- Whether external network access is allowed;
- Which processes can be started;
- How CPU, memory, storage, and execution time are limited;
- How credentials are injected, and whether they can be read by the task or written to logs;
- Which resources must be destroyed after the task ends.
Different isolation methods have different security boundaries. Simply separating working directories can reduce accidental operations, but it cannot replace process, permission, and runtime environment isolation. When handling code from untrusted sources, appropriate isolation mechanisms should be selected according to risk.
4.2 The file system is part of task artifact management
Files generated by agents should not be treated only as temporary attachments. Intermediate data, processing scripts, analysis reports, and result manifests may all become important evidence for recovery and auditing.
It is recommended to give each task an independent workspace and distinguish:
- Input area: stores original materials and can be set to read-only when necessary;
- Temporary area: stores intermediate files that can be rebuilt;
- Output area: stores final deliverables;
- Metadata area: records source, version, checksum information, and generation process.
When exposing files externally, controlled artifact identifiers should be used instead of accepting arbitrary paths submitted by clients. Path normalization, directory boundary validation, and access authorization should be implemented together to prevent unauthorized reads.
4.3 Resource reclamation must cover failure paths
Cleaning up resources after normal completion is not difficult. The real gaps are process crashes, service restarts, task cancellation, and timeout exits.
The system should record resource ownership and validity periods, and use background reclamation mechanisms to handle runtime environments that have lost their task association. For artifacts that need to be retained, persistence should be completed before temporary execution space is released, avoiding the situation where “the task shows success, but the files have already disappeared.”
5. Middleware Pipeline: Turn Cross-Cutting Capabilities into Explicit Processes
Capabilities such as identity, isolation, context compression, tool validation, and auditing can easily become scattered across business code. The value of a middleware pipeline is to turn these cross-cutting capabilities into execution stages with explicit order and input/output contracts.
The number of stages is not an indicator of architectural quality. The following is an illustrative set of stages for design discussion, not a representation of any specific implementation:
- Validate request format and identity;
- Check tenant and resource permissions;
- Load session and task state;
- Establish a task isolation context;
- Acquire or create an execution environment;
- Organize context and history summaries;
- Apply planning mode and approval policies;
- Validate tool calls;
- Execute tools and record results;
- Commit checkpoints and candidate memories;
- Aggregate output, send events, and reclaim resources.
Order has business meaning. For example, permission checks must happen before resource access; tool parameter validation must happen before execution; final completion status should be committed after necessary results are persisted.
Each stage should also declare whether it is retryable, whether it has external side effects, and whether compensation is required after failure. For irreversible operations, simple repeated execution cannot be relied upon to recover a task.
Tool call repair is not automatic guessing
Model output may contain format errors, missing fields, or type mismatches. The system can correct formatting according to explicit rules, but it should not fill in meanings with business risk on its own.
For example, deterministic conversion of field types can be handled by validation rules; when a payee, deletion scope, or target environment is missing, the model should be asked to regenerate or the user should be asked to confirm. Repair mechanisms must not become a channel for bypassing authorization and approval.
6. Context and Long-Term Memory Should Be Managed Separately
6.1 Context compression must preserve execution constraints
Information accumulated by long-running tasks often exceeds the context range a model can handle. Summaries can reduce input size, but the summary itself may also omit facts.
During compression, priority should be given to preserving task goals, prohibited actions, user confirmations, key decisions, evidence behind tool results, and unfinished items. Verbose tool output can be stored in the artifact area, while the context retains summaries and controlled references.
Summaries should ideally include coverage scope and sources so the system can look back at original records when needed, rather than treating the summary as unquestionable fact.
6.2 Long-term memory requires write governance
Not all information that appears in a session should enter long-term memory. Temporary speculation, instructions from external files, and one-off task details can all contaminate subsequent behavior.
A more reliable process is: first generate candidate memories, then perform source checks, sensitive information detection, conflict handling, and write authorization, and only then persist them. Asynchronous queues can reduce waiting time in the main flow, but task completion does not mean memory has been written successfully. The two states should be represented separately.
Long-term memory should also support updates, deletion, expiration, and usage restrictions so that outdated information is not continuously reused.
7. Sub-Agent Collaboration: Boundaries Matter More Than Quantity
Sub-agents are suitable for tasks with clear boundaries, such as independent research consolidation, analysis of different options, or result review. However, adding more participants does not necessarily improve quality. It can also bring duplicate execution, wasted context, and coordination overhead.
Each subtask should include a clear objective, input scope, allowed tools, output requirements, execution budget, and cancellation conditions. The parent task is responsible for dispatch, waiting, aggregation, and conflict handling.
Permissions should not be inherited unconditionally. A subtask that only needs to read materials should not receive the ability to modify business data. When multiple subtasks need to write to shared resources, version checks, serial commits, or conflict detection should be used to avoid overwriting each other.
The aggregation stage should not merely concatenate text. It needs to check whether evidence is consistent, whether conclusions conflict, and whether any key constraints from the parent task were missed.
8. Reliability and Observability Must Be Core to the Architecture
8.1 Define task states explicitly
Tasks can have states such as waiting, running, pending confirmation, succeeded, failed, cancelled, and timed out. Each state should have clear entry conditions and allowed transitions.
In particular, distinguish “request received,” “task started,” and “result persisted.” These three should not share a vague success marker.
8.2 Establish idempotency boundaries for retries
Network failures may leave the caller unsure whether a tool has already executed. Retrying directly at this point may cause duplicate writes or duplicate submissions.
Operations with side effects should be handled with idempotency identifiers, execution records, or result query mechanisms. For actions that cannot guarantee idempotency, confirmation and compensation strategies should be used, and the risk should be clearly presented to the user.
8.3 Record execution chains that explain behavior
Logs need to associate tasks, sessions, tenants, stages, and tool calls, but sensitive content should not be recorded indiscriminately.
Observability should cover stage latency, tool failures, retry counts, resource usage, context compression, subtask waiting, and cancellation propagation. This makes it possible to determine whether a problem comes from reasoning, external dependencies, insufficient resources, or process design.
9. Architecture Refactoring Should Prioritize Behavioral Compatibility
A full rewrite can clean up historical coupling, but it may also lose existing behavioral contracts. A more robust refactoring approach is to first define task inputs, state representation, artifact formats, error semantics, and permission boundaries, and then replace internal modules incrementally.
Implementation can follow a path such as:
- Build regression samples for typical tasks and failure scenarios;
- Extract tool calls from business processes;
- Unify task states and execution records;
- Introduce independent workspaces and resource reclamation;
- Add context governance and memory write policies;
- Add sub-agents only to tasks where there is a clear benefit;
- Finally, split services according to load and team needs.
Validation should focus not only on answer quality but also on unauthorized access, duplicate execution, process interruption, task cancellation, and artifact recovery. Architecture reliability often becomes visible only in abnormal scenarios.
10. Conclusion: Measure Architecture Maturity by Controlled Execution
The maturity of an agent system is not determined by the number of model calls, the number of services, or the length of the middleware chain. It depends on whether the system can clearly answer: where does the task execute, what permissions does it have, how is state recovered, what is the evidence for results, and who confirms risky actions.
Only by designing orchestration, execution environment, state, memory, and collaboration mechanisms separately, and connecting them through clear contracts, can a system move from demonstrable to operable. For development teams, the most worthwhile investment is not stacking capabilities all at once, but establishing execution boundaries that are verifiable, recoverable, and auditable.
