UNPKG

autosnippet

Version:

Extract code patterns into a knowledge base for AI coding assistants

107 lines (106 loc) 3.47 kB
/** * AgentState — 类型安全的 Agent 状态机 * * 借鉴 LangGraph StateGraph + Anthropic Agentic Patterns: * - 每个 Agent 拥有独立的 typed state * - 状态转移通过声明式 transitions 定义 * - 支持 guard 条件(类似 XState) * - 内置事件发射(状态变更通知) * * 设计原则: * 1. 不可变更新 — 每次 transition 返回新 state snapshot * 2. 可溯源 — 保留完整状态历史(可选) * 3. 可序列化 — state 可 JSON 化,支持持久化/恢复 * * @module AgentState */ import { EventEmitter } from 'node:events'; /** Guard condition: returns true if transition is allowed */ type TransitionGuard = (data: Record<string, unknown>) => boolean; /** Side-effect action executed after transition */ type TransitionAction = (data: Record<string, unknown>, payload: Record<string, unknown>) => void; /** State transition definition */ interface Transition { from: string; to: string; event: string; guard?: TransitionGuard; action?: TransitionAction; } /** History entry for state changes */ interface HistoryEntry { phase: string; data: Record<string, unknown>; timestamp: number; event?: string; from?: string; } /** Snapshot used by toJSON / fromJSON */ interface AgentStateSnapshot { phase?: string; data?: Record<string, unknown>; history?: HistoryEntry[]; } /** Agent 执行阶段枚举 */ export declare const AgentPhase: Readonly<{ IDLE: "idle"; PLANNING: "planning"; EXECUTING: "executing"; REFLECTING: "reflecting"; WAITING_INPUT: "waiting_input"; HANDOFF: "handoff"; COMPLETED: "completed"; FAILED: "failed"; ABORTED: "aborted"; }>; export declare class AgentState extends EventEmitter { #private; /** * @param [opts.initialData={}] 初始状态数据 * @param [opts.initialPhase='idle'] 初始阶段 * @param [opts.transitions] 自定义转移定义(合并到默认转移上) * @param [opts.keepHistory=true] 是否保留状态历史 */ constructor({ initialData, initialPhase, transitions, keepHistory, }?: { initialData?: {} | undefined; initialPhase?: string | undefined; transitions?: Transition[] | undefined; keepHistory?: boolean | undefined; }); /** 当前阶段 */ get phase(): string; /** 当前状态数据(只读 copy) */ get data(): { [x: string]: unknown; }; /** 状态历史 */ get history(): HistoryEntry[]; /** Agent 是否处于终态 */ get isTerminal(): boolean; /** * 触发事件,尝试状态转移 * @param event 事件名 * @param [payload={}] 附加数据(合并到 state.data) * @returns 是否成功转移 */ send(event: string, payload?: Record<string, unknown>): boolean; /** * 直接更新状态数据(不触发阶段转移) * @param patch 要合并的数据 */ update(patch: Record<string, unknown>): void; /** 获取当前阶段可用的事件列表 */ availableEvents(): string[]; /** 导出为可序列化对象 */ toJSON(): { phase: string; data: Record<string, unknown>; history: HistoryEntry[]; }; /** 从序列化数据恢复 */ static fromJSON(snapshot: AgentStateSnapshot, opts?: { transitions?: Transition[]; keepHistory?: boolean; }): AgentState; } export default AgentState;