Engineering Frameworks for Continuously Running AI Agents: Two-Layer Architecture, Event-Driven Design, and External Oversight
A practical guide to building engineering frameworks that let LLM-based agents run continuously across sessions. This article covers a two-layer control/execution architecture, event-driven scheduling, asynchronous multi-channel interaction, separation of state and compute, and an external watchdog for supervision, along with key implementation practices such as observability, permission boundaries, idempotency, and human approval checkpoints.
Engineering Frameworks for Continuously Running AI Agents: Two-Layer Architecture, Event-Driven Design, and External Oversight
1. From Single Conversations to Persistent Agents
Over the past two years, the dominant way to use large language models has been single-turn or multi-turn Q&A. The user asks a question, the model answers, and when the session ends, the model’s memory of that interaction ends with it. This model works well for question answering and text generation, but it struggles to support tasks that need to run over long periods—research that spans several days, continuous monitoring of a system’s state, or keeping multiple projects moving at the same time.
As models have grown more capable at planning and tool calling, a new class of application has emerged: personal assistant agents. These agents need to remember user preferences, understand the history of a task, and proactively push work forward even when the user is not present. Their value comes from being continuous, not from the quality of any single answer.
Persistent agents impose new requirements on the engineering architecture. The model itself only handles understanding and generation. To make it work long-term, stably, and under control, you need a full supporting runtime system—one that schedules tasks, preserves state, connects to external tools, handles failures, and returns results to a human.
2. What an Agent Runtime Framework Is Responsible For
An agent runtime framework is a software layer built around a large language model. The model handles reasoning and decision-making; the framework turns those decisions into actions that are executable, traceable, and recoverable. A complete runtime framework typically covers the following responsibilities:
- Session and state management: Persist task goals, progress, intermediate artifacts, and decision history so the agent can resume across sessions.
- Context assembly: Before each model call, select relevant information from long-term memory, task state, and recent events, and keep the context within bounds.
- Tool invocation and execution: Translate the model’s action requests into calls to external services, handling timeouts, failures, and retries.
- Task scheduling: Manage priorities, dependencies, and concurrency across multiple tasks without letting them interfere with each other.
- Human interaction: Report progress at key checkpoints and collect feedback and approvals.
- Safety and oversight: Restrict which resources the agent can access, log operations, and pause or roll back when something goes wrong.
The boundary between the framework and the model must be clear. The model should not manage its own retry logic or permissions—those are deterministic responsibilities that belong to the framework. Giving deterministic work to code and leaving uncertain reasoning to the model is the basic precondition for reliability in these systems.
3. Core Challenges of Continuous Operation
Before designing anything, the problems need to be clear. Persistent agents typically face four challenges.
First, human attention caps the number of tasks. If every task requires the user to watch the session, the number of concurrently running tasks is limited by human bandwidth. No matter how capable the agent is, efficiency drops when the user has to keep switching contexts.
Second, sessions are too tightly coupled to tasks. In the traditional interaction model, one session maps to one task. When a task spans multiple sessions, key information gets lost, and the model depends on the user re-explaining the background.
Third, context drifts over time. The longer a task runs, the more history accumulates. Without filtering and compression, the context fills up with stale information, the model’s judgment quality degrades, and costs rise.
Fourth, tasks interfere with each other. When multiple tasks share the same model, the same tools, and the same memory, one task’s erroneous output can pollute another task’s context or consume more than its share of resources.
The key to solving all of these is to decouple the task from the session—making the task an independent running entity that the framework schedules and manages centrally.
4. Core Architecture Design
4.1 Two-Layer Architecture: Control Layer and Execution Layer
The two-layer architecture splits the system into a control layer and an execution layer. The control layer maintains the global view: the task list, priorities, dependencies, resource quotas, and human approval checkpoints. The execution layer advances individual tasks: calling the model, executing tools, and writing intermediate results.
The two layers communicate through explicit interfaces. The control layer hands down task goals and constraints; the execution layer returns status and outputs. The benefit is that when a single execution unit fails, the control layer can reassign or pause it without affecting other tasks.
Control Layer├── Task registry and priority queue├── Dependency graph and scheduler├── Approval and reporting module└── Resource quota managementExecution Layer (one independent execution unit per task)├── Context assembly├── Model inference├── Tool invocation└── State write-back
4.2 Event-Driven Design: State Changes Instead of Polling
A persistent agent spends most of its time waiting—waiting for an external API to return, waiting for user feedback, waiting for a scheduled condition. Polling wastes resources and adds latency. An event-driven model records every state change as an event, and subscribers respond as needed.
Common event types include task creation, model output completion, tool call returns, incoming user messages, timeout triggers, and exception alerts. Events should carry a unique identifier and a timestamp to support deduplication, replay, and auditing.
from dataclasses import dataclass, fieldfrom datetime import datetimeimport uuid@dataclassclass TaskEvent:task_id: strevent_type: str # e.g. "tool_result", "user_message", "timeout"payload: dictevent_id: str = field(default_factory=lambda: str(uuid.uuid4()))created_at: datetime = field(default_factory=datetime.utcnow)def dispatch(event: TaskEvent, handlers: dict):"""Dispatch an event to the handler registered for its type."""handler = handlers.get(event.event_type)if handler is None:return # Unregistered event types are ignored and loggedhandler(event)
4.3 Asynchronous Multi-Channel Interaction
An agent needs to communicate with multiple parties at once: users may send instructions from different devices, external systems may push notifications, and scheduled jobs may trigger reports. If all interactions go through a single synchronous channel, they block each other. An asynchronous multi-channel design splits input and output into independent queues, each with its own buffering, rate limiting, and retries.
This design has another benefit: messages the user sends at any moment can be queued first and processed by the scheduler at the right time, without requiring the agent to respond immediately.
4.4 Separating State from Compute
Separation of state and compute means deploying state storage and computation independently. Compute units (model calls, tool execution) should be stateless or weakly stateful, so they can be scaled, resized, or migrated at any time. State data (task progress, memory, logs) lives in a separate persistence layer backed by general-purpose data storage services.
With this design, a crash in a single execution unit does not lose task progress. The framework only needs to read the latest checkpoint from the persistence layer to resume the task on another execution unit.
Checkpoint granularity matters in practice. Checkpointing too frequently adds write overhead; too sparsely, and a failure loses more progress. A common approach is to write a checkpoint before and after each tool call and at every key decision point.
4.5 External Watchdog: Supervision Independent of the Model
During operation, an agent may fall into loops, repeatedly call the same tool, drift away from the task goal, or produce conclusions that look plausible but are wrong. Relying solely on the model to check itself is unreliable, because whatever causes the error often affects the self-check too.
An external watchdog is a supervisory component that is independent of the model’s reasoning path. It monitors execution through rules and metrics—for example, a per-task step limit, a consecutive-failure count, elapsed-time thresholds, tool call frequency, and whether output matches the expected format. When a threshold is hit, the watchdog can pause the task, notify a human, or roll back to the previous checkpoint.
class Watchdog:def __init__(self, max_steps: int, max_failures: int, max_seconds: float):self.max_steps = max_stepsself.max_failures = max_failuresself.max_seconds = max_secondsdef check(self, steps: int, failures: int, elapsed: float) -> str | None:"""Return the action to take; return None if everything is normal."""if steps >= self.max_steps:return "pause_for_review"if failures >= self.max_failures:return "rollback_to_checkpoint"if elapsed >= self.max_seconds:return "notify_user"return None
Watchdog thresholds must be calibrated per task type. Thresholds that are too strict will frequently interrupt normal work; too loose, and they provide no protection. A good practice is to record the real metric distributions for each task type during early rollout, then set thresholds based on that data.
5. Key Implementation Practices
5.1 Observability
A continuously running system must be observable. For every task, you should be able to answer: which stage is it in, what were the inputs and outputs of the most recent model call, which tools were invoked, and at which step did the failure occur. Generate a unified trace identifier for each task and chain model calls, tool calls, and state changes into a single queryable trace.
On the metrics side, track task completion rate, average steps, retry counts, per-task duration, and model call cost. These metrics serve both troubleshooting and evaluating the efficiency of the framework itself.
5.2 Permissions and Security Boundaries
The tool permissions an agent holds should follow the principle of least privilege. Each task should only access the resources strictly necessary to complete it. Write operations require explicit authorization, and irreversible actions—deleting, sending, deploying—must be confirmed by a human.
Sensitive information such as access credentials and personal data should be stored in a dedicated secrets management service, never written into prompts, logs, or checkpoint files.
5.3 Idempotency and Retries
Tool calls can time out due to network fluctuations, and framework retries may cause the same action to execute twice. For write operations, carry an idempotency key with the call so downstream services can detect duplicate requests. For operations that cannot guarantee idempotency, the framework should record the intent first and execute only after confirmation.
5.4 Human Approval Checkpoints
An agent can autonomously handle most of the work, but key outputs need human acceptance. A sensible approach is to place approval checkpoints at critical milestones—for example, before finalizing a plan, merging code, or sending content externally. When an approval passes, the framework continues; when it is rejected, the attached revision notes should be written into the task state as new context.
6. Practical Recommendations
When introducing a persistent agent framework into a real project, the following steps are recommended.
First, pick a pilot scenario with clear boundaries and controlled risk—such as document organization, scheduled report generation, or read-only data inspections. In the pilot phase, focus on validating state recovery and watchdog rules rather than scaling up task volume.
Second, implement deterministic logic and model reasoning separately. Build task scheduling, permission checks, and retry policies as ordinary code with unit tests; let the model handle only planning and content generation. This lets you use traditional engineering methods to keep the system predictable.
Third, scale up the number of tasks gradually. As concurrency grows, pay close attention to resource quotas and task isolation, so that one expensive task cannot starve the others.
Finally, keep collecting runtime data to tune the context assembly strategy and watchdog thresholds. The effectiveness of a persistent agent depends largely on polishing the engineering details, not on the strength of any single model.
7. Conclusion
The core of a persistent agent is freeing the task from the single session—keeping it coherent across sessions and isolated from other tasks. Achieving this requires a runtime framework that is independent of the model and handles state management, event scheduling, asynchronous interaction, separation of state and compute, and external oversight.
The two-layer architecture divides global scheduling from local execution; event-driven design reduces waiting overhead; asynchronous multi-channel interaction keeps communication flowing; separation of state and compute improves failure recovery; and the external watchdog provides a safety net that does not depend on the model checking itself. Together, these design choices let people step back from the execution details and focus on goal setting, result acceptance, and key decisions.
