Long-running autonomous agent: work that outlives one run

A long-running agent saves its state, sleeps, and resumes across hours or days, with budgets and approvals around it. Use it for jobs too long for one context window or one sitting.

Long-running agent in 60 seconds

  • What: an agent whose task spans many runs over hours or days, resuming each time from saved state.
  • Key idea: the state lives in storage, not in the model's context or in a process that must stay alive.
  • Best for: research, migrations, monitoring, and clean-up jobs that are too big for one sitting.
  • Weak spots: drift from the goal, runaway cost, stale assumptions after a long pause, and unattended risky actions.
  • Design rule: budgets apply to the whole task, and risky steps wait for a person.

Where this type fits

In the hub, the long-running agent belongs to the family defined by the kind you build, with the tool-using, coding, browser, and voice agents. It is less about how the agent decides and more about how it survives time. Inside each run it may plan, call tools, or reflect. What is new is the scaffolding that lets those runs chain together safely.

The problem it solves

Some jobs are simply bigger than one run. Updating a thousand product descriptions, watching a data feed for a week, migrating an old codebase, or compiling a market report from fifty sources. If you try to do this in a single loop, three things go wrong.

First, the context fills up. Every step adds text, and eventually the model can no longer see its early decisions, or the call fails. Second, the process is fragile. A restart, a deployment, or a network error in hour three loses everything, and you start again from nothing. Third, nobody is in control. An agent left running with no limits can spend a large budget, repeat a mistake a thousand times, or take a risky action while everyone is asleep.

The long-running agent answers each problem. It writes its progress to durable storage after each run, so memory does not depend on one context window. It treats every run as short and restartable. And it wraps the whole task in budgets and approval points. The idea echoes MemGPT (Packer et al., 2023), which borrows virtual memory from operating systems to move information between a limited main context and external storage. Here the same move is applied to a whole task rather than to a single conversation.

How it works

  • Define the task and budgets: state the goal, a finish test, and limits for the whole task, such as total cost, total runs, and a deadline.
  • Run in short bursts: each run loads the saved state, does a bounded amount of work with its usual loop, and stops. A run might be a few minutes.
  • Checkpoint: at the end of a run, and after any step that must not repeat, the agent writes its state: the plan, what is done, notes, and counters.
  • Sleep and wake: a scheduler or a queue starts the next run on a timer or when an event arrives. Nothing needs to stay in memory between runs.
  • Pause for approval: when the agent reaches a risky step, it saves state, asks a person, and stops. The run resumes when the answer comes.
  • Finish or stop: the task ends when the finish test passes, a budget runs out, or a person cancels. The agent then reports what was done and what was not.
A long task is a chain of short runs joined by saved state, with a human gate before risky steps.

The diagram shows that time passes between boxes, but the agent does not. Between run 1 and run 2 there is only a stored record and a timer. If the server restarts during that gap, nothing is lost. The next run reads the record and carries on.

Two points deserve care. The saved state must hold enough to continue without the old conversation: the goal, the plan, a progress list, and short notes on what was learnt. And the budgets belong to the task, not to each run. If each run had its own fresh limit, a task could run for ever by spending a little each time.

A worked example

Acme Retail asks an agent to review 600 supplier listings and flag those with missing safety information. Total budget: 40 runs and a spend of 25 units. Deadline: Friday.

  • Run 1 (Monday, 09:00). The agent loads an empty state, writes a plan: 'work through listings in batches of 30, record gaps, then summarise'. It handles batch 1, finds 4 listings missing safety sheets, and writes the checkpoint: {done: 30, flagged: [L-017, L-022, L-025, L-029], next_batch: 2, runs_used: 1, spend: 0.6}.
  • Wake-up. A scheduler starts the next run in 30 minutes. In between, the server is redeployed. Nothing is lost.
  • Run 2. The agent reads the checkpoint, and processes batch 2. It notices that supplier Delta Foods uses a different file format and adds a note: 'Delta Foods listings store safety data under the notes field.' This note goes into the saved state, so later runs benefit.
  • Run 14 (Wednesday). The agent proposes to email suppliers asking for missing sheets. That is a risky step, because it contacts outside people. It saves state, requests approval, and stops. A manager reads the draft, edits one line, and approves the next morning.
  • Run 15. The agent resumes from the saved state, sends the approved emails, and logs each one so it cannot send twice.
  • Run 21 (Thursday). All 600 listings are done. The finish test passes. The agent writes a report with 37 flagged items, 20 runs used of 40, and spend of 12.4 of 25.

The task spanned four days and about twenty short runs, and it survived a redeployment and a human delay.

A checkpoint record after run 14 (illustrative) (json)
{
  "task_id": "acme-listing-review-01",
  "goal": "Flag listings with missing safety information",
  "status": "waiting_for_approval",
  "plan": ["review batches", "request missing sheets", "summarise"],
  "progress": { "listings_done": 420, "flagged": 29 },
  "notes": ["Delta Foods stores safety data in the notes field"],
  "pending_action": { "type": "send_email", "draft_id": "d-88" },
  "budget": { "runs_used": 14, "runs_max": 40, "spend": 8.1, "spend_max": 25 },
  "version": 14
}

Building it

The sketch below is one run of the loop. The store, llm, tools, and ask_human objects are placeholders. What to copy is the shape: load state, check budgets first, do bounded work, checkpoint, and stop at risky steps.

One bounded run that loads, works, and checkpoints (illustrative) (python)
import time

MAX_STEPS_PER_RUN = 15        # keep each run short and restartable
MAX_SECONDS_PER_RUN = 240
RISKY_ACTIONS = {'send_email', 'delete', 'publish', 'pay'}

# Placeholders: store, llm, tools, and ask_human stand in for your own parts.
def run_once(task_id, store, llm, tools, ask_human):
    state = store.load(task_id)               # the only memory between runs
    b = state['budget']

    # Budgets cover the whole task, so check them before any work.
    if b['runs_used'] >= b['runs_max'] or b['spend'] >= b['spend_max']:
        state['status'] = 'budget_exhausted'
        store.save(task_id, state)
        return state

    started = time.time()
    for _ in range(MAX_STEPS_PER_RUN):
        if time.time() - started > MAX_SECONDS_PER_RUN:
            break
        step = llm.generate(goal=state['goal'], plan=state['plan'],
                            progress=state['progress'], notes=state['notes'][-10:])
        if step['name'] == 'finish':
            state['status'] = 'done'
            break
        if step['name'] in RISKY_ACTIONS:
            # Why: save first, so the pause survives a restart.
            state['status'] = 'waiting_for_approval'
            state['pending_action'] = step
            ask_human(task_id, step)
            break
        result = tools.call(step)               # tools must be safe to retry
        state['progress'] = result['progress']
        state['notes'] += result.get('notes', [])
        b['spend'] += result['cost']

    b['runs_used'] += 1
    state['version'] += 1                      # lets a reader spot stale copies
    store.save(task_id, state)                 # checkpoint at the end of every run
    return state

Design decisions

  • State storage: use a durable database row or document per task, with a version number. Default to one writer at a time, using a lock or a compare-and-set update, so two runs cannot overwrite each other.
  • Wake-up mechanism: use a scheduler for timed work and a queue for event-driven work. See message queues. Both let the process shut down between runs.
  • Run length: keep runs to minutes. Short runs are cheap to retry and easy to inspect. Long ones lose more when they fail.
  • Idempotent actions: every tool call that changes something should carry a key so a retry does not repeat it. Record sent emails and created records in the state. See idempotency.
  • Context hygiene: do not replay the full history each run. Load the goal, plan, progress, and the latest notes. Summarise old notes so the list stays short. The tiered memory page shows the pattern.
  • Budgets and kill switch: cap runs, spend, and calendar time per task, and offer a cancel command that takes effect at the next run. Default to a low cap and raise it deliberately.
  • Approval: require a person for sending, paying, deleting, and publishing. Notify them by message, expire stale requests, and never let the agent approve its own step.

Measuring it

  • Task completion rate: the share of tasks that reach their finish test within budget, checked against the real outcome, not the agent's claim.
  • Goal drift: sample checkpoints midway and have a reviewer score how well the current plan still matches the original goal, on a simple three-point scale.
  • Cost per completed task: total model and tool spend divided by tasks finished. Watch the 90th percentile as well as the mean.
  • Resume correctness: deliberately kill runs in tests, then check that the final result is identical to a run with no interruption, with no duplicated actions.
  • Approval wait and rejection rate: how long steps wait for a person, and how often they are rejected. A high rejection rate shows the agent proposes poor actions.
  • Runs per task: the mean and the 90th percentile. A growing figure often signals looping or an unclear finish test.

When to use it, and when not to

SituationUse this type?Why
Reviewing hundreds of records over several daysYesThe job exceeds one context window and benefits from saved progress.
Watching a data feed and acting on changesYesEvent-driven wake-ups fit, and state carries what has been seen.
A question that a single run answers in a minuteNoA plain agent is simpler and cheaper.
Tasks with an unclear finish lineNot yetWithout a finish test the agent drifts and spends. Define done first.
Actions that cannot be undone and are unreviewedNoUnattended risk is too high. Add a human checkpoint.
Work that must finish in secondsNoThe design trades speed for durability.

Trade-offs

DimensionEffectWhat to do about it
QualityCan finish big jobs, but small errors can build up over many runs.Check progress at set points, and keep notes short and accurate.
LatencyResults arrive over hours or days, not seconds.Show progress to users and send updates at milestones.
CostMany runs add up, and idle loops quietly spend.Set whole-task budgets, alerts at 50 and 80 percent, and a hard stop.
ComplexityYou need storage, scheduling, locking, and approval flows.Reuse a queue and a database you already run, and start with one task type.
Failure modesDrift, duplicate actions, stale facts after a pause, and forgotten tasks.Use idempotency keys, re-check key facts on resume, and alert on stuck tasks.

A planning agent writes a plan and follows it within a single run. A long-running agent can use the same planning, but it must also save the plan and survive gaps in time. The planning part is about deciding. The long-running part is about durability and control.

The human checkpoint pattern is the natural partner, because long unattended tasks nearly always need a pause for approval. For how old notes move out of the prompt and into storage, see tiered memory.

What this means for your role

Common mistakes

Further reading

  • Types of AI agents: the hub that compares all agent types.
  • MemGPT (Packer et al., 2023): borrows the idea of an operating system's virtual memory, moving information between a limited main context and external storage.
  • Human checkpoint: pausing a run for a person to approve, edit, or reject.
  • Idempotency: making retries safe.

A long-running agent is a short-run agent plus durable state, whole-task budgets, and human gates. Get those three right and the length of the job stops being the hard part.

Search topics

↑↓ to move · Enter to open · Esc to close