Build a Self-Evolving AI Agent from Scratch and Connect It to Personal Messaging

    This guide explains how to implement an agent whose main differentiator is a closed loop for accumulating reusable skills. It covers environment prerequisites, Linux and Windows/WSL installation, OpenAI-compatible model configuration, least-privilege tool access, scheduling, and a personal messaging gateway. It also provides troubleshooting and security checklists for running the agent as a persistent, observable, and auditable automation service.

    1. Clarify the Concept: What Is a “Self-Evolving” Agent?

    Agents have been widely discussed over the past two years, but many products remain a Q&A shell with plugin calls. The core difference in implementations with real engineering value is the closed loop for skill accumulation: after a task is completed, the agent automatically reviews its execution trace, abstracts reusable steps into a skill description with trigger conditions, and writes that description to a local skill library. On the next similar intent, it first searches the skill library, then decides whether to reuse the skill directly, fine-tune it, or replan.

    The resulting capability leap can be summarized in three points:

    • Increasingly token-efficient over time: High-frequency tasks move from multi-turn reasoning to skill retrieval plus parameter filling.
    • Auditable behavior: Skills are persisted as text or structured files that people can read, edit, and delete.
    • Portable capabilities: The skill library is decoupled from the model, so switching models does not require rewriting business logic.

    An apt analogy is a 24/7 digital intern. It can operate a terminal, read and write files, retrieve web pages, connect to external systems through a standardized tool-calling protocol, and execute scheduled tasks based on Cron expressions. Deployment can fit on a small cloud VM with minimal specifications, or run on a container platform or cloud functions, while the user sends and receives messages from a phone at any time.

    2. Environment Prerequisites

    Operating system: Mainstream Linux distributions, Unix-like desktop systems, and the Linux virtualized subsystem on Windows. It can also run in a terminal emulator on mobile devices, but that is recommended only for lightweight tasks. Native Windows usually lacks a POSIX toolchain and is not recommended for direct deployment.

    Accounts and credentials:

    1. A machine with internet access and persistent uptime (a cloud VM or an always-on local device).
    2. A personal messaging account for receiving instructions; session binding is established later by scanning a QR code.
    3. An LLM service API key from any OpenAI-compatible model service platform, such as a model service offered by Baidu AI Cloud or another comparable provider.

    Hard constraint: A context window of at least 64K tokens is recommended. Below that limit, long-document parsing and multi-file refactoring tasks may be truncated, and skill distillation quality will drop noticeably.

    3. Installation: Two Paths

    Path A: Linux, Unix Desktop, or Terminal Emulator

    Official projects usually provide a one-command installation script. It typically performs four actions: validate the runtime version, install dependencies, pull the code, and write shell configuration.

    1. # Get the installation script URL from the project's official documentation. Do not use mirrors of unknown origin.
    2. curl -fsSL "<official installation script URL>" | bash
    3. # Apply the configuration.
    4. source ~/.bashrc # If using zsh, run source ~/.zshrc
    5. # Verify the installation.
    6. agent --version
    7. agent doctor # Check dependencies, network access, and credentials.

    Security note: curl | bash is a high-privilege operation. In production, download the script, review it manually, and then execute it.

    Path B: Windows (Set Up a Linux Subsystem First)

    Open a terminal as Administrator, install the Linux subsystem, and restart:

    1. wsl --install

    After the restart, set a username and password as prompted. Enter the subsystem and repeat the steps in Path A. Note: files inside the subsystem should be stored in Linux-side directories such as ~/. Placing them in cross-system mounted directories significantly slows down file-intensive operations.

    4. Model Configuration

    Inject the configuration through environment variables to avoid committing keys to a code repository:

    1. export AGENT_MODEL_BASE_URL="https://<model-service-endpoint>/v1"
    2. export AGENT_MODEL_API_KEY="<your-key>"
    3. export AGENT_MODEL_NAME="<model-identifier>"
    4. export AGENT_MAX_CONTEXT=65536

    Configuration considerations:

    • Prioritize interface compatibility: Prefer services compatible with the common Chat Completions style; they have the lowest switching cost.
    • Tier capability and cost: Use a large-parameter model for planning and reasoning, and a lightweight model for tool calls and formatting. This can significantly reduce costs.
    • Provide failure fallbacks: Configure timeouts, retries, and a degraded model so that instability at a single endpoint does not halt all tasks.

    5. Tools, Permissions, and Scheduling

    • Least privilege: Grant access only to the working directories required by the task. Do not mount the entire home directory or system directories for the agent.
    • Dangerous-command allowlisting: Actions such as deletion, formatting, and force pushing must require a second confirmation or be disabled.
    • Standardized tool protocol: Connect databases, object storage, message queues, logging services, and other common cloud capabilities through a unified tool interface. Avoid writing private glue code for every system.
    • Scheduled tasks: Use Cron for daily report aggregation, data inspection, and alert preprocessing. Tasks must be idempotent and write to independent log files.

    6. Connecting to Personal Messaging

    A typical chain is: the agent’s built-in session gateway generates a one-time QR code; the user scans it from a phone to establish the binding; messages enter a local queue; the agent consumes them and replies.

    1. Phone --(message)--> Session gateway --> Queue --> Agent core --> Tools/Models
    2. ^ |
    3. └──────────────────(reply/file/card)────────────────────────────┘

    Three risks require attention:

    1. Platform policy risk: Connecting a personal account through unofficial protocols may result in restrictions. Evaluate official open capabilities first.
    2. Content compliance: Outbound content must be traceable and auditable.
    3. Credential security: Session credentials are equivalent to account permissions. Encrypt them at rest, restrict file permissions, and rotate them regularly.

    7. Operational Reliability and Troubleshooting

    Symptom Common cause Action
    Command not found after installation Shell configuration was not applied Restart the terminal or source the file manually
    Model call returns 401 Incorrect key or key not injected Check environment variables and process inheritance
    Replies are truncated Insufficient context Increase the context limit or feed content in chunks
    No response after scanning the QR code Queue blocked or gateway offline Check gateway logs; add process supervision and automatic reconnection
    Abnormal cost increase Missing skill reuse or retry loops Enable the skill library and limit the maximum number of turns

    Launch recommendations: Use a process supervisor to keep the service running, connect a centralized logging service for search, and configure monitoring alerts covering three core metrics: process liveness, task success rate, and token consumption. When deploying in containers, mount the skill library and configuration to persistent volumes so upgrades do not lose capabilities.

    8. Security Red Lines

    1. Keys must not enter repositories, images, or chat logs.
    2. Do not run curl | bash directly in production; review first and install afterward.
    3. Keep the agent account separate from your primary account and minimize permissions.
    4. Treat all external input as untrusted and guard against prompt injection.
    5. Retain human confirmation and rollback plans for critical tasks.

    After following these steps, the result is not just another chat window but a continuously improving automation pipeline that accumulates skills and is observable and auditable. The real barrier is not installation; it is long-term governance of permission boundaries and skill quality.