A Practical Guide to Self-Hosted, Self-Improving AI Agent Architecture

    This article presents a reference engineering architecture for self-hosted agents that stay online across sessions, rather than a review of any specific product. It defines a four-layer capability model (persistence, memory, reusability, governability), breaks the system into five layers (access, orchestration, capability, execution, infrastructure), and details how to implement tiered long-term memory with extract-then-retrieve strategies, how to distill successful runs into versioned skill definitions, how to classify and sandbox tools by read/write and reversibility risk, and how to isolate identity and permissions at the messaging gateway while keeping model backends replaceable. It closes with an evaluation loop, rollout advice, and common pitfalls.

    1. From Chat Box to a Long-Running Digital Worker

    Over the past two years, the interaction model of large language models has converged three times: first the web chat box, then coding assistants embedded in editors, and now the “autonomous agent” that gets discussed repeatedly. The first two forms share the same limitation: the session boundary is the capability boundary. Close the window and the context disappears; switch tools and the workflow has to be rebuilt. The third form tries to turn the agent from a passive responder into a continuously online executor. It runs persistently on a server or in a container, receives instructions through messaging platforms, calls tools such as terminals, files, and browsers to complete multi-step tasks, and leaves experience behind when the task ends.

    This article does not evaluate any specific product. Instead, it abstracts this class of system into a reference engineering architecture and focuses on four questions: how memory persists across sessions, how skills are automatically extracted and reused, how the tool layer stays controllable, and how the message gateway stays “always online without getting out of control.”

    2. Target Capability Model: What a “Self-Improving” Agent Needs

    Breaking the slogan of “self-evolution” into verifiable engineering terms yields roughly four layers of capability:

    1. Persistence: processes and state recover across restarts, tasks can be triggered on a schedule, and no human has to open an interface.
    2. Memory: the system distinguishes “factual memory” (project structure, interface contracts, personal preferences) from “procedural memory” (solution paths for a class of problems).
    3. Reusability: one-off successful experience is solidified into capability units with input and output constraints, available for later calls and for sharing across a team.
    4. Governability: permissions, auditing, cost, and rollback all need boundaries; otherwise “autonomy” quickly turns into “uncontrollable.”

    If any one of these four layers is missing, the system degrades into a chatbot with a timer.

    3. Reference Architecture: A Five-Layer Breakdown

    1. ┌─────────────────────────────────────────────┐
    2. │ Access Message gateway / scheduler │
    3. │ / webhooks │
    4. ├─────────────────────────────────────────────┤
    5. │ Orchestration Task planning · reflection │
    6. │ extraction · skill routing │
    7. ├─────────────────────────────────────────────┤
    8. │ Capability Memory store · skill library │
    9. │ · tool registry │
    10. ├─────────────────────────────────────────────┤
    11. │ Execution Sandbox containers · terminal│
    12. │ · files · browser │
    13. ├─────────────────────────────────────────────┤
    14. │ Infrastructure Container platform · object │
    15. │ storage · logging & monitoring│
    16. └─────────────────────────────────────────────┘

    The access layer keeps the agent always online. The orchestration layer makes it think before acting. The capability layer handles remembering and reuse. The execution layer does the actual work. The infrastructure layer makes the whole thing operable. Each layer is expanded below.

    4. Long-Term Memory: Tiered Storage and Retrieval

    Long-term memory is not about stuffing the entire conversation history into the context window. It is about three things: tiering, summarization, and retrieval.

    • Working memory: the context of the current task, released when the task ends.
    • Episodic memory: a timeline of “what was done and how it turned out,” used for retrospection.
    • Semantic memory: distilled stable facts, such as directory conventions, dependency versions, and approval processes.
    • Preference memory: user habits, such as output language, commit message format, and default branch strategy.

    The practical recommendation is “extract before writing, rerank before retrieving.” Write structured entries rather than raw text. For retrieval, combine vector similarity with keyword matching, then let the model rerank the results. This significantly reduces interference from irrelevant context. A sample structure:

    1. {
    2. "type": "semantic",
    3. "scope": "project",
    4. "key": "db.migration.policy",
    5. "value": "All schema changes must ship with a rollback script",
    6. "confidence": 0.92,
    7. "updated_at": "2025-01-01T00:00:00Z"
    8. }

    Two points deserve emphasis. First, memory needs eviction and conflict resolution; otherwise wrong conclusions get reinforced over and over. Second, sensitive information should not enter long-term memory. Credentials belong in a dedicated key management capability and should be injected on demand at runtime.

    5. Skill Distillation: Turning Successful Experience into Callable Units

    A “skill” is essentially a constrained instruction document plus optional scripts. It describes the applicable scenario, preconditions, inputs and outputs, and failure fallback. Its value is converting the model’s implicit reasoning into explicit assets that can be reviewed, versioned, and shared.

    A minimal skill definition:

    1. name: rollback-db-migration
    2. when: A migration script failed and the transaction was not committed
    3. inputs: [migration_id, target_env]
    4. steps:
    5. - Read the migration record and backup location
    6. - Run the rollback script in the staging environment
    7. - Verify sampled data consistency results
    8. outputs: [rollback_report]
    9. on_failure: Stop and escalate to a human

    For the extraction step, trigger a “reflection” after the task ends: have the model compare the plan against the actual execution trace and output “which steps are reusable and which were incidental.” A human or a set of rules then reviews the result before it enters the library. This is how you avoid treating a lucky success as general experience. The skill library works best with an open, plain-text description format, which makes cross-tool migration and team review easier.

    6. Tools and Execution: Capability Inventory and Safety Boundaries

    The tool layer concentrates the most risk. In practice, classify tools along three dimensions: read/write permission, network access, and reversibility.

    • Read-only: log queries, metric reads, document retrieval. These can be opened up.
    • Write: file modifications, configuration changes. These need a directory allowlist and a diff preview.
    • Irreversible: deleting data, shipping production changes. These require human confirmation or two-person review.

    Run everything inside sandbox containers. Mount the base image read-only, give the working directory its own volume, and route network egress through an allowlist proxy. Keep a structured audit log for every tool call (caller, parameter summary, duration, result status), feed it into logging and monitoring, and set thresholds on failure rate and latency spikes.

    For scheduled tasks, describe them in natural language and let the scheduler compile them into concrete triggers, for example “every weekday morning, summarize yesterday’s build failures and generate a brief.” Write the execution result back to the messaging platform to close the loop.

    7. Access Layer and Model Compatibility: Decoupling Is the Key

    The value of a message gateway is placing the agent inside the channels users already use. But it must implement identity mapping and permission isolation: different groups map to different skill allowlists, so that a single message in a group chat cannot trigger a production change. Also apply length and rate limits to all inbound messages to guard against prompt injection and resource abuse.

    On the model side, stick to “interface abstraction plus replaceable providers.” Wrap three capabilities behind a unified interface: conversation, tool calling, and embedding. Switch backends through configuration, supporting both commercial cloud models and locally deployed open-source models. The direct benefit is controllable cost and compliance: strong models for high-value tasks, smaller local models for batch work, and sensitive data that never leaves the internal network.

    8. A Closed Loop for Training and Evaluation

    Once skills and traces are structurally accumulated, the system naturally has material for evaluation and training optimization: batch-generate task traces, compress and denoise them, and build tool-calling datasets to measure success rate and average step count of different models on multi-step tasks. The evaluation set should cover four scenario types: normal paths, boundary inputs, tool failures, and permission denials. Metrics should include at least task success rate, average number of tool calls, human takeover rate, and cost per task.

    9. Rollout Advice and Common Pitfalls

    1. Start narrow, then widen. Begin with low-risk scenarios such as read-only inspections and daily report generation, and verify that memory and skills actually deliver reuse benefits.
    2. Observability first. An autonomous agent without distributed tracing is a black box; when something breaks, you cannot tell whether the planning or the tool was wrong.
    3. Cost and quotas. Set a maximum step count and timeout per task to avoid loops of repeated calls.
    4. Keep a human in the loop. Retain a confirmation step for irreversible operations and include the confirmation record in the audit trail.
    5. Build on general cloud capabilities. Let a container platform host the execution sandbox, object storage hold skills and reports, a message queue buffer tasks, logging and monitoring provide observability, and a dedicated service manage keys. In an environment such as Baidu AI Cloud, this gives you elasticity and isolation.

    10. Conclusion

    A “self-improving agent” is not a marketing concept. It is the combined result of four engineering capabilities: tiered memory, skill assets, governable tools, and isolated access. Make each layer a module that can be reviewed, rolled back, and measured, and the system’s autonomy turns into real productivity instead of an operations burden.