Event-Driven and Sleep-Wake Architecture for Long-Horizon Autonomous Agents

    This article explores the engineering challenges of building long-horizon autonomous agents and proposes an event-driven, sleep-wake architecture as a reliable alternative to the "always-on" model. It details the core components of this architecture, including event inboxes and outboxes, short-cycle execution, follow-up mechanisms, hierarchical memory management, and robust exception handling. By decoupling event reception from model inference and prioritizing task recoverability, developers can build stable, resource-efficient agent systems suitable for production environments.

    In many people’s visions, a long-horizon autonomous agent operates like a digital employee that never clocks out: continuously reading web pages, polling interfaces, waiting for user messages, and thinking in the background until the task is completely finished.

    From an engineering perspective, however, this “always-on” design is typically unreliable. It continuously consumes model calling resources, repeatedly checks unchanged data, and generates massive amounts of invalid logs. If an external interface experiences an anomaly, the system may get stuck in prolonged retries, ultimately creating the illusion that “the process is still running, but the task is making no progress.”

    A more reasonable approach is to design the agent as an event-driven system: it remains in a low-activity state and is only awakened when a new event arrives, a scheduled time triggers, or a task needs to be advanced. Each time, the model only processes a single run cycle with clear boundaries. After completing the necessary work, it saves its state, writes outputs, and returns to a waiting state.

    This does not strip the agent of its autonomy; rather, it shifts “continuous autonomy” from inside the model to the peripheral system.

    1. Being Online 24/7 Does Not Mean the Model Runs Constantly

    Mobile devices provide an intuitive analogy for understanding this architecture. The device appears to always be capable of receiving messages, but it spends the vast majority of its time in a low-power state. It only briefly returns to an active state when a call, notification, alarm, or system task arrives, and enters sleep mode again once processing is complete.

    Long-horizon agents should follow a similar principle:

    1. The external system continuously receives events;
    2. Events are reliably recorded;
    3. The scheduler determines which events need immediate processing;
    4. The model is awakened and executes a single, time-bounded run;
    5. The run results are written to persistent storage;
    6. The system decides whether to send messages, wait for feedback, or schedule the next wake-up based on the results.

    The key distinction here is that the event reception and scheduling services are continuously online, not the model itself.

    Models are suited for phases that require understanding, reasoning, and decision-making, not for acting as high-frequency pollers. Separating these two types of responsibilities yields both lower resource consumption and better system stability.

    2. Core Structure: Event Inbox and Outbox

    A general-purpose long-horizon agent requires at least two types of persistent queues.

    2.1 Event Inbox

    The event inbox is used to store all inputs waiting to be processed, including:

    • New user messages;
    • State changes pushed by external systems;
    • Scheduled task expiration notifications;
    • Tool execution completion events;
    • Approval results or human feedback;
    • Failure retry notifications;
    • Task timeout and exception alerts.

    Events should not directly invoke the model; instead, they should first be written to a database, message queue, or other reliable storage. This approach offers several benefits.

    First, events will not be lost due to temporary model unavailability. Even if the inference service goes down, inputs remain in the queue and can be processed once it recovers.

    Second, it decouples event reception from event processing. The receiving service is only responsible for fast acknowledgment and persistence, while the model service can consume tasks gradually according to its own capacity.

    Third, the processing flow can be tracked through event statuses. For example, an event can transition through states like “pending, running, done, retry, failed,” preventing the system from relying solely on whether the process is alive to determine the task outcome.

    A simplified data structure can be represented as:

    1. Event {
    2. id: unique identifier
    3. type: event type
    4. payload: event content
    5. priority: priority level
    6. status: pending | running | done | retry | failed
    7. attempt_count: number of attempts
    8. created_at: creation time
    9. available_at: available processing time
    10. }

    Here, available_at is crucial. It allows the system to implement delayed processing and backoff retries, rather than entering an infinite loop immediately after a failure.

    2.2 Output Outbox

    Replies, notifications, or external operation requests generated by the model should also not depend directly on the current process to be sent out; they should be written to the outbox first.

    The outbox can store:

    • Text replies for the user;
    • Emails or in-app notifications to be sent;
    • Call requests to external systems;
    • Task status changes;
    • Suggestions requiring manual review;
    • Subsequent wake-up schedules.

    By adopting the outbox pattern, even if a send action temporarily fails, the system can retry it independently without re-executing the entire inference process. This avoids redundant model calls and reduces the risk of duplicate sends.

    In actual implementation, an idempotency identifier should be set for each output. For instance, if the same notification is consumed multiple times by the sending module, it should be recognized as the same business action, preventing the user from receiving multiple identical messages.

    3. Short-Cycle Execution: Do Not Let a Single Thought Prolong Indefinitely

    Long-horizon tasks should not be implemented as a single model call lasting hours or even days. A more controllable approach is to break the task down into multiple short-cycle runs.

    A single run typically includes the following steps:

    1. Read the current task state;
    2. Fetch events relevant to this decision;
    3. Determine if the task is still valid;
    4. Call necessary tools or data sources;
    5. Generate an intermediate conclusion;
    6. Update the task state and memory;
    7. Produce output or schedule the next wake-up;
    8. End the current run.

    This design is similar to splitting a long process into multiple recoverable transactions. Each run should have a clear beginning and end, and should not default to relying on context in memory existing long-term.

    For example, a task to “track the progress of a specific business initiative” can be broken down into:

    • Confirming the current state;
    • Querying the latest changes;
    • Determining if trigger conditions are met;
    • Generating an intermediate report;
    • Waiting for the next external feedback.

    If a certain step fails, the system only needs to continue from the most recently saved state, rather than re-executing the entire process.

    4. Follow-Up Mechanisms: Letting Agents “Schedule Their Next Wake-Up”

    A significant source of long-horizon autonomous capability is the follow-up mechanism.

    Traditional scheduled tasks often only support fixed cycles, such as executing once a day at a specific time. However, actual tasks are usually conditional: waiting for a reply, waiting for a file to be generated, waiting for an approval to complete, or waiting for an external state to change.

    Therefore, after completing its current round of work, the agent can create a new wake-up schedule:

    1. FollowUp {
    2. task_id: task identifier
    3. trigger_at: trigger time
    4. condition: optional trigger condition
    5. reason: scheduling reason
    6. status: scheduled | triggered | canceled
    7. }

    For example:

    • Check if feedback has been received in three days;
    • Confirm if data synchronization is complete in two hours;
    • Generate a summary on the morning of the next business day;
    • Continue execution when a certain state changes from “processing” to “completed”.

    It is important to note that the follow-up mechanism should not equate to unlimited polling. The system should prioritize using event notifications; only when the external system cannot provide notification capabilities should controlled polling be used, with maximum limits, minimum intervals, and timeout strategies in place.

    5. Memory and State: Saving “What is Needed Next” Instead of Everything

    Long-horizon tasks often last for days or even weeks. If every wake-up stuffs the entire history back into the model, it is not only costly but also leads to context redundancy and attention dispersion.

    A better approach is to save state hierarchically.

    5.1 Task State

    Record which stage the task is currently in, what has been completed, and what is planned for the next step. For example:

    1. TaskState {
    2. goal: task goal
    3. stage: current stage
    4. completed: completed items
    5. pending: pending items
    6. blockers: blocking reasons
    7. next_action: next action
    8. last_updated: last updated time
    9. }

    5.2 Working Memory

    Save recent and directly relevant information for the current task, such as the most recent tool return result, the latest user requirements, and the basis for the current decision.

    5.3 Long-Term Memory

    Only retain stable information that may be reused repeatedly later, such as user preferences, business rules, important constraints, and historical conclusions.

    The memory system also needs to set lifecycles. Temporary data should be cleaned up promptly, and expired information should not continue to participate in decision-making; otherwise, the agent may perform incorrect actions based on outdated facts.

    6. Exception Handling: Shifting from “Process Alive” to “Task Recoverable”

    The most dangerous state for a background program is not a crash, but appearing to run normally while repeatedly failing.

    Therefore, the system needs at least the following mechanisms:

    Timeout Control

    Model calls, tool access, and external requests should all have timeout limits set. A step cannot wait indefinitely; otherwise, it will occupy an execution slot for a long time.

    Bounded Retries

    There must be an upper limit on the number of retries, using incremental wait times. For deterministic errors, such as insufficient permissions or incorrect parameters, they should not be blindly retried but instead routed to manual processing or a failed task state.

    Circuit Breaker

    When a certain external dependency continuously fails, related tasks should be temporarily paused to prevent all agents from simultaneously initiating requests, which could cause a larger-scale outage.

    Dead Letter Queue

    Events that still fail after multiple processing attempts should enter a dead letter queue (DLQ) for manual analysis. Dead letter records need to retain the error reason, call chain, and the most recent input and output to facilitate problem identification.

    Idempotent Execution

    The same event may be delivered repeatedly due to network retries, so every critical action must possess idempotent capabilities. Especially when sending notifications, modifying data, and submitting external operations, one cannot simply rely on the assumption of “executing only once.”

    7. How to Evaluate the Effectiveness of This Architecture

    You cannot just look at the quality of the model’s answers; you also need to observe system operational metrics:

    • Average number of wake-ups per task;
    • Average input size per run;
    • Invalid polling ratio;
    • Latency from event generation to processing;
    • Task success completion rate;
    • Retry and timeout rates;
    • Duplicate output ratio;
    • Number of long-stalled tasks;
    • Resource consumption per unit task;
    • Human handover ratio.

    If a task is frequently awakened but rarely makes effective progress, it indicates issues with event filtering or state design. If a task re-reads large amounts of historical content every time, it means memory compression and state summarization are inadequate. If failures are primarily concentrated on external dependencies, strategies such as timeouts, circuit breaking, and degradation should be optimized, rather than simply increasing the number of model calls.

    8. Overall Principles for Production Environments

    Long-horizon autonomous agents can be summarized in one sentence: keep the peripheral system reliable, and keep the model briefly and efficiently active.

    Specifically, the following principles should be followed:

    1. Persist events first, then trigger inference;
    2. Decouple reception, inference, sending, and scheduling;
    3. Every run should have clear boundaries;
    4. All intermediate states must be persistable;
    5. External actions must support idempotency;
    6. Failures must be retryable, pausable, and capable of human handover;
    7. Prioritize event notifications, use polling cautiously;
    8. Let agents proactively schedule subsequent wake-ups rather than continuously occupying computing resources;
    9. Observe task progress through logs, metrics, and tracing systems;
    10. Treat “whether the task can recover” as a more important reliability metric than “whether the process is alive.”

    From this perspective, a truly mature autonomous agent is not a continuously running model, but a system composed of event-driven logic, task states, schedulers, tool executors, and the model working together. The model is responsible for making decisions at critical moments, while the infrastructure is responsible for ensuring events are not lost, states are recoverable, and actions are trackable.

    This is also the key for long-horizon agents to transition from demos to stable applications: not keeping the model awake forever, but waking it up at the right time to do the right job, and then safely returning to a waiting state.