naylence-agent-sdk-ts / BaseAgentState
Class: BaseAgentState
Defined in: src/naylence/agent/base-agent.ts:167
Base class for agent state with Pydantic-like serialization and validation.
Provides feature parity with Python’s BaseAgentState:
- Schema-based validation using Zod (equivalent to Pydantic validators)
- Type-safe serialization and deserialization
- Custom toJSON/fromJSON methods for proper persistence
Examples
import { z } from 'zod';
const CounterStateSchema = z.object({
count: z.number().int().nonnegative(),
});
class CounterState extends BaseAgentState {
static readonly schema = CounterStateSchema;
count: number = 0;
}const ItemSchema = z.object({
id: z.string().uuid(),
name: z.string(),
});
const InventoryStateSchema = z.object({
items: z.array(ItemSchema),
});
class InventoryState extends BaseAgentState {
static readonly schema = InventoryStateSchema;
items: Array<{ id: string; name: string }> = [];
}Constructors
Constructor
new BaseAgentState(): BaseAgentState;Returns
BaseAgentState
Properties
Methods
clone()
clone(): this;Defined in: src/naylence/agent/base-agent.ts:314
Create a validated copy of this state instance.
Useful for creating snapshots or clones with validation.
Returns
this
A new instance with the same data
Throws
If current state doesn’t match schema
toJSON()
toJSON(): unknown;Defined in: src/naylence/agent/base-agent.ts:209
Serialize state to JSON using schema validation.
Override in subclasses to customize serialization behavior. The default implementation:
- Extracts all enumerable own properties
- Validates against schema if defined
- Returns validated data
This is automatically called by JSON.stringify() and storage providers.
Returns
unknown
Plain object representation of the state
Throws
If state doesn’t match schema (wraps z.ZodError)
Example
toJSON() {
// Custom serialization with specific fields
return {
count: this.count,
lastUpdated: this.lastUpdated.toISOString(),
};
}fromJSON()
static fromJSON<T>(this: () => T, data: unknown): T;Defined in: src/naylence/agent/base-agent.ts:278
Deserialize and validate data using the schema.
This provides runtime type safety equivalent to Pydantic’s model_validate_json.
Type Parameters
| Type Parameter |
|---|
T extends BaseAgentState |
Parameters
| Parameter | Type | Description |
|---|---|---|
this | () => T | - |
data | unknown | Plain object data to deserialize |
Returns
T
Validated instance of the state class
Throws
If data doesn’t match schema
Examples
const state = CounterState.fromJSON({ count: 42 });try {
const state = CounterState.fromJSON(untrustedData);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Validation failed:', error.errors);
}
}