state

A built-in way for agents to store application data, save it automatically, and synchronize changes with connected clients in real time. A client is an app or browser connected to the agent.

In plain words
What is it for?
Use it for data such as players, scores, and statuses that must survive restarts and stay synchronized between a server and connected clients, with TypeScript type checking.
Why use it?
It removes the need to build separate persistence and live-update handling for shared application state.

Agent

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add agents/cloudflare/agents/state
Clone the repo
git clone --depth 1 https://github.com/cloudflare/agents
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 3,238 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.03238
Opus 5 $0.00000 $0.01619
Sonnet 5 $0.00000 $0.00648
Haiku 4.5 $0.00000 $0.00324

Measured 2d ago against content hash be95d021db4a, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

state scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

docs/agents/state.md · 513 lines

How it starts

The opening of the file, as written. The whole thing — 513 lines — stays where its author put it; the contents beside it link to each section on GitHub.

State Management

Agents provide built-in state management with automatic persistence and real-time synchronization across all connected clients.

Overview

Agent state is:

  • Persistent - Automatically saved to SQLite, survives restarts and hibernation
  • Synchronized - Changes broadcast to all connected WebSocket clients instantly
  • Bidirectional - Both server and clients can update state
  • Type-safe - Full TypeScript support with generics
import { Agent } from "agents";

type GameState = {
  players: string[];
  score: number;
  status: "waiting" | "playing" | "finished";
};

export class GameAgent extends Agent<Env, GameState> {
  // Default state for new agents
  initialState: GameState = {
    players: [],
    score: 0,
    status: "waiting"
  };

  // React to state changes
  onStateChanged(state: GameState, source: Connection | "server") {
    if (source !== "server" && state.players.length >= 2) {
      // Client added a player, start the game
      this.setState({ ...state, status: "playing" });
    }
  }

  addPlayer(name: string) {
    this.setState({
      ...this.state,
      players: [...this.state.players, name]
    });
  }
}

Defining Initial State

Use the initialState property to define default values for new agent instances:

type State = {
  messages: Message[];
  settings: UserSettings;
  lastActive: string | null;
};

export class ChatAgent extends Agent<Env, State> {
  initialState: State = {
    messages: [],
    settings: { theme: "dark", notifications: true },
    lastActive: null
  };
}

Type Safety

The second generic parameter to Agent<Env, State> defines your state type:

// State is fully typed
export class MyAgent extends Agent<Env, MyState> {
  initialState: MyState = { count: 0 };

  increment() {
    // TypeScript knows this.state is MyState
    this.setState({ count: this.state.count + 1 });
  }
}

When Initial State Applies

Initial state is applied lazily on first access, not on every wake:

Read the full file on GitHub · 513 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 513 lines · 0 tokens per session scan A be95d021db4a

Subscribe to this mod's changes

state is an agent published in the GitHub repository cloudflare/agents (5,498 stars, last pushed 2d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 3,238 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.