Skip to content

LeoYeAI/agent-master-skills / skills/agent-mode-upgrades

agentic-loop-upgrade

Flagged

Enhanced agentic loop with planning, parallel execution, confidence gates, semantic error recovery, and observable state machine. Includes Mode dashboard UI for easy configuration.

src/state-machine/fsm.ts

View on GitHub
/**
 * Agent State Machine
 * 
 * Provides observable state transitions for debugging, logging, and dashboards.
 */

import type {
  AgentState,
  StateContext,
  StateObserver,
  StateTransition,
  StateMachineConfig,
} from "../types.js";

// Valid state transitions
const TRANSITIONS: Record<AgentState, AgentState[]> = {
  idle: ["planning"],
  planning: ["executing", "error"],
  executing: ["reflecting", "waiting_human", "recovering", "completing"],
  reflecting: ["executing", "replanning", "completing"],
  replanning: ["executing", "error"],
  waiting_human: ["executing", "planning", "completing", "idle"],
  recovering: ["executing", "replanning", "error"],
  completing: ["idle"],
  error: ["idle"],
  complete: ["idle"],
};

export class AgentStateMachine {
  private context: StateContext;
  private observers: StateObserver[] = [];
  private config: StateMachineConfig;
  private metrics: Map<AgentState, { count: number; totalMs: number }>;

  constructor(config: StateMachineConfig) {
    this.config = config;
    this.context = {
      state: "idle",
      previousState: null,
      enteredAt: Date.now(),
      metadata: {},
      history: [],
    };
    this.metrics = new Map();
    
    // Initialize metrics for all states
    for (const state of Object.keys(TRANSITIONS) as AgentState[]) {
      this.metrics.set(state, { count: 0, totalMs: 0 });
    }
  }

  /**
   * Transition to a new state
   */
  transition(
    to: AgentState,
    trigger: string,
    metadata?: Record<string, unknown>
  ): void {
    const from = this.context.state;

    // Validate transition
    if (!TRANSITIONS[from].includes(to)) {
      throw new Error(`Invalid transition: ${from} -> ${to}`);
    }

    const now = Date.now();
    const timeInState = now - this.context.enteredAt;

    // Update metrics
    if (this.config.metrics) {
      const stateMetrics = this.metrics.get(from);
      if (stateMetrics) {
        stateMetrics.count += 1;
        stateMetrics.totalMs += timeInState;
      }
    }

    // Record transition
    const transition: StateTransition = {
      from,
      to,
      trigger,
      timestamp: now,
      metadata,
    };

    this.context.history.push(transition);
    this.context.previousState = from;
    this.context.state = to;
    this.context.enteredAt = now;
    this.context.metadata = metadata ?? {};

    // Log transition
    if (this.config.logging) {
      console.log(
        `[FSM] ${from} -> ${to} (${trigger}) [${timeInState}ms in ${from}]`
      );
      if (metadata) {
        console.log(`[FSM] metadata:`, JSON.stringify(metadata));
      }
    }

    // Notify observers
    for (const observer of this.observers) {
      try {
        observer.onTransition(transition);
      } catch (err) {
        console.error("[FSM] Observer error:", err);
      }
    }
  }

  /**
   * Get current state
   */
  getState(): AgentState {
    return this.context.state;
  }

  /**
   * Get full state context
   */
  getContext(): Readonly<StateContext> {
    return { ...this.context, history: [...this.context.history] };
  }

  /**
   * Get transition history
   */
  getHistory(): readonly StateTransition[] {
    return this.context.history;
  }

  /**
   * Get metrics for all states
   */
  getMetrics(): Map<AgentState, { count: number; totalMs: number; avgMs: number }> {
    const result = new Map<AgentState, { count: number; totalMs: number; avgMs: number }>();
    
    for (const [state, metrics] of this.metrics) {
      result.set(state, {
        count: metrics.count,
        totalMs: metrics.totalMs,
        avgMs: metrics.count > 0 ? metrics.totalMs / metrics.count : 0,
      });
    }
    
    return result;
  }

  /**
   * Check if a transition is valid
   */
  canTransition(to: AgentState): boolean {
    return TRANSITIONS[this.context.state].includes(to);
  }

  /**
   * Subscribe to state changes
   */
  subscribe(observer: StateObserver): () => void {
    this.observers.push(observer);
    return () => {
      this.observers = this.observers.filter((o) => o !== observer);
    };
  }

  /**
   * Reset the state machine
   */
  reset(): void {
    this.context = {
      state: "idle",
      previousState: null,
      enteredAt: Date.now(),
      metadata: {},
      history: [],
    };
    
    for (const metrics of this.metrics.values()) {
      metrics.count = 0;
      metrics.totalMs = 0;
    }
  }

  /**
   * Serialize state for persistence
   */
  serialize(): string {
    return JSON.stringify({
      state: this.context.state,
      enteredAt: this.context.enteredAt,
      metadata: this.context.metadata,
      history: this.context.history,
    });
  }

  /**
   * Restore state from persistence
   */
  restore(serialized: string): void {
    try {
      const data = JSON.parse(serialized);
      this.context = {
        state: data.state ?? "idle",
        previousState: null,
        enteredAt: data.enteredAt ?? Date.now(),
        metadata: data.metadata ?? {},
        history: data.history ?? [],
      };
    } catch (err) {
      console.error("[FSM] Failed to restore state:", err);
      this.reset();
    }
  }
}

// ============================================================================
// Built-in Observers
// ============================================================================

/**
 * Logging observer - logs all transitions to console
 */
export class LoggingObserver implements StateObserver {
  private lastTimestamp: number = Date.now();

  onTransition(transition: StateTransition): void {
    const duration = transition.timestamp - this.lastTimestamp;
    console.log(
      `[${new Date(transition.timestamp).toISOString()}] ` +
        `${transition.from} -> ${transition.to} ` +
        `(${transition.trigger}) ` +
        `[${duration}ms]`
    );
    this.lastTimestamp = transition.timestamp;
  }
}

/**
 * Metrics observer - collects timing statistics
 */
export class MetricsObserver implements StateObserver {
  private stateTimers = new Map<AgentState, number>();
  private transitionCounts = new Map<string, number>();
  private stateDurations = new Map<AgentState, number[]>();

  onTransition(transition: StateTransition): void {
    // Track time in previous state
    const entryTime = this.stateTimers.get(transition.from);
    if (entryTime) {
      const duration = transition.timestamp - entryTime;
      const durations = this.stateDurations.get(transition.from) ?? [];
      durations.push(duration);
      this.stateDurations.set(transition.from, durations);
    }

    // Track entry time for new state
    this.stateTimers.set(transition.to, transition.timestamp);

    // Count transitions
    const key = `${transition.from}->${transition.to}`;
    this.transitionCounts.set(key, (this.transitionCounts.get(key) ?? 0) + 1);
  }

  getStats(): {
    transitionCounts: Record<string, number>;
    avgDurations: Record<AgentState, number>;
    totalTransitions: number;
  } {
    const avgDurations: Record<string, number> = {};
    let totalTransitions = 0;

    for (const [state, durations] of this.stateDurations) {
      if (durations.length > 0) {
        avgDurations[state] = durations.reduce((a, b) => a + b, 0) / durations.length;
      }
    }

    for (const count of this.transitionCounts.values()) {
      totalTransitions += count;
    }

    return {
      transitionCounts: Object.fromEntries(this.transitionCounts),
      avgDurations: avgDurations as Record<AgentState, number>,
      totalTransitions,
    };
  }
}

/**
 * Broadcast observer - sends state changes via callback
 */
export class BroadcastObserver implements StateObserver {
  constructor(
    private sessionKey: string,
    private broadcast: (data: unknown) => void
  ) {}

  onTransition(transition: StateTransition): void {
    this.broadcast({
      type: "agent_state_change",
      sessionKey: this.sessionKey,
      data: {
        state: transition.to,
        previousState: transition.from,
        trigger: transition.trigger,
        metadata: transition.metadata,
        timestamp: transition.timestamp,
      },
    });
  }
}
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall