Building a Persistent AI Agent on Ubuntu: A Complete Setup Guide

    This article walks through building a persistent AI agent from scratch on Ubuntu 22.04/24.04. It covers environment hardening and process management, a cross-session memory system, a reusable skill loop, pluggable model configuration, multi-channel messaging with scheduled tasks, tool integration, and observability, along with typical use cases.

    1. Why a Persistent Agent Instead of a One-Off Chat Tool

    Most conversational AI tools follow a short-lived request-response model: the user asks a question, the model returns content, and the session context is bounded by the context window. Once the task is done, the state is discarded. This works well for Q&A and copywriting, but it cannot support scenarios that require long-running operation, continuous accumulation, and proactive triggering.

    The key difference of a persistent agent is that it runs continuously on a server, with durable state, reusable experience, and the ability to be triggered by external events. Its capabilities can be broken down into four layers:

    1. Execution layer: It can invoke shell commands, read and write files, and search codebases, so it actually gets work done rather than only offering suggestions.
    2. Memory layer: It preserves user preferences, project context, and prior conclusions across sessions, avoiding a fresh start every time.
    3. Scheduling layer: It supports time-based or event-driven proactive tasks without manual initiation.
    4. Integration layer: It connects to multiple messaging gateways, so the agent shows up in the communication channels users already use.

    Only when these four layers are combined do you get the foundation for an agent that gets smarter with use. The following sections use an Ubuntu 22.04/24.04 server as the example and lay out a from-scratch approach.

    2. Environment Setup: Build a Solid Foundation

    2.1 System and Security Baseline

    Use a recent Ubuntu LTS release and keep the system updated. Create a dedicated runtime account instead of running the agent with superuser privileges:

    1. sudo adduser agent
    2. sudo usermod -aG sudo agent
    3. sudo -iu agent

    At minimum, complete three security tasks: configure key-based login and disable password login, enable the host firewall and allow only necessary ports, and apply least privilege to the agent’s working directory. Because the agent can execute commands, its permission boundary must be tightened from the start.

    2.2 Runtime Dependencies

    A persistent agent is typically a long-running process, so it needs a stable runtime and process supervision. Install the base components with the package manager, and let the system service manager own the process to get startup on boot and automatic restarts after failures:

    1. # /etc/systemd/system/hermes-agent.service example
    2. [Unit]
    3. Description=Persistent AI Agent
    4. After=network-online.target
    5. [Service]
    6. User=agent
    7. WorkingDirectory=/home/agent/agent
    8. ExecStart=/usr/bin/python3 -m agent.cli serve
    9. Restart=always
    10. RestartSec=5
    11. [Install]
    12. WantedBy=multi-user.target

    Enable it as follows:

    1. sudo systemctl daemon-reload
    2. sudo systemctl enable --now hermes-agent

    2.3 Isolation and Execution Backends

    Isolation is a requirement, not an option, when the agent executes untrusted tasks. Ordered from weakest to strongest isolation, the common approaches are local processes, containerized execution, remote host execution, and serverless hosted execution. For production, use at least container isolation to keep the filesystem and network egress within a controlled scope, and add confirmation or allowlist mechanisms for high-risk commands.

    3. Memory System: Keep Context Alive Across Sessions

    Memory is the dividing line for a persistent agent. In engineering practice it is usually split into two types:

    • Factual memory: Structured information such as user preferences, project conventions, and environment parameters, which fits relational or key-value storage.
    • Semantic memory: Historical conversations and document fragments, which are best recalled through full-text or vector retrieval.

    A pragmatic combination is to use an embedded database for structured memory while building a full-text index for keyword recall, then add user modeling so that “who is asking, and under which project” becomes a retrieval filter. An illustrative storage schema:

    1. CREATE TABLE memory (
    2. id INTEGER PRIMARY KEY,
    3. user_id TEXT NOT NULL,
    4. scope TEXT,
    5. content TEXT NOT NULL,
    6. created_at TEXT
    7. );
    8. CREATE INDEX idx_memory_user ON memory(user_id);

    It is important to stress that memory must be able to expire and be corrected. Add a confidence score and an expiration policy to each memory entry, and let users explicitly delete incorrect memories; otherwise wrong information gets amplified over the long term.

    4. Skill Loop: Turn Successful Experience into Reusable Capability

    A skill is essentially an abstraction of one successful task trajectory into a replayable process description, including trigger conditions, required tools, execution steps, and verification methods. The loop has four steps:

    1. Task completion: The agent successfully invokes several tools and achieves the goal in a task.
    2. Trajectory abstraction: Summarize the process as “under which conditions, in which steps, calling which capabilities.”
    3. Storage and deduplication: Compare against existing skills by similarity to avoid redundant growth.
    4. Automatic reuse: Later similar tasks match existing skills first, falling back to general reasoning if they fail.

    Two engineering points matter: the skill library needs versioning and rollback, and skill invocation needs timeouts and failure circuit breakers so that one bad skill cannot contaminate all subsequent tasks.

    5. Multi-Model Integration: Treat the Model as a Replaceable Component

    Do not hardcode a model provider’s invocation logic into business code. The recommended approach is to abstract at the configuration layer, hide differences behind a unified adapter, and switch through configuration:

    1. model:
    2. provider: custom_openai_compatible
    3. base_url: http://127.0.0.1:8080/v1
    4. model: general-chat
    5. temperature: 0.3
    6. max_tokens: 4096

    Switching models requires only a configuration change and a service restart, with zero changes to business code. It is also advisable to implement multi-level fallback: switch to a backup model when the primary one is unavailable, and track token usage in real time with a budget cap to prevent runaway costs from a long-running process.

    6. Multi-Platform Messaging and Scheduled Tasks

    The role of a message gateway is to unify heterogeneous channels into a standard interface of “inbound event to outbound reply.” In implementation, abstract a unified message model and build a separate adapter for each channel, with deduplication and rate limiting:

    1. # Unified message model example
    2. @dataclass
    3. class InboundMessage:
    4. channel: str
    5. user_id: str
    6. thread_id: str
    7. text: str
    8. ts: float

    For scheduled tasks, a built-in scheduler can create them from a natural language description, for example “check service status at 9 a.m. every weekday and report anomalies.” In practice, ensure that tasks are idempotent, execution logs are queryable, failures can be retried, and results are proactively pushed through the message gateway.

    7. Tool Extensions and Observability

    Extending capabilities through a standardized tool integration protocol is key to keeping the architecture decoupled: file operations, code search, data queries, and external system calls are all registered as tools, and the agent depends only on a unified tool description and invocation convention.

    Observability is equally indispensable. Cover at least three types of signals: trace logs (input summaries and duration for each tool call), metrics monitoring (success rate, latency, token consumption), and alerts (consecutive failures and budget overruns). Together with logging and monitoring services, this is what lets you locate problems quickly while the agent runs over the long term.

    8. Four Typical Use Cases

    • Developers: Run builds and tests on the server, search codebases, and collaborate across environments.
    • Researchers: Batch data processing, multi-model comparison experiments, and generating reproducible experiment trajectories.
    • Operations engineers: Periodically inspect service status and proactively report anomalies through messaging channels.
    • Everyday users: Access a personal assistant deployed on a cloud server from a mobile client.

    To reduce operational overhead, deploy the agent on a cloud server or container platform, use object storage for memory and skill data, a message queue for event buffering, and logging and monitoring services for observability, forming a complete loop.

    9. Conclusion

    The value of a persistent agent lies not in how impressive a single answer is, but in whether state, experience, and scheduling can run stably over the long term. When building from scratch on Ubuntu, keep four main threads in mind: the boundary of permissions and isolation, the correctability of memory, the circuit breaker in the skill loop, and the replaceability of models and channels. Get these four solid, and the agent can genuinely keep evolving over time.