Practical Autonomous Agent Development: From Runtime Architecture to Reliable Delivery
Building autonomous agents requires shifting from single-prompt interactions to continuous, constrained execution systems. This article explores the general engineering design of autonomous agents, covering runtime architecture, tool protocols, execution loops, context assembly, long-term memory, safety isolation, and multi-agent collaboration. It also details practical scenarios for code maintenance and research agents, alongside strategies for debugging, evaluation, and reliable deployment to ensure every step is necessary, controlled, and verifiable.
I. From Model Interaction to Sustainable Execution
Standard large language model applications typically revolve around a single request: a user asks a question, the system organizes the context, and the model generates an answer. Autonomous agents, however, must break down a goal into a sequence of actions and use external feedback to determine the next step.
For example, “fixing a test failure in a project” does not simply mean generating a piece of code. The complete process may involve reading project documentation, locating relevant files, reproducing the failure, analyzing the root cause, modifying the code, re-verifying, and organizing delivery instructions. Failure at any step could alter the subsequent trajectory.
Therefore, the core of agent development is not continuously adding prompts, but building a constrained execution system. This system must answer at least five questions:
- What state is the current task in?
- Which tools can the model invoke?
- How do external execution results feed into the next round of decision-making?
- Which actions must be halted or require manual confirmation?
- What evidence proves the final result is completed?
This article discusses general engineering design, independent of any specific framework. The structures and pseudocode used here illustrate implementation concepts and do not represent interfaces or capabilities of existing products.
II. Runtime Architecture: Separating Inference, Execution, and State Management
An extensible agent runtime can be broken down into the following functional modules:
Task Entry is responsible for receiving the goal, execution scope, permission constraints, and acceptance criteria. Goals should be translated into verifiable requirements whenever possible, such as “fix the specified test without changing the public interface,” rather than a vague “optimize the project.”
Session State Manager is responsible for saving task progress, historical actions, tool feedback, budget, and checkpoints. The state should not just be a continuously growing conversation log, but should contain explicit structured fields.
Context Assembler is responsible for organizing the current goal, necessary history, relevant materials, and available tool definitions into the model’s input.
Decision Module is responsible for proposing the next action but does not directly execute operations with side effects.
Tool Executor is responsible for parameter validation, permission checks, resource limits, executing operations, and generating structured feedback.
Observation & Audit Module is responsible for recording state changes, execution duration, failure reasons, and delivery evidence.
The significance of this separation lies in establishing responsibility boundaries. The model proposes “what should be done,” the runtime decides “whether execution is allowed,” the tool handles “what actually happened,” and the validation module determines “whether the result meets requirements.”
1. Session State Cannot Reside Only in Memory
For long-running tasks, process restarts, network interruptions, and tool timeouts can occur. Critical states need to be persisted, including at least:
- Task ID and current status;
- Original goal, constraints, and acceptance criteria;
- Completed steps and pending items;
- Tool call records and result summaries;
- Remaining execution budget;
- Artifact locations and validation evidence.
States such as “pending,” “running,” “waiting for confirmation,” “success,” “failed,” and “canceled” can be adopted. State transitions should be triggered by explicit events, such as permission approval, tool results, or budget exhaustion, rather than relying on the model’s self-declarations in text.
2. Checkpoints and Recovery Must Handle Side Effects
When recovering a task, the most dangerous issue is the repeated execution of completed write operations. For instance, if a change was committed before the interruption, it might be executed again upon recovery.
Therefore, a distinction should be made between read-only and write operations. For scenarios where external systems support idempotency mechanisms, stable operation identifiers can be used; for unsupported scenarios, states must be recorded before and after execution and verified against actual results during recovery.
“Re-initiating a call” does not equate to “safe recovery.” The system must know which steps can be retried, which require prior querying, and which can only be left to human judgment.
III. Tool Protocols: Converting Natural Language Intent to Controlled Operations
Tools form the boundary between the agent and the external environment. A complete tool definition requires not only a name and parameters but also a description of its purpose, input constraints, return structure, permission requirements, and side effects.
Take file reading capabilities as an example. It is necessary to specify:
- Accessible working directories;
- Whether reading hidden files or sensitive configurations is allowed;
- File size and return content length limits;
- Error formats for non-existent paths or insufficient permissions;
- Handling of text encoding anomalies.
For command execution capabilities, constraints should be stricter. You should not allow arbitrary system commands by default just because a task requires running tests. Provide operations with clear purposes and restricted parameters, and limit working directories, execution time, output size, and network access ranges.
1. Valid Parameters Do Not Mean Safe Operations
Structural validation can only check field types, required fields, and enumeration ranges; it cannot replace business authorization.
For example, a path string might conform to formatting rules but could access files outside the workspace through path traversal or symbolic links. Therefore, boundary checks on the canonicalized actual path are necessary.
Network access is similar. You cannot just verify if the address format is correct; you must restrict destinations and consider the risks of redirected addresses and internal network resource access.
2. Tool Feedback Must Support Subsequent Decisions
It is recommended that tools return a unified result envelope:
Execution Result:Call IDSuccess or failure statusData or artifact referenceError categoryError descriptionWhether retry is appropriateExecution durationWhether output is truncated
Error categories can distinguish between parameter errors, permission denials, timeouts, transient failures, and business failures. This allows the model to decide whether to correct parameters, wait and retry, switch strategies, or stop execution.
Special attention is needed: a successful tool return only means the call was completed according to protocol, not necessarily that the business goal was achieved. Successfully reading a file does not mean the root cause was found; successfully modifying a file does not mean the fix is correct.
IV. Execution Loop: Driving Actions with Feedback, Not Infinite Retries
The agent execution loop can be summarized as:
Assemble context → Generate action → Validate action → Execute tool → Receive feedback → Update state → Judge whether to continue.
Below is an illustrative flow:
While the task is not finished:Check cancellation signals, remaining time, and execution budgetAssemble necessary context based on current stateGet the next actionIf the action requests termination:Verify evidence against acceptance criteriaComplete if conditions are met, otherwise record gapsContinue or stopIf the action requests a tool call:Validate parameters, permissions, and risk levelRoute high-risk operations to manual confirmationExecute permitted operationsSave feedback and update checkpointsIf there is no effective progress for consecutive rounds:Adjust the plan or escalate to manual processing
1. Termination Conditions Must Be Constrained by the Runtime
Setting a maximum number of steps is insufficient. In practice, you should also limit total runtime, cumulative call counts, single-tool execution time, and retry limits for similar failures.
Additionally, “no-progress loops” can be detected: consecutive calls to the same tool with nearly identical inputs, repeated feedback, and no task state advancement. In such cases, mechanical retries should be halted, requiring replanning or human intervention.
2. Retry Strategies Must Match Failure Reasons
Transient network failures can be retried with limits, using backoff strategies to reduce repeated request pressure; parameter errors should be corrected first; permission denials should not be bypassed through repeated attempts; business failures require re-analyzing the task.
For calls with side effects where the result is unknown, the external state should be queried first. Otherwise, a retry after a timeout might cause duplicate writes or submissions.
3. Completion Must Rely on Evidence
The model outputting “task completed” cannot be the sole termination criterion. The runtime should inspect deliverables, validation results, and task constraints.
If evidence is insufficient, a clear distinction should be made between “completed,” “partially completed,” “unverifiable,” and “stopped due to limits.” This is more reliable than generating a seemingly complete but unverified conclusion.
V. Context Assembly: Controlling Information Density and Trust Boundaries
Context windows are limited, yet task history grows continuously. Directly concatenating all logs, files, and tool outputs often causes critical constraints to be drowned out, increases costs, and can even introduce untrusted instructions.
A reasonable context should be organized in layers:
- Stable system rules and permission boundaries;
- Current task goals and acceptance criteria;
- Current plan and structured state;
- Evidence directly related to the next action;
- Recent critical tool feedback;
- Necessary historical summaries.
1. Summaries Must Preserve Decision Value
A good summary is not just about shortening text, but preserving information needed for subsequent actions: which hypotheses were validated, which strategies failed and why, and which operations must not be repeated.
Historical summaries may omit details, so critical errors, modification records, and acceptance evidence should retain original references and can be re-read when necessary.
2. External Data Cannot Be Elevated to System Instructions
Web pages, documents, code comments, and tool outputs are all data to be processed. Even if they contain text like “ignore previous instructions,” they cannot alter runtime permissions or system rules.
Sources and trust levels should be clearly marked in the context. At the same time, prompt-level constraints cannot completely eliminate risks; true security boundaries must still be enforced through tool authorization, resource isolation, and manual approval.
VI. Long-Term Memory and Skills: Reusing Experience Without Solidifying Errors
Long-term memory is used to retain valuable information across tasks, while skills are used to reuse organized operational workflows. The two should not be confused.
Memory can include user preferences, project conventions, verified environment information, and historical decisions; skills can include applicability conditions, execution steps, required permissions, and success checkpoints.
1. Memory Writes Need Filtering
Not every conversation is worth saving. Before writing, determine if the information is stable, verifiable, free of sensitive content, and genuinely reusable in the future.
For example, “the project requires certain checks before committing changes” can form a project memory; “the model guesses a module has a defect” cannot be directly treated as a long-term fact.
Memory records should be accompanied by source, timestamp, applicable scope, and expiration conditions. When conflicts occur, newer and verifiable evidence should take precedence, rather than letting old memories permanently affect execution.
2. Skills Should Have Boundaries and Versions
A reliable skill is not a vague operational suggestion, but a verifiable process. For example, a code maintenance skill should specify:
- Which tasks it applies to;
- What environment is required before execution;
- Which scopes are allowed to be modified;
- Which steps must be validated;
- When to stop and request confirmation;
- How to roll back generated changes.
Skills should retain version information after updates. When involving expanded permissions or write operation changes, they should be re-audited rather than allowing the new process directly into production execution.
VII. Safety Isolation: Putting Access Control Outside the Model
Agents can misjudge or be induced by external content. Therefore, security design must follow the principle of least privilege.
File operations should be restricted to designated workspaces; execution environments should only expose necessary resources; network access should be opened as needed by the task; sensitive credentials should be provided via controlled mechanisms, avoiding conversations and logs; publishing, deletion, and irreversible changes should require additional confirmation.
Sandboxing limits the potential blast radius, but it is not a panacea. Isolated environments still require correct configuration, including mount directories, network permissions, resource quotas, and credential visibility.
A risk grading system should also be established: ordinary reads can be executed automatically; modifications within a limited scope can be executed after validation; operations involving production states or irreversible consequences should require manual approval.
VIII. Knowledge Enhancement and Multi-Agent Collaboration
1. The Goal of Knowledge Enhancement Is to Provide Traceable Evidence
Retrieval-Augmented Generation (RAG) provides a basis for model responses and actions by retrieving relevant materials. The engineering workflow typically includes document parsing, rational chunking, index construction, querying, candidate filtering, and citation organization.
Chunking should not just cut by fixed lengths but should try to preserve titles, paragraphs, and contextual relationships. Returned results should include source, time, and permission information to help assess credibility and timeliness.
Permission filtering should act on the retrieval pipeline, not after materials enter the model’s context. Conclusions lacking sufficient material support should explicitly express uncertainty.
2. Multi-Agent Suits Clear Boundary Divisions
Multi-agent systems are not inherently superior to single-agent systems. Additional coordination increases latency, call costs, and state conflicts.
Collaboration is more valuable when subtasks can be completed independently and output standards are clear. For example, separately conducting information gathering, evidence verification, and report compilation.
Roles should hand off structured results, marking dependencies, sources, and unresolved issues. For shared files or states, independent workspaces, controlled merges, or other concurrency control methods should be used to prevent multiple executors from overwriting each other’s results.
IX. Two Typical Practical Scenarios
1. Code Maintenance Agent
Code maintenance tasks should proceed along the lines of “establish baseline, minimal changes, level-by-level validation, delivery review.”
First, read project rules and confirm the modification scope, then reproduce the issue, distinguishing between existing failures and failures introduced by this change. When modifying, prioritize minimal necessary changes and avoid expanding risks through incidental refactoring.
Validation can start with related local checks, followed by more comprehensive checks based on impact scope. If environment restrictions prevent certain validations from running, they should be listed in the delivery instructions; “not run” must not be written as “passed.”
The final delivery should include the root cause, change scope, validation evidence, residual risks, and rollback methods. The agent can assist in preparing changes, but high-risk actions like merging and deploying should be separately authorized.
2. Research Agent
Research tasks must first clarify problem boundaries, including the research subject, time range, evidence standards, and output format.
During execution, formulate a retrieval plan first, then collect materials, record sources, cross-verify, and organize conclusions. Finding the same content across multiple searches does not necessarily mean obtaining multiple independent pieces of evidence, as different pages may cite the same source.
Research results should distinguish between facts, inferences, and recommendations. For conflicting materials, explain the conflict points and judgment basis; for long-term tasks, save covered scopes and unanswered questions to avoid repeated retrieval after resuming execution.
X. Debugging, Evaluation, and Deployment: Making Reliability Observable
Agent debugging cannot just look at the final answer; it must be able to reconstruct the critical execution process: what was the task state at the time, what evidence was included in the input, what action was proposed, why was it authorized, and what did the tool actually return.
Logs are recommended to include task and call IDs, state changes, parameter summaries, duration, error categories, and artifact references. Sensitive fields should be masked, and long content can be saved as controlled references to prevent logs themselves from becoming leak channels.
Evaluation should use a fixed set of tasks and observe the system from multiple dimensions:
- Was the goal truly achieved?
- Were tool selection and parameters reasonable?
- Were there any privilege escalation attempts?
- Can it recover correctly after failure?
- Is the final conclusion supported by evidence?
- Are execution costs and time acceptable?
- Under what circumstances is human intervention required?
Before going live, in addition to normal paths, you should test scenarios like tool timeouts, format anomalies, insufficient permissions, material conflicts, task cancellations, and process interruptions.
The rollout sequence should go from small to large: first implement restricted tools and an observable loop, then add state recovery, memory, and knowledge retrieval, and finally expand collaboration capabilities based on explicit needs. The maturity of an autonomous agent does not depend on how many steps it can execute consecutively, but on whether each step is necessary, controlled, explainable, and capable of delivering reliable evidence.
