Skip to content

Class: AgentState

@providerprotocol/agents


@providerprotocol/agents / index / AgentState

Defined in: src/state/index.ts:63

Immutable agent state container for tracking execution context.

AgentState captures the complete execution state of an agent at any point in time, including conversation history, execution metadata, reasoning traces, and sub-agent execution records. All operations return new instances, leaving the original state unchanged.

The immutable design enables:

  • Safe concurrent access without locks
  • Easy state rollback and history tracking
  • Predictable debugging with state snapshots
  • Simple serialization for checkpointing

Each state transition generates a new UUID to uniquely identify the snapshot.

// Create initial state
const state = AgentState.initial();
// Add messages immutably
const state2 = state.withMessage(new UserMessage('Hello'));
const state3 = state2.withMessage(new AssistantMessage('Hi there!'));
// Add reasoning traces
const state4 = state3.withReasoning('User greeted me, responding politely.');
// Serialize for persistence
const json = state4.toJSON();
const restored = AgentState.fromJSON(json);

readonly id: string

Defined in: src/state/index.ts:65

Unique identifier for this state snapshot (UUIDv4)

AgentStateInterface.id


readonly messages: readonly Message[]

Defined in: src/state/index.ts:68

Immutable conversation history containing UPP Messages

AgentStateInterface.messages


readonly metadata: Readonly<Record<string, unknown>>

Defined in: src/state/index.ts:74

User-defined metadata for storing arbitrary state

AgentStateInterface.metadata


readonly plan: readonly PlanStep[] | undefined

Defined in: src/state/index.ts:80

Execution plan for Plan-strategy agents

AgentStateInterface.plan


readonly reasoning: readonly string[]

Defined in: src/state/index.ts:77

Reasoning traces captured during ReAct-style execution

AgentStateInterface.reasoning


readonly step: number

Defined in: src/state/index.ts:71

Current step number in the agent’s execution lifecycle

AgentStateInterface.step


readonly subagentTraces: readonly SubagentExecutionTrace[]

Defined in: src/state/index.ts:83

Sub-agent execution traces per UAP spec Section 8.8

AgentStateInterface.subagentTraces

toJSON(): AgentStateJSON

Defined in: src/state/index.ts:415

Serializes the state to JSON for persistence or transport.

The output includes a version identifier for forward compatibility and can be restored using AgentState.fromJSON.

AgentStateJSON

A JSON-serializable representation of the complete state

const state = AgentState.initial().withMessage(new UserMessage('Hello'));
const json = state.toJSON();
// Persist to storage
await Bun.write('checkpoint.json', JSON.stringify(json));

AgentStateInterface.toJSON


withContext(messages): AgentState

Defined in: src/state/index.ts:218

Creates a new state with the entire message context replaced.

Use this for context window management operations such as:

  • Pruning old messages to stay within token limits
  • Replacing history with a summarized version
  • Implementing sliding window contexts

Message[]

The new complete message history

AgentState

A new AgentState with the replaced context

// Prune to last 10 messages
const pruned = state.withContext(state.messages.slice(-10));
// Replace with summarized context
const summary = new AssistantMessage('Previous discussion summary...');
const summarized = state.withContext([summary, ...recentMessages]);

AgentStateInterface.withContext


withMessage(message): AgentState

Defined in: src/state/index.ts:154

Creates a new state with a single message appended.

Message

The UPP Message to add to the conversation history

AgentState

A new AgentState with the message appended

const state = AgentState.initial();
const updated = state.withMessage(new UserMessage('What is 2+2?'));
console.log(updated.messages.length); // 1

AgentStateInterface.withMessage


withMessages(messages): AgentState

Defined in: src/state/index.ts:185

Creates a new state with multiple messages appended.

Useful for adding a complete turn (e.g., user message + assistant response) in a single operation.

Message[]

Array of UPP Messages to append

AgentState

A new AgentState with all messages appended

const state = AgentState.initial();
const updated = state.withMessages([
new UserMessage('Hello'),
new AssistantMessage('Hi! How can I help?')
]);
console.log(updated.messages.length); // 2

AgentStateInterface.withMessages


withMetadata(key, value): AgentState

Defined in: src/state/index.ts:279

Creates a new state with a metadata entry added or updated.

Use metadata to store arbitrary application-specific data that should persist with the agent state, such as user preferences, session info, or custom tracking data.

string

The metadata key

unknown

The value to store (must be JSON-serializable)

AgentState

A new AgentState with the updated metadata

const state = AgentState.initial()
.withMetadata('userId', 'user-123')
.withMetadata('sessionStart', Date.now());
console.log(state.metadata.userId); // 'user-123'

AgentStateInterface.withMetadata


withPlan(plan): AgentState

Defined in: src/state/index.ts:342

Creates a new state with the execution plan set.

Used by Plan-strategy agents to store their decomposed task plan. The plan is copied to ensure immutability.

PlanStep[]

Array of plan steps defining the execution strategy

AgentState

A new AgentState with the plan set

const plan: PlanStep[] = [
{ id: 'step-1', description: 'Research topic', dependsOn: [], status: 'pending' },
{ id: 'step-2', description: 'Write outline', dependsOn: ['step-1'], status: 'pending' }
];
const state = AgentState.initial().withPlan(plan);

PlanStep for the plan step structure

AgentStateInterface.withPlan


withReasoning(reasoning): AgentState

Defined in: src/state/index.ts:310

Creates a new state with a reasoning trace appended.

Reasoning traces capture the agent’s internal thought process during ReAct-style execution, enabling debugging and explainability.

string

The reasoning trace entry to add

AgentState

A new AgentState with the reasoning appended

const state = AgentState.initial()
.withReasoning('User asked about weather, need to call weather API')
.withReasoning('Weather API returned sunny, 72F');
console.log(state.reasoning);
// ['User asked about weather...', 'Weather API returned...']

AgentStateInterface.withReasoning


withStep(step): AgentState

Defined in: src/state/index.ts:247

Creates a new state with an updated step number.

The step number tracks the agent’s position in its execution lifecycle, useful for progress tracking and debugging.

number

The new step number

AgentState

A new AgentState with the updated step

const state = AgentState.initial();
const afterStep1 = state.withStep(1);
const afterStep2 = afterStep1.withStep(2);
console.log(afterStep2.step); // 2

AgentStateInterface.withStep


withSubagentTrace(trace): AgentState

Defined in: src/state/index.ts:383

Creates a new state with a sub-agent execution trace appended.

Records the execution details of a sub-agent spawned by the parent agent, enabling hierarchical debugging and audit trails.

SubagentExecutionTrace

The sub-agent execution trace to record

AgentState

A new AgentState with the trace appended

Conforms to UAP specification Section 8.8 for sub-agent tracing.

const trace: SubagentExecutionTrace = {
subagentId: 'sub-123',
subagentType: 'researcher',
parentToolCallId: 'call-456',
prompt: 'Find information about...',
startTime: Date.now() - 5000,
endTime: Date.now(),
success: true,
result: 'Found the following...'
};
const updated = state.withSubagentTrace(trace);

SubagentExecutionTrace for the trace structure

AgentStateInterface.withSubagentTrace


static fromJSON(json): AgentState

Defined in: src/state/index.ts:453

Restores an AgentState from its JSON representation.

Validates the UAP version and reconstructs all message types to their proper UPP Message class instances.

AgentStateJSON

The serialized state from AgentState.toJSON

AgentState

A fully hydrated AgentState instance

Error if the UAP version is unsupported

// Load from storage
const file = await Bun.file('checkpoint.json').text();
const json = JSON.parse(file) as AgentStateJSON;
const state = AgentState.fromJSON(json);
console.log(state.messages.length);

static initial(): AgentState

Defined in: src/state/index.ts:129

Creates a fresh initial state with no history.

Use this to start a new agent execution session with empty messages, metadata, and traces.

AgentState

A new AgentState with default empty values

const state = AgentState.initial();
console.log(state.messages.length); // 0
console.log(state.step); // 0