Pausing and Resuming Agents Through API Calls
Introduction: Adding Lifecycle Control to Agent APIs
In the previous lesson, you implemented database persistence and progress callbacks that save the agent's state after each step. This allows clients to monitor progress in real time, but they still have no control over the agent once it starts running. Now it's time to complete Factor 6 — Launch / Pause / Resume with simple APIs. You already have the /agent/launch endpoint from lesson one and the durable persistence layer from lesson two; in this lesson, you add the /agent/pause and /agent/resume endpoints that give users the power to stop expensive computations temporarily or correct mistakes without losing progress.
These endpoints are standard Express route handlers registered with app.post(...). Input validation uses the requireStringField(...) helper already present in the codebase; all state reads and writes go through the StateStore, and long-running execution is managed with void runAgentInBackground(...), which starts the agent asynchronously without blocking the HTTP response. You will implement a cooperative pause mechanism that lets agents stop gracefully between steps.
How the Pause Mechanism Works
Unlike forcefully terminating a running process, a cooperative pause lets the agent finish its current step before stopping. The flow works like this:
- A client calls
/agent/pause, which usesstore.update(...)to flip the persisted status to"paused". - After each step, the progress callback running inside
runAgentInBackgroundcallsstore.get(stateId)to read the latest persisted state. - If the persisted status is
"paused", the callback writesupdatedState.status = "paused"onto the in-memory state object and saves it, then returns. - Because the agent loop's continuation condition reads the
statusfrom that same in-memory state object, it exits on the next check.
The agent never stops mid-step — it always completes the current operation and only then discovers the pause signal. This keeps the state consistent and all fields properly synchronized, which is exactly what Factor 6 calls for: the agent can checkpoint, wait, and resume reliably across time.
Modifying the Progress Callback to Detect Pause Requests
In the previous lesson, the progress callback simply saved each updated state to the database. To support pause detection, it needs one extra check. The callback is defined inline — inside runAgentInBackground — and is async, making it ready for any asynchronous work that may be needed later:
After each step, the callback reads the record from the store with store.get(stateId). This is a fast, synchronous lookup (backed by SQLite) that returns the most recently persisted version of the state. If that record's status is "paused", the callback knows that a /agent/pause request arrived while the step was running. It writes "paused" back onto updatedState — the live object the agent loop is reading — saves it, and returns early. The agent loop sees the updated status on its next iteration and exits. In the normal case where no pause was requested, the callback calls store.save(updatedState) as before.
Implementing the Pause Endpoint
The pause endpoint only needs one piece of data from the client: the id of the agent run to pause. Rather than defining a separate request class, the handler validates the request body directly using requireStringField:
requireStringField checks that the request body is a plain object containing "id" as a non-empty string and throws an HttpError(400, ...) immediately if that is not the case. Express's error middleware then serializes the error to a JSON response automatically, keeping all validation logic in one place and out of the route logic itself.
Creating the Pause Route Handler
With input validation handled, the route sets the pause signal using store.update(...):
A successful call to this endpoint returns the updated state snapshot. Notice how the status has flipped to "paused" even if the agent is still finishing its current step:
store.update takes the id and a transformer function that receives the current state and returns the new one. In this teaching implementation, it is a convenience wrapper around a separate read-transform-save sequence; it is not an atomic compare-and-swap, so production multi-worker APIs should use a transaction or conditional SQL update such as UPDATE states SET status = ? WHERE id = ? AND status = ? for lifecycle transitions.
Inside the transformer, the handler guards against invalid transitions: pausing an agent that is already "complete", "failed", or "paused" makes no sense, so an HttpError(400, ...) is thrown with the current status included in the message. If store.update returns nothing, the id did not match any record and a 404 is returned. On success, the route responds with the updated state object.
Adapting the Background Runner for Resume Support
To support both fresh launches and resumes, runAgentInBackground accepts an optional workingState parameter:
When workingState is undefined — a fresh launch — the expression workingState ?? store.get(stateId) loads the initial state from the store. When workingState is provided (a resume), that object is used directly — the resume endpoint has already persisted "running" before calling this function, so the stored and in-memory states are already consistent.
The try/catch block at the function level ensures that any unexpected error thrown by the agent — network failures, tool errors that escape normal handling — is caught and written to the store as status: "failed" with the error message recorded in the error field. This prevents the agent from silently disappearing; clients can always query /agent/state/:stateId and find out what went wrong.
Implementing the Resume Endpoint
Like the pause endpoint, the resume endpoint only requires the agent's id from the client. Input validation uses the same requireStringField helper:
If "id" is missing or is not a non-empty string, requireStringField throws an HttpError(400, ...) before any store interaction happens, keeping the route handler free of manual type-checking boilerplate.
Creating the Resume Route Handler
The resume handler reads the current state, validates that starting a new execution makes sense, persists the "running" status, and fires off the background loop:
The response confirms the agent is back in the "running" status and has cleared any previous errors:
The 409 Conflict response is a lightweight guard for this single-process teaching implementation: if a request observes the workflow as already "running", it refuses to start another background task. It should not be treated as a complete concurrency guarantee for nearly simultaneous requests; production code should make the status transition atomic with a transaction, a conditional UPDATE, or another locking mechanism.
Before restarting execution, the handler spreads current into a new object, sets status: "running", and clears any previous error with error: null. This matters after a "failed" run: the stale error message from a previous attempt should not persist into the new execution. The call to store.save(...) persists this clean starting state and returns the saved object as workingState.
void runAgentInBackground(id, workingState) starts the agent in the background without blocking. The void operator intentionally discards the returned Promise — the route does not wait for the agent to finish; it immediately responds with workingState so the client knows execution has restarted.
Testing Launch and Pause
The following TypeScript script tests the launch and pause flow end to end. It uses the native fetch API and parses responses as typed State objects:
Running this part of the script produces the following logs. You can see the agent has been paused and captured its current progress, including any pending tool calls:
After launching, the script waits two seconds to give the agent time to begin running. It then attempts to pause. Because the agent runs concurrently, there is a genuine race: if the agent finishes within those two seconds, the pause request will arrive too late and receive a 400 response.
Testing Resume and Monitoring Completion
The script checks whether the pause succeeded before attempting a resume, then polls until the agent reaches a terminal state:
The polling logic shows the agent picking up exactly where it left off:
The if (pauseResponse.ok) branch handles the success case — it logs the paused state snapshot and immediately sends a resume request. The polling loop calls /agent/state/:stateId every second. When a terminal state is detected, it prints the final_answer and breaks out. The fact that the agent reached "complete" after being paused confirms the lifecycle logic is sound.
Summary and Next Steps
You have now fully implemented Factor 6 — Launch / Pause / Resume with simple APIs. Your agent's lifecycle is modeled explicitly through three Express route handlers: /agent/launch, /agent/pause, and /agent/resume. The cooperative pause mechanism ensures agents always stop gracefully between steps by using the inline async progress callback to propagate the "paused" status from the store back into the live state object. The resume endpoint validates state, clears prior errors, and restarts execution with void runAgentInBackground(...) — all without blocking the HTTP response. In the next lesson, you will implement Factor 7 — Contact humans with tool calls, enabling agents to proactively request information from users when they need it, treating human escalation as a first-class tool with structured requests and recorded outputs.
