PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 100 / 100
100%

Pause and Resume an AI Agent: Lifecycle States Explained

Pause and resume a running AI agent: the eight lifecycle states, valid transitions, suspend and resume from code or HTTP, and what happens to queued work.

Intermediate16 minAgent RuntimeDeploymentHuman-in-the-LoopObservability
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. ✓How to Test LLM Prompts and AI Agents in Python
  84. ✓AI Agent Evals in CI: Run Them on Every Pull Request
  85. ✓What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. ✓Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. ✓Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. ✓AI Agent Cron Jobs: Run an Agent on a Schedule
  89. ✓AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. ✓AI Agent File Watcher: Process New Files Automatically
  91. ✓Custom AI Agent Triggers: Wake an Agent From Any Source
  92. ✓AI Agent Event Filters: Skip Runs Before the LLM
  93. ✓AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. ✓Run Multiple AI Agents: One Runtime, Many Processes
  95. ✓AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. ✓AI Agent CLI: Start, Stop and Inspect Running Agents
  97. ✓AI Agent Monitoring Dashboard in the Terminal
  98. ✓Multi-Agent Event Bus: Chain Agents With Events
  99. ✓Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. ✓Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. ✓Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. ✓What Is Agentic RAG? How It Differs from Classic RAG
  53. ✓AI Agent Memory in Python: Short-Term and Long-Term
  54. ✓Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. ✓Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. ✓AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. ✓Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. ✓Self-Modifying AI Agent in Python: Open Mode & Limits
  59. ✓CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. ✓Migrate from AutoGen: Agent Framework, AG2 and More
  61. ✓What Is an LLM Guardrail? Types, Examples and Limits
  62. ✓Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. ✓AI Agent Guardrails in Python: Block Injection, Redact PII
  64. ✓NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. ✓AI-Based PII Detection and Redaction Tools for LLM Apps
  66. ✓Stop Secrets Leaking Into LLM Logs and Traces
  67. ✓AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. ✓AI Agent Network Egress: Limit Where Agents Can Connect
  69. ✓AutoGen Docker Task Isolation: Secure the Code Executor
  70. ✓SPIFFE for AI Agents: Workload Identity Without API Keys
  71. ✓On-Behalf-Of Auth for AI Agents: Act as Each User
  72. ✓AI Agent Production Checklist: What to Check Before Launch
  73. ✓Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. ✓What Is Human in the Loop AI? Approvals for AI Agents
  75. ✓AI Agent Notifications: Webhook and Slack Alerts in Python
  76. ✓AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. ✓Best AI Agent Observability Tools (2026), Compared
  78. ✓AI Agent Stuck in a Loop? How to Detect and Stop It
  79. ✓How to Run, Debug and Deploy an AI Agent in Python
  80. ✓AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. ✓How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. ✓AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. ✓How to Test LLM Prompts and AI Agents in Python
  84. ✓AI Agent Evals in CI: Run Them on Every Pull Request
  85. ✓What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. ✓Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. ✓Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. ✓AI Agent Cron Jobs: Run an Agent on a Schedule
  89. ✓AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. ✓AI Agent File Watcher: Process New Files Automatically
  91. ✓Custom AI Agent Triggers: Wake an Agent From Any Source
  92. ✓AI Agent Event Filters: Skip Runs Before the LLM
  93. ✓AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. ✓Run Multiple AI Agents: One Runtime, Many Processes
  95. ✓AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. ✓AI Agent CLI: Start, Stop and Inspect Running Agents
  97. ✓AI Agent Monitoring Dashboard in the Terminal
  98. ✓Multi-Agent Event Bus: Chain Agents With Events
  99. ✓Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

Sometimes you need a running AI agent to stop working for a while without shutting it down: an upstream system is in maintenance, a budget ran out, or someone wants to look at what it did before it does more. This guide explains how to pause and resume an AI agent safely. It covers the eight lifecycle states of a Promptise Foundry agent process, which transitions are allowed, how to suspend and resume from code and over HTTP, and what happens to triggers and queued events while the agent is paused.

[01]

How do you pause and resume an AI agent?

Suspend the process instead of stopping it. A suspended process keeps its model client, tools and triggers. Triggers still accept events and queue them, but no new run starts until you resume. A run that was already going finishes. In Promptise, suspend() and resume() move the process between the RUNNING and SUSPENDED states, and the state machine rejects anything else with a StateError:

Python
await process.suspend()   # RUNNING -> SUSPENDED; events queue up
print(process.status()["queue_size"])
await process.resume()    # SUSPENDED -> RUNNING; the queue drains

Key takeaways:

  • Suspend pauses work, not the process. Nothing is torn down, and nothing is lost from the queue.

  • Every state change is checked. Eight states, a fixed table of allowed transitions, and a StateError for the rest.

  • Several things suspend a process for you: idle timeout, budget limits and health anomalies. Only an idle suspension ends by itself, when the next trigger event arrives.

  • Queued events keep their order. After a resume they run in the order they arrived.

  • Suspending emits an event. process.suspended and process.resumed carry the reason, so alerts need no polling.


[02]

What is an agent process lifecycle?

A long-running agent is more than a model call. It holds connections to tools, listens to triggers, keeps a queue of work and runs in the background. A lifecycle is the set of states such a process can be in and the rules for moving between them. It answers questions an operator asks every day: is the agent working, paused, broken or gone, and what is it allowed to do next? A state machine that rejects invalid moves keeps the answers trustworthy. You can't "resume" an agent that crashed, and you can't start one twice.

In Promptise every AgentProcess owns a ProcessLifecycle. These are its states:

State

Meaning

CREATED

Registered, never started.

STARTING

Building the agent, connecting MCP servers, starting triggers.

RUNNING

Accepting and processing trigger events. An idle agent waiting for its next event is RUNNING too.

SUSPENDED

Paused. Triggers queue events; no new run starts.

AWAITING

Reserved. Defined in the table below, but the runtime never enters it.

STOPPING

Shutting down: cancelling runs, stopping triggers, closing connections.

STOPPED

Shut down cleanly. Can be started again.

FAILED

Too many failed runs, or a failed start. Can be started again, or stopped.

And the allowed transitions, printed from VALID_TRANSITIONS in step 1:

State diagram of an agent process with the states CREATED, STARTING, RUNNING, SUSPENDED, AWAITING, FAILED, STOPPING and STOPPED, and the calls and events that move a process between them, such as start(), suspend(), resume(), a trigger event for an idle process, stop() and max_lifetime.
FigureThe lifecycle states of an agent process and the transitions between them

Every transition is recorded as a ProcessTransition with the old and new state, a UTC timestamp, a reason and optional metadata. The list is the process's history, and listeners you register are called after each transition. A process with an event_notifier also emits an event for each change, such as process.suspended and process.resumed with their reason.

What changes the state

Cause

Transition

Undone by

suspend(), API POST .../suspend, dashboard suspend <name>

RUNNING → SUSPENDED

resume()

idle_timeout without a run, with nothing queued

RUNNING → SUSPENDED

The next trigger event, inject() or resume()

Budget on_exceeded="pause" or "escalate"

RUNNING → SUSPENDED

resume()

Health on_anomaly="pause", or "escalate" with an escalation target

RUNNING → SUSPENDED

resume()

max_consecutive_failures failed runs

→ FAILED

start() or the restart policy; stop() stops it

stop(), budget "stop", mission complete

→ STOPPING → STOPPED

start()

Restarts and failure handling have their own guide, AI agent auto-restart.


[03]

When to suspend an agent (and when to stop it instead)

Suspend when you expect to resume soon and want nothing lost:

  • A downstream system is in maintenance, and the agent's tools would fail or do damage.

  • You want to inspect what the agent did, or correct its instructions, before it acts again.

  • A budget or health check paused it, and a person decides whether it goes on.

Stop when the pause is long or open-ended:

  • A suspended process still holds its MCP connections, stdio server subprocesses and webhook ports. Stopping releases them.

  • Events keep piling up in memory while suspended, up to 1,000 per process. Stopping closes webhook ports, so senders get an error and retry later instead of handing events to an agent that won't run them.

  • A deployment or config change is coming. stop() and start() rebuild everything from the new config.

Never use suspension to "fix" a failing agent. A FAILED process can't be resumed, only started again or stopped.


[04]

What you need

  • Python 3.10 or later and Promptise Foundry 1.5.0 or later. The outputs below come from 1.9.0.

  • No API key. The examples use the fake OpenAI-compatible model server from the auto-restart guide, flaky_llm.py, with a delay setting so runs take a known time.

  • About 15 minutes.

>_Terminal
pip install "promptise>=1.5.0"

[05]

Step 1: Explore the state machine

ProcessLifecycle works on its own, without an agent, which makes it easy to learn and to test. This script prints the transition table, registers three listeners, walks through a pause and tries one invalid move:

Pythonstate_machine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""The process state machine on its own: transitions, StateError, listeners, snapshots."""
import asyncio
import json

from promptise.runtime import (
    VALID_TRANSITIONS,
    ProcessLifecycle,
    ProcessState,
    StateError,
)

print("valid transitions:")
for state, targets in VALID_TRANSITIONS.items():
    print(f"  {state.value:9} -> {', '.join(sorted(t.value for t in targets))}")


async def main() -> None:
    lc = ProcessLifecycle()  # starts in CREATED

    def audit(t) -> None:  # sync listener
        print(f"  audit: {t.from_state.value} -> {t.to_state.value} ({t.reason})")

    async def alert_on_pause(t) -> None:  # async listener
        if t.to_state is ProcessState.SUSPENDED:
            print(f"  alert: paused because {t.reason!r}")

    def broken(t) -> None:  # a listener that raises is logged and skipped
        raise RuntimeError("listener bug")

    lc.add_listener(audit)
    lc.add_listener(alert_on_pause)
    lc.add_listener(broken)

    print("\ntransitions:")
    await lc.transition(ProcessState.STARTING, reason="start() called")
    await lc.transition(ProcessState.RUNNING, reason="startup complete")
    await lc.transition(ProcessState.SUSPENDED, reason="budget exceeded",
                        metadata={"limit": "max_cost_per_day"})
    print("  can go to STARTING?", lc.can_transition(ProcessState.STARTING))
    try:
        await lc.transition(ProcessState.STARTING, reason="start() called")
    except StateError as exc:
        print(f"  StateError: {exc}")
    await lc.transition(ProcessState.RUNNING, reason="resume() called")

    print("\nhistory:")
    for t in lc.history:
        print(f"  {t.timestamp:%H:%M:%S.%f} {t.from_state.value:9} -> {t.to_state.value:9} {t.reason}")

    snapshot = lc.snapshot()
    restored = ProcessLifecycle.from_snapshot(json.loads(json.dumps(snapshot)))
    print(f"\nrestored: {restored!r}, last metadata: {restored.history[2].metadata}")


asyncio.run(main())
Output
valid transitions:
  created   -> starting, stopped
  starting  -> failed, running, stopping
  running   -> awaiting, failed, stopping, suspended
  suspended -> failed, running, stopping
  awaiting  -> failed, running, stopping
  stopping  -> failed, stopped
  stopped   -> starting
  failed    -> starting, stopping

transitions:
  audit: created -> starting (start() called)
  audit: starting -> running (startup complete)
  audit: running -> suspended (budget exceeded)
  alert: paused because 'budget exceeded'
  can go to STARTING? False
  StateError: Cannot transition from 'suspended' to 'starting'. Allowed targets: ['failed', 'running', 'stopping']
  audit: suspended -> running (resume() called)

history:
  22:43:22.717699 created   -> starting  start() called
  22:43:22.718374 starting  -> running   startup complete
  22:43:22.718478 running   -> suspended budget exceeded
  22:43:22.718564 suspended -> running   resume() called

restored: ProcessLifecycle(state='running', transitions=4), last metadata: {'limit': 'max_cost_per_day'}

What it shows:

  • StateError names the allowed targets. Starting a suspended process is invalid, and the message lists what is allowed instead. StateError is a ValueError. Check first with can_transition() when you are not sure.

  • Listeners can be sync or async. They run in registration order after the state has changed, so they can read the new state. The broken listener raised on every transition. The error was logged to stderr and skipped, and the transitions still happened. A listener can't veto a transition.

  • The history is complete and ordered, with the reason and metadata you passed. That is the audit trail of the process.

  • Snapshots round-trip through JSON. snapshot() returns the state and the full history as plain data, and from_snapshot() rebuilds a lifecycle from it.

AgentProcess registers its own listener first. It writes each transition to the journal when one is configured, and it emits process.failed and schedules restarts on FAILED. Your listeners run after it, through process.lifecycle.add_listener().


[06]

Step 2: Suspend a running process

Now suspend a real process. This one has a webhook trigger on port 9091 and a fake model that takes one second per call. The script sends one order, suspends the process while that order is running, and sends four more:

Pythonsuspend_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""Suspend a running agent process, let events queue up, then resume it."""
import asyncio
import os
import shutil
import time

import aiohttp

os.environ["OPENAI_BASE_URL"] = "http://127.0.0.1:8765/v1"  # fake model server
os.environ.setdefault("OPENAI_API_KEY", "sk-fake")

from flaky_llm import FlakyLLM
from promptise.runtime import (
    AgentProcess,
    JournalConfig,
    ProcessConfig,
    StateError,
    TriggerConfig,
)
from promptise.runtime.journal import FileJournal

T0 = time.monotonic()
URL = "http://127.0.0.1:9091/orders"


def log(message: str) -> None:
    print(f"{time.monotonic() - T0:5.1f}s  {message}")


def show(process: AgentProcess) -> None:
    s = process.status()
    log(f"state={s['state']} invocations={s['invocation_count']} queue={s['queue_size']}")


async def post(session: aiohttp.ClientSession, order: int) -> None:
    async with session.post(URL, json={"order": order}) as resp:
        log(f"POST order {order} -> HTTP {resp.status}")


async def main() -> None:
    shutil.rmtree("journal", ignore_errors=True)
    llm = FlakyLLM()
    llm.delay = 1.0  # each model call takes one second
    await llm.start()

    process = AgentProcess("orders", ProcessConfig(
        model="openai:gpt-5-mini",
        instructions="Check each new order.",
        triggers=[TriggerConfig(type="webhook", webhook_path="/orders", webhook_port=9091)],
        journal=JournalConfig(level="full", path="journal"),
    ))
    await process.start()

    async with aiohttp.ClientSession() as session:
        await post(session, 1)
        await asyncio.sleep(0.3)           # order 1 is now running
        await process.suspend()
        log("suspended while order 1 runs")
        for order in (2, 3, 4, 5):
            await post(session, order)
        await asyncio.sleep(2)
        show(process)                      # order 1 finished, 2-5 wait

        try:
            await process.suspend()
        except StateError as exc:
            log(f"suspend again: {exc}")

        await process.resume()
        log("resumed")
        await asyncio.sleep(5)
        show(process)

    entries = await FileJournal("journal").read("orders", entry_type="trigger_event")
    log(f"processing order: {[e.data['payload']['order'] for e in entries]}")
    states = await FileJournal("journal").read("orders", entry_type="state_transition")
    log(f"journaled transitions: {[e.data['to_state'] for e in states]}")
    await process.stop()
    await llm.stop()


asyncio.run(main())

The first half of the output:

Text
1
2
3
4
5
6
7
8
  0.3s  POST order 1 -> HTTP 202
  0.6s  suspended while order 1 runs
  0.6s  POST order 2 -> HTTP 202
  0.6s  POST order 3 -> HTTP 202
  0.6s  POST order 4 -> HTTP 202
  0.6s  POST order 5 -> HTTP 202
  2.6s  state=suspended invocations=1 queue=4
  2.6s  suspend again: Process 'orders': Cannot transition from 'suspended' to 'suspended'. Allowed targets: ['failed', 'running', 'stopping']

Three things happened:

  • The run in progress finished. Order 1 had started before the suspend, and invocation_count reached 1 while the process was suspended. suspend() doesn't cancel runs. If you need the agent to stop mid-run, use stop().

  • The trigger kept accepting events. Orders 2 to 5 got HTTP 202, the webhook's "accepted" answer, and waited in the queue. Senders can't tell a suspended agent from a busy one. That is usually what you want during a short pause.

  • A second suspend is an error. SUSPENDED → SUSPENDED is not a transition. The message names the process. Code that pauses from several places, such as a budget and a person, should check process.state first or catch StateError.


[07]

Step 3: Resume it and drain the queue

The second half of the same run:

Text
  2.6s  resumed
  7.6s  state=running invocations=5 queue=0
  7.6s  processing order: [1, 2, 3, 4, 5]
  7.6s  journaled transitions: ['starting', 'running', 'suspended', 'running']

resume() moved the process back to RUNNING, and the four queued orders ran, one second each. The journal, at level="full", recorded each event as it was processed and each state change.

The orders ran as 1, 2, 3, 4, 5: events queued during a suspension keep the order they arrived in. With more than one worker (concurrency above 1), runs overlap and can finish in a different order, so put a sequence number or timestamp in the payload when order matters. The trigger guides cover payload design.


[08]

Step 4: Suspend and resume over HTTP

In production, the person who pauses an agent is rarely in the same Python program. The runtime's control API exposes the same two methods. This script starts an AgentRuntime with one process, serves the API on localhost, and calls it:

Pythonapi_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""Suspend and resume a process over the runtime's HTTP API."""
import asyncio
import json
import os

import aiohttp

os.environ["OPENAI_BASE_URL"] = "http://127.0.0.1:8765/v1"  # fake model server
os.environ.setdefault("OPENAI_API_KEY", "sk-fake")

from flaky_llm import FlakyLLM
from promptise.runtime import AgentRuntime, OrchestrationAPI, ProcessConfig

BASE = "http://127.0.0.1:9100/api/v1/processes/orders"


async def call(session: aiohttp.ClientSession, method: str, path: str = "", full=False) -> None:
    async with session.request(method, BASE + path) as resp:
        body = await resp.json()
        if method == "GET" and not full:
            body = {"state": body["state"], "queue_size": body["queue_size"]}
        print(f"{method} {path or '/'} -> {resp.status} {json.dumps(body, indent=2 if full else None)}")


async def main() -> None:
    llm = FlakyLLM()
    await llm.start()
    async with AgentRuntime() as runtime:
        await runtime.add_process("orders", ProcessConfig(
            model="openai:gpt-5-mini", instructions="Check each new order.",
        ))
        await runtime.start_all()
        api = OrchestrationAPI(runtime, host="127.0.0.1", port=9100)  # loopback: no token
        await api.start()
        async with aiohttp.ClientSession() as session:
            await call(session, "POST", "/suspend")
            await call(session, "GET", full=True)    # the full status snapshot
            await call(session, "POST", "/suspend")   # already suspended
            await call(session, "POST", "/resume")
            await call(session, "GET")
        await api.stop()
    await llm.stop()


asyncio.run(main())
Output
POST /suspend -> 200 {"name": "orders", "suspended": true, "state": "suspended"}
GET / -> 200 {
  "name": "orders",
  "process_id": "e227c635-7e78-4e7a-8b92-e05f87baf5a8",
  "state": "suspended",
  "execution_mode": "strict",
  "invocation_count": 0,
  "consecutive_failures": 0,
  "restart_count": 0,
  "journal_enabled": false,
  "trigger_count": 0,
  "dynamic_trigger_count": 0,
  "custom_tool_count": 0,
  "rebuild_count": 0,
  "spawned_process_count": 0,
  "conversation_messages": 0,
  "has_memory": false,
  "suspend_reason": "manual",
  "queue_size": 0,
  "dead_letter_count": 0,
  "filtered_count": 0,
  "pending_retries": 0,
  "uptime_seconds": 0.002513916988391429,
  "hook_count": 0,
  "triggers": []
}
POST /suspend -> 400 {"error": {"code": "SUSPEND_FAILED", "message": "Process 'orders' can't be suspended in state 'suspended'", "error_id": "1c96257c6270"}}
POST /resume -> 200 {"name": "orders", "resumed": true, "state": "running"}
GET / -> 200 {"state": "running", "queue_size": 0}

POST /api/v1/processes/{name}/suspend and .../resume call suspend() and resume() and answer with the new state. A StateError comes back as HTTP 400 with the code SUSPEND_FAILED or RESUME_FAILED, a message that names the current state, and an error_id; the exception itself is logged on the server under that id. GET /api/v1/processes/{name} returns the full status snapshot of the process.

On localhost the API needs no token. Bound to any other address it refuses to start without auth_token, and every route except the health check requires it. The AI agent control API covers authentication, the Python client and every route.

Read a status snapshot

status() (and the GET route) returns a plain dict. The fields that matter for pausing:

Field

Use

state

The lifecycle state as a string.

suspend_reason

Why it is suspended: manual, idle, budget, health or rewind. None when it isn't.

queue_size

Events waiting. Grows while suspended.

invocation_count

Completed runs. Frozen while suspended, except for a run that was in flight.

dead_letter_count

Events that won't run. Should not grow while suspended.

uptime_seconds

Time since the last start, including time spent suspended.

consecutive_failures, restart_count

Failure streak and restart streak.

The snapshot has no "suspended since" time. Read it from process.lifecycle.history[-1], or from the journal's state_transition entries over the API.


[09]

Step 5: Know what suspends a process by itself

You are not the only one who suspends processes. Budget limits (on_exceeded="pause"), health anomalies (on_anomaly="pause" or "escalate") and idle_timeout do it too. A budget or health suspension stays until something calls resume(). AI agent cost control and AI agent health monitoring cover those two. idle_timeout works differently: the process wakes up by itself. This script also subscribes to the process's events:

Pythonidle_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""idle_timeout suspends a quiet process; the next trigger event resumes it."""
import asyncio
import os
import time

os.environ["OPENAI_BASE_URL"] = "http://127.0.0.1:8765/v1"  # fake model server
os.environ.setdefault("OPENAI_API_KEY", "sk-fake")

from flaky_llm import FlakyLLM
from promptise import CallbackSink, EventNotifier
from promptise.runtime import AgentProcess, ProcessConfig, TriggerEvent

T0 = time.monotonic()


def log(message: str) -> None:
    print(f"{time.monotonic() - T0:5.1f}s  {message}")


def on_event(event) -> None:  # process.suspended and process.resumed carry a reason
    log(f"event {event.event_type} reason={event.data['reason']}")


async def main() -> None:
    llm = FlakyLLM()
    llm.delay = 1.5  # a model call takes 1.5 seconds
    await llm.start()
    notifier = EventNotifier(sinks=[CallbackSink(on_event, events=["process.suspended", "process.resumed"])])
    process = AgentProcess("digest", ProcessConfig(
        model="openai:gpt-5-mini",
        instructions="Summarize each event.",
        idle_timeout=2.0,        # suspend after 2 s without a run
        heartbeat_interval=1.0,  # the idle check runs on every heartbeat
    ), event_notifier=notifier)
    process.lifecycle.add_listener(
        lambda t: log(f"{t.from_state.value} -> {t.to_state.value} ({t.reason})")
    )
    await process.start()
    await asyncio.sleep(2.6)
    log(f"suspend_reason={process.suspend_reason}")

    for n in range(3):  # no resume() call: the first event wakes the process
        await process.inject(TriggerEvent(trigger_id="manual", trigger_type="manual",
                                          payload={"n": n}))
    await asyncio.sleep(6)
    s = process.status()
    log(f"state={s['state']} invocations={s['invocation_count']} queue={s['queue_size']}")
    await process.stop()
    await llm.stop()


asyncio.run(main())
Output
  0.0s  created -> starting (start() called)
  0.3s  starting -> running (startup complete)
  2.3s  running -> suspended (suspended (idle))
  2.3s  event process.suspended reason=idle
  2.9s  suspend_reason=idle
  2.9s  suspended -> running (resumed (trigger))
  2.9s  event process.resumed reason=trigger
  8.9s  state=running invocations=3 queue=0
  8.9s  running -> stopping (stop() called)
  8.9s  stopping -> stopped (shutdown complete)

The process was suspended 2 s after startup because nothing had run, and suspend_reason says idle. The script never calls resume(): the first injected event woke the process, with the reason trigger, and all three events ran. The idle clock restarts on every resume, and a process with events queued or running never counts as idle, so it stayed RUNNING while it worked. It suspends itself again once it has been quiet for idle_timeout seconds.

That makes idle_timeout a way to mark a quiet agent as paused without losing its triggers. A webhook or cron event still reaches it and wakes it. Budget, health and manual suspensions don't end this way: they wait for resume().


[10]

The complete example

Text
1
2
3
4
5
6
pause-resume/
├── flaky_llm.py        # fake OpenAI-compatible model with a delay setting
├── state_machine.py    # ProcessLifecycle, StateError, listeners, snapshots (step 1)
├── suspend_demo.py     # suspend mid-run, queue events, resume (steps 2-3)
├── api_demo.py         # suspend and resume over the control API (step 4)
└── idle_demo.py        # idle_timeout suspension and the wake-up by a trigger (step 5)
>_Terminal
pip install "promptise>=1.5.0"
python state_machine.py
python suspend_demo.py    # uses ports 8765 and 9091
python api_demo.py        # uses ports 8765 and 9100
python idle_demo.py

To run against a real model, remove the two os.environ lines and the FlakyLLM calls, and set OPENAI_API_KEY.


[11]

Running it in production

Alert when a process is suspended

A budget that pauses an agent at 3 a.m. is invisible until someone checks. Give the process an event notifier. It then emits process.suspended with the reason, and process.resumed when it continues. A webhook sink posts the suspension to your chat (config is the process's ProcessConfig):

Python
1
2
3
4
5
6
7
8
9
import os

from promptise import EventNotifier, WebhookSink
from promptise.runtime import AgentProcess

notifier = EventNotifier(sinks=[
    WebhookSink(os.environ["ALERT_WEBHOOK_URL"], events=["process.suspended"]),
])
process = AgentProcess("orders", config, event_notifier=notifier)

The event's reason is manual, idle, budget, health or rewind. Filter out idle if quiet agents suspend often. See AI agent notifications.

Keep the history

lifecycle.history lives in memory and is gone when the program exits. With JournalConfig(level="checkpoint") or higher, every transition is also written to the journal as a state_transition entry with its reason, which survives restarts and is readable over the API. Durable AI agents explains the journal.

Bound the pause

A suspended process queues events in memory, up to 1,000. When the queue is full, a webhook trigger answers 503 and other triggers wait until there is room. For pauses longer than a few minutes, stop() the process: its webhook port closes and senders retry later, instead of filling a queue that may be lost. If a person must decide whether a paused agent goes on, record who paused it and why, for example with process.record_operator_action() in the journal, and review paused processes on a schedule.

Don't build on AWAITING

AWAITING is in the state enum and the transition table, and resume() accepts it, but no code in the runtime puts a process into it. An agent waiting for its next trigger reports RUNNING. Treat AWAITING as reserved; dashboards that count "waiting" agents should count RUNNING processes with an empty queue.


[12]

Common problems and fixes

Symptom

Cause

Fix

StateError: Cannot transition from 'suspended' to 'suspended'

Suspending twice, often a budget and a person at once

Check process.state first, or catch StateError

resume() raises on a broken agent

A FAILED process can't be resumed

stop(), then start(), after fixing the cause

A suspended process still finished one run

suspend() doesn't cancel a run in progress

Use stop() to end runs immediately

A process paused itself and nobody noticed

No one listens for its events

Give it an event_notifier with a sink for process.suspended

A quiet process shows SUSPENDED

idle_timeout suspended it (suspend_reason is idle)

Nothing to do: the next trigger event wakes it

The API answers 400 SUSPEND_FAILED

The process isn't RUNNING

Read state from GET /api/v1/processes/{name} first


[13]

Limitations

  • No timed pause. There is no "suspend for 30 minutes". Schedule the resume() yourself, or use a cron job that calls the API.

  • No automatic resume after budget or health. Those suspensions stay until something calls resume(). Daily budget resets don't resume a process. Only an idle suspension ends by itself.

  • Suspension is in memory. If the program restarts, every process starts fresh in RUNNING, and queued events are gone. The journal keeps the record, not the queue.

  • No per-trigger pause. Suspending pauses all of a process's triggers at once. To pause one source, remove or filter that trigger.

  • AWAITING is unused, as described above.


[14]

Frequently asked questions

What is the difference between suspending and stopping an AI agent?

Suspending pauses work but keeps everything set up: the model client, MCP connections and triggers stay, and new events wait in a queue. Stopping tears all of that down: runs in progress are cancelled, triggers stop, and webhook ports close. Suspend for short pauses you will resume, and stop for long ones or before a config change.

Does a paused AI agent lose events?

Not while the program keeps running. Triggers accept events during a suspension, and they wait in the process queue until you resume. They are held in memory, though, so they are lost if the program exits. After the resume they run in the order they arrived.

Can I pause an AI agent in the middle of a task?

suspend() stops new runs from starting, but a run that has already begun finishes. To end a run immediately, stop the process. For a pause inside a run, before a specific tool call, use human approval on that tool instead of suspension.

What does StateError mean?

It means the code tried a transition the lifecycle doesn't allow from the current state, such as suspending a process that is already suspended, or resuming one that failed. The message names the current state, the target and the allowed targets. Check with can_transition() or read process.state first.

What are the states of an AI agent process?

Promptise processes have eight: CREATED, STARTING, RUNNING, SUSPENDED, AWAITING, STOPPING, STOPPED and FAILED. A healthy agent waiting for work is RUNNING. SUSPENDED is a pause, FAILED means too many failed runs or a failed start, and AWAITING is reserved and never entered.

How do I pause an AI agent from another service?

Run the control API next to the runtime and call POST /api/v1/processes/{name}/suspend, then .../resume later. Use a bearer token for anything but localhost. A state that doesn't allow the change returns HTTP 400 with the reason.


[15]

Next steps

  • Your first long-running agent, end to end: deploy AI agents in production.

  • What happens after FAILED: AI agent auto-restart.

  • Every route of the HTTP API: AI agent control API.

  • Tell a running agent what to do instead of pausing it: message a running AI agent.

  • Pause and stop as steps of a containment plan: AI agent kill switch.

  • The governance that pauses agents: the autonomous AI agent runtime.

  • Reference: process lifecycle and the control API in the Promptise docs.

← PreviousDistributed AI Agents: Run Agents Across Many MachinesPath completeBack to the overview →