Class: AgentState
@providerprotocol/agents / index / AgentState
Class: AgentState
Section titled “Class: 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.
Remarks
Section titled “Remarks”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.
Example
Section titled “Example”// Create initial stateconst state = AgentState.initial();
// Add messages immutablyconst state2 = state.withMessage(new UserMessage('Hello'));const state3 = state2.withMessage(new AssistantMessage('Hi there!'));
// Add reasoning tracesconst state4 = state3.withReasoning('User greeted me, responding politely.');
// Serialize for persistenceconst json = state4.toJSON();const restored = AgentState.fromJSON(json);- AgentStateInterface for the interface contract
- AgentStateJSON for the serialization format
Implements
Section titled “Implements”Properties
Section titled “Properties”
readonlyid:string
Defined in: src/state/index.ts:65
Unique identifier for this state snapshot (UUIDv4)
Implementation of
Section titled “Implementation of”messages
Section titled “messages”
readonlymessages: readonlyMessage[]
Defined in: src/state/index.ts:68
Immutable conversation history containing UPP Messages
Implementation of
Section titled “Implementation of”metadata
Section titled “metadata”
readonlymetadata:Readonly<Record<string,unknown>>
Defined in: src/state/index.ts:74
User-defined metadata for storing arbitrary state
Implementation of
Section titled “Implementation of”
readonlyplan: readonlyPlanStep[] |undefined
Defined in: src/state/index.ts:80
Execution plan for Plan-strategy agents
Implementation of
Section titled “Implementation of”reasoning
Section titled “reasoning”
readonlyreasoning: readonlystring[]
Defined in: src/state/index.ts:77
Reasoning traces captured during ReAct-style execution
Implementation of
Section titled “Implementation of”
readonlystep:number
Defined in: src/state/index.ts:71
Current step number in the agent’s execution lifecycle
Implementation of
Section titled “Implementation of”subagentTraces
Section titled “subagentTraces”
readonlysubagentTraces: readonlySubagentExecutionTrace[]
Defined in: src/state/index.ts:83
Sub-agent execution traces per UAP spec Section 8.8
Implementation of
Section titled “Implementation of”AgentStateInterface.subagentTraces
Methods
Section titled “Methods”toJSON()
Section titled “toJSON()”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.
Returns
Section titled “Returns”A JSON-serializable representation of the complete state
Example
Section titled “Example”const state = AgentState.initial().withMessage(new UserMessage('Hello'));const json = state.toJSON();
// Persist to storageawait Bun.write('checkpoint.json', JSON.stringify(json));- AgentStateJSON for the serialization format
- AgentState.fromJSON for deserialization
Implementation of
Section titled “Implementation of”withContext()
Section titled “withContext()”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
Parameters
Section titled “Parameters”messages
Section titled “messages”Message[]
The new complete message history
Returns
Section titled “Returns”AgentState
A new AgentState with the replaced context
Example
Section titled “Example”// Prune to last 10 messagesconst pruned = state.withContext(state.messages.slice(-10));
// Replace with summarized contextconst summary = new AssistantMessage('Previous discussion summary...');const summarized = state.withContext([summary, ...recentMessages]);Implementation of
Section titled “Implementation of”AgentStateInterface.withContext
withMessage()
Section titled “withMessage()”withMessage(
message):AgentState
Defined in: src/state/index.ts:154
Creates a new state with a single message appended.
Parameters
Section titled “Parameters”message
Section titled “message”Message
The UPP Message to add to the conversation history
Returns
Section titled “Returns”AgentState
A new AgentState with the message appended
Example
Section titled “Example”const state = AgentState.initial();const updated = state.withMessage(new UserMessage('What is 2+2?'));console.log(updated.messages.length); // 1Implementation of
Section titled “Implementation of”AgentStateInterface.withMessage
withMessages()
Section titled “withMessages()”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.
Parameters
Section titled “Parameters”messages
Section titled “messages”Message[]
Array of UPP Messages to append
Returns
Section titled “Returns”AgentState
A new AgentState with all messages appended
Example
Section titled “Example”const state = AgentState.initial();const updated = state.withMessages([ new UserMessage('Hello'), new AssistantMessage('Hi! How can I help?')]);console.log(updated.messages.length); // 2Implementation of
Section titled “Implementation of”AgentStateInterface.withMessages
withMetadata()
Section titled “withMetadata()”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.
Parameters
Section titled “Parameters”string
The metadata key
unknown
The value to store (must be JSON-serializable)
Returns
Section titled “Returns”AgentState
A new AgentState with the updated metadata
Example
Section titled “Example”const state = AgentState.initial() .withMetadata('userId', 'user-123') .withMetadata('sessionStart', Date.now());
console.log(state.metadata.userId); // 'user-123'Implementation of
Section titled “Implementation of”AgentStateInterface.withMetadata
withPlan()
Section titled “withPlan()”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.
Parameters
Section titled “Parameters”PlanStep[]
Array of plan steps defining the execution strategy
Returns
Section titled “Returns”AgentState
A new AgentState with the plan set
Example
Section titled “Example”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
Implementation of
Section titled “Implementation of”withReasoning()
Section titled “withReasoning()”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.
Parameters
Section titled “Parameters”reasoning
Section titled “reasoning”string
The reasoning trace entry to add
Returns
Section titled “Returns”AgentState
A new AgentState with the reasoning appended
Example
Section titled “Example”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...']Implementation of
Section titled “Implementation of”AgentStateInterface.withReasoning
withStep()
Section titled “withStep()”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.
Parameters
Section titled “Parameters”number
The new step number
Returns
Section titled “Returns”AgentState
A new AgentState with the updated step
Example
Section titled “Example”const state = AgentState.initial();const afterStep1 = state.withStep(1);const afterStep2 = afterStep1.withStep(2);console.log(afterStep2.step); // 2Implementation of
Section titled “Implementation of”withSubagentTrace()
Section titled “withSubagentTrace()”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.
Parameters
Section titled “Parameters”The sub-agent execution trace to record
Returns
Section titled “Returns”AgentState
A new AgentState with the trace appended
Remarks
Section titled “Remarks”Conforms to UAP specification Section 8.8 for sub-agent tracing.
Example
Section titled “Example”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
Implementation of
Section titled “Implementation of”AgentStateInterface.withSubagentTrace
fromJSON()
Section titled “fromJSON()”
staticfromJSON(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.
Parameters
Section titled “Parameters”The serialized state from AgentState.toJSON
Returns
Section titled “Returns”AgentState
A fully hydrated AgentState instance
Throws
Section titled “Throws”Error if the UAP version is unsupported
Example
Section titled “Example”// Load from storageconst file = await Bun.file('checkpoint.json').text();const json = JSON.parse(file) as AgentStateJSON;const state = AgentState.fromJSON(json);
console.log(state.messages.length);- AgentStateJSON for the expected format
- AgentState.toJSON for serialization
initial()
Section titled “initial()”
staticinitial():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.
Returns
Section titled “Returns”AgentState
A new AgentState with default empty values
Example
Section titled “Example”const state = AgentState.initial();console.log(state.messages.length); // 0console.log(state.step); // 0