Architecture Design and Engineering Practices for Persistent Autonomous Agents

    This article explores the architecture design and engineering practices of persistent autonomous agents. It addresses the structural limitations of traditional stateless conversational applications, such as memory discontinuity, capability rigidity, and the lack of autonomous execution. The article introduces a six-layer reference architecture, detailing key components including cross-session memory retrieval, runtime skill generation, multi-model orchestration, multi-channel integration, observability, and security compliance. It also provides a practical roadmap for phased implementation.

    1. Background: From One-off Q&A to Long-running Executors

    Traditional conversational applications operate on the basic assumption of “statelessness”: once a session ends, the context is discarded, and the model starts from scratch in the next interaction. This assumption is sufficient for demonstration scenarios, but once tasks span hours, days, or even weeks (such as continuously tracking build failures in a code repository, conducting long-term inspections of service metrics, or generating periodic reports), stateless design exposes three structural flaws:

    1. Memory Fragmentation: Users are forced to repeatedly provide background information, and interaction costs increase linearly with the task cycle.
    2. Capability Rigidity: The model can only use preset tools and cannot fill capability gaps when encountering new scenarios.
    3. Lack of Autonomous Action: The system only runs when prompted and lacks the ability to execute on schedule or trigger based on conditions.

    The defining characteristics of a persistent autonomous agent are precisely to address these three points: cross-session searchable memory, runtime-extensible skills, and a scheduler-driven execution loop rather than a human-driven one. It must be emphasized that “autonomous” does not mean “unconstrained”; in engineering terms, it means making its own decisions on the next action within explicit permission and budget boundaries.

    2. Layered Architecture: A Practical Reference Model

    Splitting such systems into six layers can significantly reduce the complexity of implementation and troubleshooting:

    • Access Layer: Unifies heterogeneous message channels (instant messaging, team collaboration tools, custom web consoles, open APIs) into “inbound events,” shielding the differences among channels in authentication, message formats, rich text, and callback retries.
    • Orchestration Layer: Responsible for intent recognition, task decomposition, tool selection, and loop termination judgment. This is the “control plane” of the agent.
    • Memory Layer: A triplet of short-term context + long-term knowledge base + structured state.
    • Skill Layer: A capability pool composed of built-in tools and runtime-generated programmatic skills.
    • Execution Layer: A sandboxed code/command execution environment paired with resource and permission quotas.
    • Scheduling and Observability Layer: Handles time/condition triggers, logs, metrics, tracing, and cost accounting.

    The key benefit of layering is fault domain isolation: rate limiting in the access layer will not crash the orchestration layer, and a sandbox escape in the execution layer will not pollute the memory layer’s data.

    3. Cross-session Memory: Retrieval-First, Not Infinite Context Growth

    Stuffing all history into the context window is infeasible in engineering—costs and latency degrade quadratically with rounds, and the recall rate of key information in long contexts drops significantly. The industry-standard approach is “externalized memory + on-demand retrieval”:

    1. Write: Perform hierarchical compression after a session ends to generate “fact entries” (verifiable states), “decision entries” (why a certain action was taken), and “preference entries” (user habits), retaining timestamps and source session IDs.
    2. Index: Build a full-text inverted index for the entries. This is a full-text search extension capability commonly provided by embedded relational databases. Its advantages include zero maintenance, single-file deployment, and support for prefix and boolean queries, making it highly suitable for single-machine or small-scale agents.
    3. Retrieve: Hybrid sorting usually outperforms single signals—keyword retrieval ensures precise hits (error codes, function names, config items), vector similarity ensures semantic generalization, and a time decay factor prioritizes recent information.
    4. Backfill: Only inject Top-K entries into the prompt, accompanied by source tags, facilitating model citation and human auditing.

    Illustrative retrieval logic (pseudocode):

    1. function recall(query, k = 6):
    2. kw = fts_index.search(query, limit = k * 2) # Exact match
    3. vec = vector_index.search(embed(query), limit = k * 2)
    4. merged = reciprocal_rank_fusion(kw, vec)
    5. merged = apply_time_decay(merged, half_life = 14d)
    6. return top_k(merged, k) with source_ref

    In engineering, three types of “memory pollution” must be handled: expired facts (require invalidation flags rather than physical deletion), duplicate entries (perform near-duplicate detection before writing), and wrong conclusions (retain a revision chain, allowing new entries to overwrite old ones rather than erasing history).

    4. Skill Self-generation: Turning “Capability Gaps” into “Verifiable Code Assets”

    The core idea of programmatic skills is that when the orchestration layer discovers that existing tools cannot complete a task, instead of giving up, it first generates an executable piece of code, verifies it, and then registers it as a formal tool. A robust implementation must include four gates:

    • Specification: Skills are described with a declarative manifest detailing the name, input schema, output schema, permission requirements, and timeout limits, allowing the orchestration layer to make typed calls.
    • Sandbox Execution: No external network or whitelisted network only, read-only file system mounts, CPU/memory/duration quotas, and system call filtering.
    • Automatic Verification: Dual validation using test cases provided by the generator + a fixed set of regression test cases; registration is only allowed if all pass.
    • Versioning and Rollback: Like code assets, skills require version numbers, changelogs, and canary releases; in case of online exceptions, they can be quickly rolled back by version.
    1. skill:
    2. name: summarize_build_log
    3. version: 1
    4. inputs: { path: string, max_lines: int }
    5. outputs: { summary: string, failed_targets: [string] }
    6. permissions: [fs.read.sandbox, net.none]
    7. limits: { cpu_ms: 2000, mem_mb: 256, wall_clock_s: 30 }
    8. tests: [tests/smoke_build_ok, tests/smoke_build_fail]

    A risk to be clearly understood is that self-generated code is essentially “supply chain input produced by a model without human review.” Therefore, the skill registry must be enumerable, auditable, instantly disableable, and self-generated skills must be prohibited from modifying their own permission manifests.

    5. Multi-Model Compatibility and Aggregate Reasoning

    Decoupling model access is a default requirement for such systems: a unified abstraction layer adapts models from different vendors and of different parameter scales to the same calling contract, thereby supporting routing by task type—low-cost models for classification and extraction, strong reasoning models for planning and debugging. On top of this, multi-agent aggregation (multiple models/samplings answering in parallel, then synthesized by an aggregator) can achieve a lower error rate in high-value decisions, at the cost of several times the token overhead. Therefore, aggregation must be a “configurable strategy” rather than a default behavior, paired with a confidence threshold: upgrade to the aggregation path only when confidence is low.

    6. Multi-Channel Access and Scheduled Triggers

    The engineering focus of multi-channel access is not “connecting to many,” but semantic normalization: mapping messages, attachments, @mentions, and thread replies from various platforms into a unified internal event model, and downgrading outbound replies based on channel capabilities (degrading to plain text + links when rich text is not supported). Simultaneously, idempotent consumption must be implemented to avoid duplicate executions caused by callback retries.

    Scheduled triggers shift the agent from “passive response” to “active inspection.” It is recommended to adopt a decoupled design where “the scheduler only emits events, and the orchestration layer makes decisions,” and to enforce a budget limit and circuit breaker condition for each periodic task to prevent infinite loop calls triggered by abnormal inputs.

    7. Observability and Cost Governance

    The call chain of an autonomous system is dynamic, rendering traditional “per-interface statistics” observation methods ineffective. It requires task trajectory (trace) as the primary key: recording the thought summary, tool calls, token consumption, and duration of each step. Based on this, establish three types of alerts: single-task token over budget, sudden spike in call volume per unit time, and rising skill failure rate. Effective measures on the cost side include prompt prefix caching, retrieval result caching, small model pre-filtering, and setting quotas for different tenants. When call volume reaches the scale of “hundreds of billions of tokens daily,” cost governance takes precedence over model capability fine-tuning.

    8. Security, Compliance, and Open Source Governance

    • Least Privilege: Default to no external network and no write permissions; capabilities are granted on demand and are revocable.
    • Human-in-the-Loop: Mandatory manual confirmation for irreversible actions such as deletion, fund transfers, and external publishing.
    • Audit Trails: Memory writes, skill registrations, and permission changes are all logged. Logs and metrics are integrated into a unified logging service and monitoring alert system.
    • Open Source Compliance: License scanning is required for introducing skills and dependencies. Occasional “code similarity disputes” in the community remind us that traceability of sources, auditable commits, and clear licenses are the foundation of long-term credibility for open source projects, not an afterthought.

    9. Implementation Roadmap

    1. First implement “memory + retrieval + single-channel access” to validate the cross-session experience benefits.
    2. Then add the scheduler and observability to allow the system to run unattended.
    3. Next, open the sandbox and skill self-generation, and simultaneously build the skill registry and rollback mechanism.
    4. Finally, introduce multi-model routing and aggregate reasoning to optimize quality within a clear cost budget.

    Advancing in this order ensures measurable benefits at each stage while keeping security and cost risks within manageable limits.