agent-error-recovery
Use this skill when implementing error handling for AI agents. Activate when the user needs agents to handle failures gracefully, implement retry strategies, design fault-tolerant agent systems, or build agents that can recover from errors without human intervention.
What this skill does
# Agent Error Recovery
Design fault-tolerant agent systems that recover gracefully from failures.
## When to Use
- Building production-grade agent systems
- Agents need to handle API failures
- Implementing autonomous error recovery
- Designing resilient multi-agent workflows
- Setting up monitoring and alerting
## Error Classification
```typescript
enum ErrorCategory {
// Transient - retry likely to succeed
RATE_LIMIT = 'rate_limit',
TIMEOUT = 'timeout',
NETWORK = 'network',
SERVICE_UNAVAILABLE = 'service_unavailable',
// Recoverable - different approach may work
INVALID_INPUT = 'invalid_input',
CONTEXT_OVERFLOW = 'context_overflow',
TOOL_FAILURE = 'tool_failure',
// Terminal - cannot proceed
AUTHENTICATION = 'authentication',
AUTHORIZATION = 'authorization',
NOT_FOUND = 'not_found',
VALIDATION = 'validation',
// Unknown
UNKNOWN = 'unknown'
}
interface AgentError {
category: ErrorCategory;
code: string;
message: string;
retryable: boolean;
context: Record<string, unknown>;
timestamp: Date;
stackTrace?: string;
}
function classifyError(error: Error): AgentError {
// Rate limits
if (error.message.includes('429') || error.message.includes('rate limit')) {
return {
category: ErrorCategory.RATE_LIMIT,
code: 'RATE_LIMITED',
message: error.message,
retryable: true,
context: { waitTime: extractWaitTime(error) },
timestamp: new Date()
};
}
// Timeouts
if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {
return {
category: ErrorCategory.TIMEOUT,
code: 'TIMEOUT',
message: error.message,
retryable: true,
context: {},
timestamp: new Date()
};
}
// Context overflow
if (error.message.includes('context length') || error.message.includes('too long')) {
return {
category: ErrorCategory.CONTEXT_OVERFLOW,
code: 'CONTEXT_OVERFLOW',
message: error.message,
retryable: true, // Can retry with truncated context
context: {},
timestamp: new Date()
};
}
// Default
return {
category: ErrorCategory.UNKNOWN,
code: 'UNKNOWN',
message: error.message,
retryable: false,
context: {},
timestamp: new Date(),
stackTrace: error.stack
};
}
```
## Recovery Strategies
### Strategy 1: Retry with Backoff
```typescript
interface RetryConfig {
maxAttempts: number;
initialDelayMs: number;
maxDelayMs: number;
backoffMultiplier: number;
jitterMs: number;
}
async function retryWithBackoff<T>(
operation: () => Promise<T>,
config: RetryConfig
): Promise<T> {
let lastError: Error;
let delay = config.initialDelayMs;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
const classified = classifyError(lastError);
// Don't retry non-retryable errors
if (!classified.retryable) {
throw lastError;
}
// Last attempt - throw
if (attempt === config.maxAttempts) {
throw lastError;
}
// Calculate delay with jitter
const jitter = Math.random() * config.jitterMs;
const waitTime = Math.min(delay + jitter, config.maxDelayMs);
console.log(`Attempt ${attempt} failed, retrying in ${waitTime}ms...`);
await sleep(waitTime);
// Increase delay for next attempt
delay *= config.backoffMultiplier;
}
}
throw lastError!;
}
```
### Strategy 2: Circuit Breaker
```typescript
enum CircuitState {
CLOSED = 'closed', // Normal operation
OPEN = 'open', // Failing, reject requests
HALF_OPEN = 'half_open' // Testing if recovered
}
class CircuitBreaker {
private state = CircuitState.CLOSED;
private failures = 0;
private lastFailure?: Date;
private successCount = 0;
constructor(
private config: {
failureThreshold: number;
resetTimeoutMs: number;
successThreshold: number;
}
) {}
async execute<T>(operation: () => Promise<T>): Promise<T> {
// Check if circuit should transition
this.checkState();
if (this.state === CircuitState.OPEN) {
throw new Error('Circuit breaker is OPEN');
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private checkState(): void {
if (this.state === CircuitState.OPEN) {
const elapsed = Date.now() - this.lastFailure!.getTime();
if (elapsed >= this.config.resetTimeoutMs) {
this.state = CircuitState.HALF_OPEN;
this.successCount = 0;
}
}
}
private onSuccess(): void {
if (this.state === CircuitState.HALF_OPEN) {
this.successCount++;
if (this.successCount >= this.config.successThreshold) {
this.state = CircuitState.CLOSED;
this.failures = 0;
}
} else {
this.failures = 0;
}
}
private onFailure(): void {
this.failures++;
this.lastFailure = new Date();
if (this.failures >= this.config.failureThreshold) {
this.state = CircuitState.OPEN;
}
}
}
```
### Strategy 3: Fallback Chain
```typescript
interface FallbackOption<T> {
name: string;
execute: () => Promise<T>;
isApplicable: (error: AgentError) => boolean;
}
async function executeWithFallbacks<T>(
primary: () => Promise<T>,
fallbacks: FallbackOption<T>[]
): Promise<T> {
try {
return await primary();
} catch (error) {
const classified = classifyError(error as Error);
for (const fallback of fallbacks) {
if (fallback.isApplicable(classified)) {
console.log(`Primary failed, trying fallback: ${fallback.name}`);
try {
return await fallback.execute();
} catch (fallbackError) {
console.log(`Fallback ${fallback.name} also failed`);
continue;
}
}
}
// All fallbacks failed
throw error;
}
}
// Example usage
const result = await executeWithFallbacks(
() => callPrimaryAPI(),
[
{
name: 'backup_api',
execute: () => callBackupAPI(),
isApplicable: (e) => e.category === ErrorCategory.SERVICE_UNAVAILABLE
},
{
name: 'cached_response',
execute: () => getCachedResponse(),
isApplicable: (e) => e.category === ErrorCategory.TIMEOUT
},
{
name: 'simplified_request',
execute: () => callWithReducedParams(),
isApplicable: (e) => e.category === ErrorCategory.CONTEXT_OVERFLOW
}
]
);
```
### Strategy 4: Self-Healing Agent
```typescript
class SelfHealingAgent {
async execute(task: Task): Promise<Result> {
let attempt = 0;
const maxAttempts = 3;
while (attempt < maxAttempts) {
attempt++;
try {
return await this.runTask(task);
} catch (error) {
const classified = classifyError(error as Error);
// Can we heal?
const healingAction = this.determineHealingAction(classified);
if (!healingAction) {
throw error;
}
console.log(`Attempting self-healing: ${healingAction.description}`);
// Execute healing
await healingAction.execute();
// Modify task if needed
task = healingAction.modifyTask?.(task) || task;
}
}
throw new Error('Max healing attempts exceeded');
}
private determineHealingAction(error: AgentError): HealingAction | null {
switch (error.category) {
case ErrorCategory.CONTEXT_OVERFLOW:
return {
description: 'Truncating context to fit limits',
execute: async () => {},
modifyTask: (task) => ({
...task,
context: this.truncateContext(task.context)
})
};
case ErrorCategory.TOOL_FAILURE:
return {
description: 'Switching to alternative tool',
execute: async () => {
this.toolRouter.excRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.