/** * State Management Types * * Core types and interfaces for conversation persistence. * Inspired by LangGraph's checkpointer pattern. */ import type { Message } from '../providers/types.js'; import type { TodoItem } from '../tools/builtin/todo.js'; /** * Serializable snapshot of an agent's current state. * Contains everything needed to resume a conversation. */ export interface AgentState { /** * Unique session identifier */ sessionId: string; /** * Conversation messages */ messages: Message[]; /** * System prompt (needed for resume) */ systemPrompt: string; /** * Model identifier (optional, for resume) */ model?: string; /** * Todo items state */ todos: TodoItem[]; /** * Current iteration count */ currentIteration: number; /** * Number of conversation turns (user + assistant exchanges) * Used by context manager to track recent vs old messages for compaction. */ turnCount: number; /** * Total tokens used in the session */ totalTokensUsed: number; /** * When the session was created (ISO 8601) */ createdAt: string; /** * When the session was last updated (ISO 8601) */ updatedAt: string; /** * Schema version for migration support */ version: number; } /** * Metadata stored alongside state for listing/filtering. */ export interface SessionMetadata { /** * Session identifier */ sessionId: string; /** * User-friendly session name */ name?: string; /** * Creation timestamp (ISO 8601) */ createdAt: string; /** * Last update timestamp (ISO 8601) */ updatedAt: string; /** * Number of messages in the conversation */ messageCount: number; /** * Truncated preview of last user message */ lastUserMessage?: string; /** * Truncated preview of last assistant message */ lastAssistantMessage?: string; /** * Tags for organization */ tags?: string[]; } /** * Lightweight session info for listing (without full state). */ export interface SessionInfo { /** * Session identifier */ sessionId: string; /** * User-friendly session name */ name?: string; /** * Creation timestamp (ISO 8601) */ createdAt: string; /** * Last update timestamp (ISO 8601) */ updatedAt: string; /** * Number of messages */ messageCount: number; /** * Preview text (last message truncated) */ preview?: string; /** * Tags for organization */ tags?: string[]; } /** * Handles conversion between AgentState and string representation. */ export interface StateSerializer { /** * Serialize agent state to string */ serialize(state: AgentState): string; /** * Deserialize string back to agent state * @throws StateError if data is invalid */ deserialize(data: string): AgentState; /** * Validate state before serialization. * Called by checkpointers before saving to prevent corrupted checkpoints. * @throws StateError if state is invalid */ validate(state: AgentState): void; /** * Version identifier for migration support */ readonly version: string; /** * Optional migration from older versions */ migrate?(data: string, fromVersion: string): string; } /** * Options for listing sessions. */ export interface ListSessionsOptions { /** * Maximum number of sessions to return */ limit?: number; /** * Number of sessions to skip (for pagination) */ offset?: number; /** * Field to sort by */ orderBy?: 'createdAt' | 'updatedAt'; /** * Sort direction */ order?: 'asc' | 'desc'; /** * Filter by tags (sessions must have all specified tags) */ tags?: string[]; } /** * Core persistence interface. Implementations handle actual storage. */ export interface Checkpointer { /** * Save agent state to storage * @param sessionId - Unique session identifier * @param state - Complete agent state to save * @param metadata - Optional metadata overrides */ save(sessionId: string, state: AgentState, metadata?: Partial): Promise; /** * Load agent state from storage * @param sessionId - Session to load * @returns AgentState if found, null if not exists */ load(sessionId: string): Promise; /** * List all saved sessions * @param options - Optional filtering/sorting options * @returns Array of session info (without full state) */ list(options?: ListSessionsOptions): Promise; /** * Delete a saved session * @param sessionId - Session to delete * @returns true if deleted, false if not found */ delete(sessionId: string): Promise; /** * Check if a session exists * @param sessionId - Session to check */ exists(sessionId: string): Promise; /** * Get session metadata without loading full state * @param sessionId - Session to query */ getMetadata(sessionId: string): Promise; } /** * Pending write from incomplete tool execution. * Used for fault-tolerant checkpointing. */ export interface PendingWrite { /** * Tool call ID */ toolCallId: string; /** * Tool name */ toolName: string; /** * Tool execution result */ result: { success: boolean; result?: unknown; error?: string; }; /** * When the write was completed (ISO 8601) */ completedAt: string; } /** * Extended checkpointer with fault tolerance support. * Tracks pending writes for recovery from mid-step failures. */ export interface CheckpointerWithPending extends Checkpointer { /** * Save pending writes (incomplete tool executions) */ savePending(sessionId: string, writes: PendingWrite[]): Promise; /** * Load pending writes for a session */ loadPending(sessionId: string): Promise; /** * Clear pending writes (called after step completion) */ clearPending(sessionId: string): Promise; } /** * Options for resuming an agent from a checkpoint. */ export interface ResumeOptions { /** * LLM provider to use */ provider: unknown; /** * Checkpointer to load from */ checkpointer: Checkpointer; /** * Override saved system prompt */ systemPrompt?: string; /** * Override saved tools */ tools?: unknown[]; /** * Event handler */ onEvent?: (event: unknown) => void; } /** * Options for creating agent from exported state. */ export interface FromStateOptions { /** * LLM provider to use */ provider: unknown; /** * Optional checkpointer for subsequent saves */ checkpointer?: Checkpointer; /** * Override saved tools */ tools?: unknown[]; /** * Event handler */ onEvent?: (event: unknown) => void; } /** * Current schema version for AgentState. * Increment when making breaking changes to the schema. */ export declare const CURRENT_STATE_VERSION = 1;