Persistent AI Agents on Ubuntu: A Guide to Building from Scratch

    Learn how to build a persistent AI agent on Ubuntu with clear permission boundaries, layered architecture, searchable memory, reusable skills, messaging integrations, and isolated execution. This guide covers service management, model routing, scheduling, security, and a phased rollout that turns a conversational prototype into a maintainable system.

    A persistent AI agent is different from a single-turn chatbot in a browser. It runs on a server, retains context, reuses validated procedures, executes scheduled tasks, and delivers results through the messaging channels its users already use.

    This guide follows an engineering implementation sequence: define boundaries and architecture first, then address runtime management, memory, skills, integrations, execution isolation, and operations. The goal is to avoid confusing “can chat” with “can work reliably over time.”

    Goals and Boundaries

    Before building anything, define three things:

    1. Who the agent works for and what it can access. Specify permitted directories and network access.
    2. Which actions require human approval. Examples include deleting data, sending messages externally, and changing production configuration.
    3. How the agent stops when something fails. Failures must leave traceable logs.

    Autonomous execution without boundaries can turn a script error into an ongoing incident.

    Suitable use cases include:

    • Development: terminal commands, file organization, and code search.
    • Research: batch data processing and recorded comparisons across models.
    • Operations: scheduled health checks and alert summaries.
    • Personal assistance: accessing a private cloud-hosted assistant through mobile messaging.

    Unsuitable use cases include unattended high-risk changes or giving the model unrestricted access to secrets and production databases.

    Overall Architecture

    Use six distinct layers rather than one monolithic process:

    1. Interaction layer: Handles terminal and messaging interfaces, message exchange, and authentication.
    2. Orchestration layer: Manages sessions, tool-call loops, timeouts, and retries.
    3. Memory layer: Stores preferences, project context, and past conclusions as searchable records.
    4. Skills layer: Converts repeatedly successful steps into reusable procedures.
    5. Execution layer: Runs commands and scripts locally, on remote hosts, or in isolated environments.
    6. Model layer: Adapts different providers’ conversation and tool-calling interfaces to a common interface.

    Exchange explicit data structures between layers—for example, user intent, retrieved context, candidate tools, execution results, and whether to write information back to memory. This allows you to replace a model or add a messaging channel without rewriting execution or memory components.

    For a cloud-hosted deployment, cloud servers can host persistent processes, container platforms can provide isolation, object storage can hold skill documents and audit archives, and logging and monitoring services can track queue backlogs and failure rates. Baidu AI Cloud is one option mentioned for these infrastructure components; verify service availability, quotas, and interfaces in the relevant console and official documentation. Do not hard-code unverified parameters into the architecture.

    Runtime Environment and Service Management

    On Ubuntu, create a dedicated system user, a separate working directory, and a least-privilege permission model. Install only the interpreters, version managers, and basic networking tools needed by the runtime.

    Keep configuration and secrets in environment variables or files with restrictive permissions. Never embed secrets in skill documents or conversation logs.

    Prefer a system service manager for persistent operation. It should restart the process after a crash, start it at boot, and send standard output to logs.

    Separate foreground interaction from the background gateway:

    • The foreground interface supports debugging, multiline editing, command completion, streaming tool output, and usage inspection.
    • The background gateway handles incoming messages and scheduled tasks over long periods.

    Both should share the same memory and skill stores, but use separate working-directory quotas so that a debugging session cannot exhaust disk space.

    A minimal self-check can follow this sequence. These comments are illustrative; use the actual paths and interpreter for your installation:

    1. # 1. Start the process as the dedicated user.
    2. # 2. Check that configuration files are readable and secret files are owner-readable only.
    3. # 3. Send a test message through the local loopback interface.
    4. # 4. Confirm that logs include a session ID, model route, and tool results.
    5. # 5. Restart the service and verify that the same session can retrieve recent context.

    Health checks should measure more than process liveness. Track the time of the most recent successful tool call as well. A process that is running but no longer consuming its queue is effectively unavailable.

    Memory: Searchable Records, Not Unlimited Context

    Putting the entire conversation history into every model request is expensive and can distract the model. A layered memory design is more reliable:

    • Working memory: The current task’s goals, constraints, and attempted steps. Archive or discard it when the task ends.
    • Episodic memory: What happened, what the outcome was, and whether the user corrected it, with timestamps and sources.
    • Semantic memory: Stable preferences, project terminology, directory conventions, and contact roles.
    • User model: Communication preferences and boundaries inferred across interactions, with options for the user to inspect and delete them.

    Use full-text search with simple filters such as time, project, and tags. Retrieve a small set of highly relevant excerpts, then let the model summarize them.

    Apply a threshold for memory writes. Save reusable facts and confirmed conclusions, not secrets, one-time codes, or raw text containing sensitive personal information.

    Periodically condense scattered conversations into short summaries and remove raw details according to a retention policy. The result should be better understanding over time, not an increasingly noisy context window.

    The Skill Lifecycle

    A skill is not another conversation. It is an executable procedure that defines:

    • Trigger conditions
    • Inputs
    • Steps
    • Success criteria
    • Failure fallback
    • Required permissions

    After a task finishes, the orchestration layer decides whether its procedure is worth preserving. Useful signals include recurring requests of the same type, a workflow requiring multiple tool calls, or an explicit instruction such as “Do it this way from now on.”

    Automatically generated skills must start as drafts. Validate each through a replay before enabling it. If replay fails, record the reason so that the same faulty steps are not repeatedly invoked.

    Index skills by name and tags. Search before execution: use a matching procedure when available, and plan freely only when no suitable skill exists. Grant the minimum permissions declared by the skill rather than unrestricted access to the host.

    Skill documents should remain editable by humans. The model may propose changes, but every update should retain a version and a diff for rollback. The purpose is to turn experience into reviewable operating procedures, not unauditable habits.

    Multiple Interaction Channels

    One instance can serve a terminal and several messaging channels. Normalize gateway input into a common internal event containing:

    • Sender
    • Session
    • Text or attachment reference
    • Timestamp
    • Whether a reply is required

    Keep channel-specific differences inside adapters, including message length, rich-text support, file-size limits, and rate limits.

    Bind identities before enabling access. Map external accounts to internal users and distinguish direct messages from group conversations. Group conversations should use more conservative defaults to prevent private memory from being broadcast.

    Before sending externally, check whether the message:

    • Falls within allowed sending hours
    • Contains sensitive content
    • Exceeds a rate limit

    Home or device integrations should expose only predefined actions. Do not expose arbitrary shell execution through publicly reachable callbacks.

    Configure callback endpoints, tokens, and signature verification to minimize exposure. Separate gateway processes from execution processes so that a flood of messages on one channel cannot directly consume all execution capacity. Use queues for rate limiting and set per-user concurrency limits.

    Model Integration

    Models should be replaceable. The orchestration layer should depend only on a common interface covering system instructions, message lists, available tool descriptions, sampling parameters such as temperature, maximum output length, and streaming callbacks.

    Keep provider endpoints, credentials, and field mappings inside adapters. Switching models should not require changing skill or memory formats.

    In practice, prepare at least two routes:

    • Primary model: Handles planning and tool calls.
    • Fallback model: Takes over after timeouts, rate limits, or unacceptable output quality.

    For comparison experiments, record the same input and tool results so researchers can review differences rather than switch models based only on impressions.

    Usage monitoring should record request counts, input and output volume, failure codes, and latency. These measurements help detect abnormal loops, such as repeatedly calling the same tool without making progress. When a loop occurs, trip a circuit breaker and notify a human.

    Never put real credentials in articles or configuration examples. Do not assume that a provider’s API fields will remain unchanged. Follow the provider’s current documentation and keep adapters thin and testable.

    Execution Backends and Isolation

    Tool execution is the highest-risk part of the system. Choose the backend according to task sensitivity:

    • Local execution: Low latency and suitable for personal development directories. Restrict the user account, accessible paths, and environment variables.
    • Remote hosts: Suitable for existing bastion hosts or private-network machines. Use short-lived credentials and command allowlists.
    • Containers or disposable environments: Suitable for untrusted scripts and batch experiments. Destroy the environment afterward and mount working files explicitly.
    • Serverless short-running tasks: Suitable for bursty, parallelizable computation. Account for cold starts and temporary-disk limits.

    Every backend needs timeouts, output-size limits, outbound network controls, and working-directory quotas. Stream tool output back to users so they can interrupt execution promptly.

    Multiline editing and slash-command completion are interaction features, not sandbox features. Keep them separate from execution isolation. Completion can happen locally, while actual file writes and execution must still pass through the policy engine.

    Scheduled Tasks

    Use a system scheduling mechanism or an internal scheduler to specify when a task runs, what it does, and who receives the result.

    Natural-language requests can first be compiled into structured schedules containing recurrence, time zone, retry behavior, and quiet hours. The scheduler then executes the plan, rather than asking the model to reinterpret timing on every run.

    Send results through the messaging gateway and include the location of the original logs. Retries need limits and backoff. Repeated failures should produce an alert instead of an endless retry loop.

    Monitoring tasks should be read-only by default: collect status, compare it with thresholds, and generate a summary. Put write operations in separate change tasks and require an additional confirmation.

    Extension Protocols

    To connect an external tool ecosystem, use a published tool-calling convention. Describe tool names, parameters, permissions, and side effects in a manifest, and let the orchestration layer decide whether to invoke them.

    Validate new tools in an isolated environment before adding them to the production manifest. Test parameter validation and error responses.

    Reject extensions that allow arbitrary code from arbitrary URLs. Extension points must be disableable so that capabilities can be reduced quickly during a security incident.

    Implementation Guidance by Role

    Developers: Limit the default workspace to specified repositories. Authorize search and patching separately, and show diffs before committing changes.

    Researchers: Record the model identifier, prompt version, input samples, and tool traces for every experiment. Store outputs in object storage to support reproducibility.

    Operations engineers: Keep inspection skills read-only, send alert summaries to collaboration channels, and perform changes within designated change windows.

    Personal users: Use the phone only for sending and receiving messages, while leaving heavy computation on the server. Provide a simple way to inspect and clear memory.

    Security and Operations Checklist

    Before launch, verify that:

    • A dedicated system user is in place.
    • Secret files have restrictive permissions.
    • Outbound access is constrained.
    • Logs do not contain secrets.
    • Memory can be deleted.
    • Skills can be rolled back.
    • Scheduling can be paused.
    • The gateway has a circuit breaker.
    • Backups can be restored.

    During operation, monitor queue depth, tool failure rate, task duration, and disk growth. Before deploying changes, replay critical skills in a replica environment, then switch traffic.

    Back up configuration, skill versions, and memory indexes, but not plaintext secrets. Perform at least one restore drill. An untested backup is not evidence that recovery will work.

    A Phased Implementation Plan

    Week 1: Support one user, a terminal interface, one model, read-only tools, and local memory. Verify that context survives a service restart.

    Week 2: Add one messaging channel and one scheduled read-only task.

    Week 3: Introduce skill drafts and replay validation.

    Week 4: Add isolated execution and multi-model routing.

    Each stage should have measurable acceptance criteria: Can the agent complete a specified task within an allowed directory? Can failures be traced? Can the user disable autonomous writes?

    Following this sequence helps turn a persistent AI agent from a demonstration script into a maintainable system—not another background process that cannot be stopped.