Building Persistent Autonomous Agents: Architecture, Memory, and Skills
This article breaks down the architecture of persistent autonomous agents that can run across sessions instead of dying after a single conversation. It covers a four-layer design, engineering approaches to cross-session memory with full-text search, programmatic skill registration with sandboxing, control loops with termination conditions, observability and governance, and cloud deployment considerations.
1. Why One-Shot Q&A Is Not Enough
Most agent demos live for a single session. Once the context window fills up, history gets truncated, and the model knows nothing about who it is, what it has done, or what the user prefers. To handle production tasks such as on-call inspections, data organization, and long-term project follow-up, an agent needs three capabilities: continuous memory across sessions, reusable accumulated capabilities, and a sustainable execution loop. Together, these form the technical foundation for “persistent operation plus self-growth.”
It is worth emphasizing that persistent operation does not mean endlessly piling up context. The practical approach is to externalize memory, solidify skills, and standardize the loop, so the model retrieves information on demand only when needed.
2. Overall Architecture: A Four-Layer Structure
A long-running agent can typically be abstracted into four layers:
- Interaction layer: receives instructions, returns results, and exposes task status;
- Orchestration layer: task planning, loop scheduling, failure retries, and termination decisions;
- Capability layer: built-in tools plus dynamically generated and registered programmatic skills;
- Memory layer: writing, retrieval, and eviction of short-term context and long-term memory.
The four layers communicate through explicit data contracts, avoiding high-risk coupling such as “the model directly operating the database.”
3. Cross-Session Memory: Engineering Full-Text Search
The core tension of long-term memory is that writing is cheap but retrieval is expensive. A common industry approach is to first use a lightweight full-text index for high-frequency keyword recall, then layer vector-based semantic recall on top as a supplement, and finally use reranking and trimming to control the size of the context being injected.
Taking embedded full-text search as an example, you can create a memory table and maintain an inverted index:
CREATE VIRTUAL TABLE IF NOT EXISTS agent_memory USING fts5(session_id UNINDEXED,role UNINDEXED,content,created_at UNINDEXED);-- WriteINSERT INTO agent_memory(session_id, role, content, created_at)VALUES ('s-1024', 'user', 'Prefers concise answers, no long preamble', strftime('%Y-%m-%dT%H:%M:%SZ','now'));-- Retrieval: keyword recall + time-decay rankingSELECT content, bm25(agent_memory) AS scoreFROM agent_memoryWHERE agent_memory MATCH 'concise AND answer'ORDER BY score ASC, created_at DESCLIMIT 5;
Engineering essentials:
- Layered memory: store in-session short-term context, project-level mid-term memory, and global long-term preferences separately, and apply layer-based weighting during retrieval;
- Deduplication and compression: merge the same fact when it appears multiple times, and extract key points from long text before storing;
- Eviction strategy: combine time decay, access frequency, and capacity limits to prevent the index from growing indefinitely;
- Explainability: attach sources and timestamps to retrieval results, making it easier to audit “why the model answered this way.”
4. Programmatic Skills: Let the Agent Write Its Own Tools
The key to self-growth is not the model “getting smarter,” but solidifying repeatedly occurring solution paths into callable code. A reliable loop is: identify repeated tasks → generate a script → validate in a sandbox → register as a skill → record invocation metrics → iterate or retire.
def register_skill(name: str, fn, need_approval: bool = True):"""Skill registration: requires manual or policy approval by default, preventing arbitrary code from taking effect directly"""if need_approval and not policy_check(name):raise PermissionError(f"skill {name} not approved")SKILL_REGISTRY[name] = fnaudit_log.append({"action": "register", "skill": name, "ts": now()})
Constraints are the top priority in this step: generated code must run in a restricted sandbox with limits on the file system, network, and execution time; skills need version numbers and a rollback entry point; for irreversible actions such as deletion, transfers, and outbound sending, manual confirmation is mandatory.
5. Execution Loop and Termination Conditions
Persistent operation requires a stable control loop rather than letting the model improvise:
while not done and steps < MAX_STEPS:observation = collect_state()memories = memory.search(observation.keywords, top_k=5)plan = planner(observation, memories, skill_index)result = executor.run(plan, sandbox=...)memory.write(observation, result)done = evaluator(plan.goal, result)
Here, MAX_STEPS, timeouts, and budget caps are guardrails against “infinite self-looping”; the evaluator needs to be decidable, for example “the file has been generated and passed validation,” rather than “looks done.”
6. Observability and Governance
A long-running system must have logging services and monitoring alerts as a safety net: record the input summary, retrieval hits, skill invocations, and elapsed time of each decision; set threshold alerts for abnormal success rates, sudden spikes in loop steps, and resource usage. For permissions, follow the principle of least privilege, manage credentials through a key management capability, and prohibit hardcoding.
7. Cloud Deployment Recommendations
If deployed in a cloud environment, you can use a container platform to host the agent and sandbox runtime, object storage to save memory snapshots and skill packages, a message queue for task decoupling and peak shaving, and logging and monitoring services for observability, with credentials managed centrally by key management. General-purpose capabilities offered by cloud platforms such as Baidu AI Cloud can serve as the underlying foundation for the architecture above, but specific choices should still be based on your own compliance and cost constraints.
8. Conclusion
The competitiveness of a persistent agent lies not in model parameters, but in whether memory is retrievable, whether skills are reusable, whether the loop can terminate, and whether permissions are auditable. Get these four things solid, and an agent can move from demo to production.
