Building a Persistent Router and Background Execution Architecture for AI Agents

    This article presents a minimal yet reusable architecture for turning conversational coding agents into persistent, always-on services. It explains the structural limitations of request-response interaction, the core design of separating a lightweight router from background workers, and six common engineering components that make the system work. Key mechanisms such as context isolation, event-driven and scheduled execution, file-based state persistence, and a watchdog are covered, along with an evolution path and practical engineering recommendations for teams building long-running automation in their own environments.

    1. Background: From One-Shot Q&A to Continuous Operation

    Most intelligent coding tools still rely on conversational interaction: the user issues an instruction, the model performs one round of reasoning and tool calls, and then waits for the next instruction. This works well for single-turn tasks, but long-running development work exposes three structural weaknesses.

    First, interaction gets blocked. When a code search or build verification takes a long time, the session cannot accept new input, and the user is forced to wait.

    Second, contexts contaminate each other. When multiple tasks share one session, background information, intermediate artifacts, and temporary conclusions from different requirements mix together, causing later reasoning to drift from the goal.

    Third, tasks cannot keep moving forward on their own. Once a session ends, unfinished plans, unverified assumptions, and items that need periodic checks are all lost, so the system cannot “take the next step by itself.”

    For these reasons, the industry has begun exploring how to evolve agents from “passive responders” into “continuously running services” that stay resident, can be accessed remotely, handle multiple tasks in parallel, and perform self-inspection. Using an engineering implementation with very few components as a sample, this article abstracts a reusable architectural pattern.

    2. Core Design Idea: Role Decoupling and Single Responsibility

    The key to this design is not adopting a more complex framework, but making a clear separation of responsibilities.

    • Router: The single external entry point. It receives requests, understands intent, breaks down tasks, selects executors, and aggregates results. It stays lightweight and does not take on heavy code modification itself.
    • Worker: Runs an intelligent coding command-line tool inside an independent, persistent terminal session, handling time-consuming work such as coding, retrieval, and verification.
    • Event and scheduling layer: Composed of an external message entry point and periodic scheduled tasks, it turns both “human input” and “the passage of time” into executable tasks.
    • Monitoring and watchdog: Periodically checks the status of each worker, and triggers alerts or restarts when it detects stalled, abnormally exited, or timed-out unfinished tasks.
    • Persistence layer: Plans, logs, and task records are written to files, separating state from computation.

    This separation yields three direct benefits: the router is always interactive; different task contexts are naturally isolated; and a crash in a single worker does not affect the overall service.

    3. Overall Architecture: Six General-Purpose Components Working Together

    The whole system relies on only six types of common engineering components, all of which are standard industry capabilities and depend on no proprietary interfaces.

    1. Persistent router: A long-running intelligent session process that acts as the control center.
    2. Persistent terminal sessions: Provide a background-capable, attachable, isolated environment for the router, the message gateway, and each worker.
    3. Remote message entry point: An instant messaging bot serves as the channel for submitting tasks and returning results, giving the system mobile operation capability.
    4. Intelligent coding command-line tool: The actual executor of development tasks; multiple different implementations can be integrated to complement each other’s capabilities.
    5. Periodic scheduler: Periodically triggers inspections and reminders via scheduled tasks.
    6. Virtual machine and shared working directory: The system runs in an isolated virtual machine, with the working directory pointing to a shared path on the host, directly reusing existing code repositories. This is also a minimal form of storage-compute separation.

    The collaboration flow can be summarized as:

    1. User → Message entry → Persistent router → Create independent terminal session → Coding tool executes
    2. ↑ ↓
    3. Scheduled inspection/watchdog ←──── Logs and task files written to disk

    4. Breakdown of Key Mechanisms

    4.1 Persistent Router: Unified Access and Lightweight Scheduling

    The router runs in a persistent terminal session and is constrained by a system prompt: understand intent first, clarify when necessary, split tasks into independently verifiable sub-items, and then dispatch them. Through a message mirroring extension, it converts external chat messages into internal task instructions, then formats execution results back to the user.

    The key design point is that “the router does not write code.” Once the router performs long-running tool calls itself, interaction blocking and context contamination immediately return. Keeping the router lightweight is the prerequisite for the entire architecture to hold.

    4.2 Background Execution and Context Isolation

    Each task starts in a newly created independent terminal session and does not share reasoning context with others. The benefits are that tasks can run in parallel, be interrupted, and be replayed; cleaning up a failed task only requires destroying its session, without affecting other tasks.

    A simplified scheduling example:

    1. def dispatch(task):
    2. session = f"worker-{task.id}"
    3. open_terminal_session(session, cwd=task.workspace)
    4. send_to_session(session, build_prompt(task))
    5. append_task_record(task.id, status="running")
    6. return task.id

    4.3 Event-Triggered and Asynchronous Progress

    There are two sources of events: event-driven input from external messages, and time-driven input from scheduled tasks. The former handles immediate needs, while the latter advances long-cycle items, such as “check whether the build passed,” “summarize today’s changes,” and “retry failed steps.” Together they turn the system from a passive responder into an active driver.

    4.4 State Persistence and Storage-Compute Separation

    Plan documents, execution logs, and task lists are all saved as files in the shared working directory. Any executor can read the same context, and progress can be restored from files after a restart. Compute resources can be rebuilt at any time without losing state, which is a low-cost way to improve overall reliability.

    4.5 Monitoring and Watchdog

    The watchdog is implemented as a periodic task, logically consisting of three steps: collect the output and heartbeat of each worker; determine whether it has timed out, stalled, or exited abnormally; and trigger an alert, restart, or fallback handling.

    1. if now - last_output_time > threshold:
    2. notify("Task appears stalled")
    3. restart_or_terminate(session)

    5. Gap from the Full Vision and Evolution Path

    This minimal implementation intentionally omits several advanced capabilities, which makes the evolution direction clear:

    • Task registry: Replace scattered file records with structured storage to support querying, deduplication, and priority ordering.
    • Thread association mechanism: Establish parent-child relationships for multi-turn tasks to support context inheritance and result tracing.
    • Fine-grained event routing: Dispatch based on task type, priority, and resource usage to avoid mutual contention.
    • Independent state management: Introduce an explicit state machine that divides the task lifecycle into pending scheduling, executing, pending verification, completed, and failed.
    • Enhanced observability: Unified log collection, metrics, and alerting to form a complete monitoring and alerting loop.

    For a further move to the cloud, the shared directory can be replaced with object storage or a file storage service, the message entry and scheduling can be decoupled into a message queue, executors can run containerized on a container platform, and log and monitoring/alerting services can be integrated, gaining elasticity and operability while keeping the architecture simple. Baidu AI Cloud offers corresponding capabilities in these general cloud product categories and can serve as a candidate environment for hosting such an architecture.

    6. Engineering Practice Recommendations

    1. Get the minimal loop working first: Connecting the router, workers, and watchdog is enough to validate the value; do not pursue full mechanisms from the start.
    2. Strictly constrain the router’s responsibilities: Pushing all heavy workloads down to executors is the key discipline for preventing architectural degradation.
    3. Persist all state to disk: File-based state is simple, auditable, and easy to recover, making it suitable as an early source of truth.
    4. Set timeouts and retry limits for tasks: Prevent abnormal tasks from occupying resources for a long time.
    5. Isolate working directories: Use independent branches or copies for different tasks to reduce interference risk.
    6. Keep a human confirmation step: High-risk operations such as deletion, release, and permission changes must be confirmed by a human.

    7. Conclusion

    The value of this design lies not in novel components, but in using the most ordinary engineering means to validate an important judgment: the reliability of an agent comes from structure, not from stacking model capabilities. Through router-executor separation, context isolation, asynchronous progress, and periodic inspection, a tool that could originally only answer one question at a time can evolve into a task system that runs continuously, can be operated remotely, and can supervise itself. For teams that want to build long-running automated development capabilities in their own environments, this is a pragmatic path with low investment, verifiable results, and easy extensibility.