The Resource Loader manages all framework resources, providing a unified interface for accessing bundled and user resources.
import { ResourceLoader } from 'aiwf/lib/resource-loader';new ResourceLoader(options?: ResourceLoaderOptions)Options:
interface ResourceLoaderOptions {
bundledPath?: string; // Path to bundled resources
userPath?: string; // Path to user resources
preferUserResources?: boolean; // Prefer user over bundled (default: true)
}Resolves the path to a resource, checking user directory first, then bundled resources.
async resolvePath(resourceType: string, resourceName: string): Promise<string>Example:
const loader = new ResourceLoader();
const personaPath = await loader.resolvePath('personas', 'analyst.json');Loads and parses a resource file.
async loadResource(resourceType: string, resourceName: string): Promise<any>Supported formats:
- JSON (
.json) - YAML (
.yaml,.yml) - JavaScript modules (
.js) - Markdown (
.md)
Lists all available resources of a given type.
async listResources(resourceType: string): Promise<string[]>Copies a resource to a specified location.
async copyResource(
resourceType: string,
resourceName: string,
destination: string
): Promise<void>Manages application and project state with support for checkpoints and atomic updates.
import { StateIndexManager } from 'aiwf/lib/state/state-index';new StateIndexManager(aiwfPath: string)Loads the current state from disk.
async loadState(): Promise<StateIndex>Returns:
interface StateIndex {
version: string;
last_updated: string;
last_updated_by: string;
project_info: ProjectInfo;
milestones: Milestone[];
sprints: Sprint[];
tasks: Task[];
workflow_mode: WorkflowMode;
}Saves state to disk with automatic backup.
async saveState(state: StateIndex): Promise<void>Updates project information.
async updateProjectInfo(updates: Partial<ProjectInfo>): Promise<void>Adds a new milestone to the project.
async addMilestone(milestone: Milestone): Promise<void>Manages project templates and code generation.
import { TemplateEngine } from 'aiwf/lib/template-engine';Lists all available project templates.
async listTemplates(): Promise<TemplateInfo[]>Creates a new project from a template.
async createFromTemplate(
templateName: string,
targetPath: string,
variables: Record<string, string>
): Promise<void>Example:
const engine = new TemplateEngine();
await engine.createFromTemplate('api-server', './my-api', {
projectName: 'My API',
author: 'John Doe',
description: 'My awesome API server'
});Manages AI tool integrations and configurations.
import AIToolCommand from 'aiwf/commands/ai-tool';Executes AI tool commands.
async execute(args: string[]): Promise<void>Subcommands:
list- List all available AI toolsactivate <tool>- Activate an AI toolconfigure <tool>- Configure an AI toolstatus- Show current AI tool status
Provides various compression strategies for optimizing context.
Compresses content using specified strategy.
async compress(
mode: CompressionMode,
content: string,
options?: CompressionOptions
): Promise<string>Compression Modes:
simple- Basic whitespace and comment removalmoderate- Balanced compressionaggressive- Maximum compressioncustom- User-defined rules
Options:
interface CompressionOptions {
preserveComments?: boolean;
preserveWhitespace?: boolean;
maxLineLength?: number;
customRules?: CompressionRule[];
}Creates new AIWF projects from templates.
async createProject(options: CreateProjectOptions): Promise<void>Options:
interface CreateProjectOptions {
template: string;
name: string;
path?: string;
variables?: Record<string, string>;
skipInstall?: boolean;
gitInit?: boolean;
}Evaluates AI responses and code quality.
Evaluates the quality of an AI response.
async evaluateResponse(
file: string,
options?: EvaluationOptions
): Promise<EvaluationResult>Evaluates code quality and best practices.
async evaluateCode(
file: string,
options?: CodeEvaluationOptions
): Promise<CodeEvaluationResult>Manages feature tracking and development workflow.
Creates a new feature entry.
async createFeature(
name: string,
description?: string
): Promise<FeatureEntry>Updates the status of a feature.
async updateFeatureStatus(
id: string,
status: FeatureStatus
): Promise<void>Feature Statuses:
plannedin-progresstestingcompleteddeployed
Manages AI personas and their configurations.
Lists all available personas.
async listPersonas(): Promise<PersonaInfo[]>Activates a specific persona.
async activatePersona(name: string): Promise<void>Creates a custom persona.
async createPersona(
name: string,
config: PersonaConfig
): Promise<void>Manages project state and workflow transitions.
Displays current project state.
async showStatus(): Promise<StateStatus>Creates a state checkpoint.
async checkpoint(
name: string,
description?: string
): Promise<CheckpointInfo>Restores from a checkpoint.
async restore(checkpointId: string): Promise<void>Monitors and manages AI token usage.
Records token usage.
async trackUsage(
input: string,
output: string,
model?: string
): Promise<UsageRecord>Generates usage report.
async getUsageReport(
period?: 'day' | 'week' | 'month'
): Promise<UsageReport>Manages YOLO mode configuration.
Creates YOLO configuration file.
async createYoloConfig(options?: YoloOptions): Promise<void>Creates configuration through interactive prompts.
async createInteractiveYoloConfig(): Promise<void>Prevents over-engineering and maintains code quality during autonomous execution.
import { EngineeringGuard } from 'aiwf/utils/engineering-guard';new EngineeringGuard(configPath?: string)Checks a single file for complexity violations.
async checkFileComplexity(filePath: string): Promise<void>Performs comprehensive project-wide complexity analysis.
async checkProject(
projectPath: string,
filePatterns?: string[]
): Promise<GuardReport>Returns:
interface GuardReport {
passed: boolean;
violations: Violation[];
warnings: Warning[];
summary: {
total_violations: number;
high_severity: number;
medium_severity: number;
warnings: number;
};
recommendations: string[];
}Provides real-time feedback during development.
async provideFeedback(
filePath: string,
content?: string
): Promise<Feedback[]>Generates comprehensive analysis report.
generateReport(): GuardReportManages state checkpoints and recovery.
import { CheckpointManager } from 'aiwf/utils/checkpoint-manager';new CheckpointManager(projectRoot: string)Starts a new YOLO session with tracking.
async startSession(sprintId: string, mode?: string): Promise<void>Begins tracking a specific task.
async startTask(taskId: string, taskInfo?: any): Promise<void>Marks a task as completed with results.
async completeTask(taskId: string, result?: any): Promise<void>Creates a new checkpoint.
async createCheckpoint(
type?: string,
metadata?: CheckpointMetadata
): Promise<string>Lists all available checkpoints.
async listCheckpoints(): Promise<CheckpointInfo[]>Restores from a specific checkpoint.
async restoreFromCheckpoint(checkpointId: string): Promise<RestoreResult>Returns:
interface RestoreResult {
success: boolean;
checkpoint: Checkpoint;
tasks_to_resume: {
completed: string[];
current: string | null;
next_task_hint: string;
};
}Generates comprehensive progress report.
async generateProgressReport(): Promise<ProgressReport>Returns:
interface ProgressReport {
session: {
id: string;
started: string;
sprint: string;
mode: string;
};
progress: {
completed: number;
failed: number;
skipped: number;
current: string;
};
performance: {
total_time: string;
avg_task_time: string;
success_rate: string;
};
checkpoints: CheckpointInfo[];
recommendations: string[];
}Ends the current session and generates final report.
async endSession(summary?: any): Promise<ProgressReport>Provides Git integration utilities.
Parses structured commit messages.
parseCommitMessage(message: string): ParsedCommitReturns:
interface ParsedCommit {
type: string;
scope?: string;
subject: string;
body?: string;
features?: string[];
tasks?: string[];
}Gets recent commit history.
async getRecentCommits(limit?: number): Promise<Commit[]>Counts tokens for various AI models.
Counts tokens in text.
countTokens(text: string, model?: string): numberSupported models:
gpt-3.5-turbogpt-4claudeclaude-instant
Estimates cost based on token count.
estimateCost(tokens: number, model: string): numberVarious text processing utilities.
Creates a summary of text.
async summarizeText(
text: string,
maxLength?: number
): Promise<string>Extracts keywords from text.
extractKeywords(text: string): string[]Normalizes whitespace in text.
normalizeWhitespace(text: string): stringStandard interface for AIWF plugins.
interface AIWFPlugin {
name: string;
version: string;
description?: string;
// Lifecycle hooks
init?(context: PluginContext): Promise<void>;
destroy?(): Promise<void>;
// Command hooks
commands?: Record<string, CommandHandler>;
// Event hooks
hooks?: Record<string, HookHandler>;
}interface PluginContext {
aiwfPath: string;
projectRoot: string;
config: AIWFConfig;
logger: Logger;
// Core services
resourceLoader: ResourceLoader;
stateManager: StateIndexManager;
templateEngine: TemplateEngine;
}Event-driven extension system.
hooks: {
'before-command': async (command, args) => { /* ... */ },
'after-command': async (command, result) => { /* ... */ },
'command-error': async (command, error) => { /* ... */ }
}hooks: {
'before-state-change': async (oldState, newState) => { /* ... */ },
'after-state-change': async (oldState, newState) => { /* ... */ },
'state-checkpoint': async (checkpoint) => { /* ... */ }
}hooks: {
'before-resource-load': async (type, name) => { /* ... */ },
'after-resource-load': async (type, name, content) => { /* ... */ },
'resource-not-found': async (type, name) => { /* ... */ }
}Manages AI persona configurations and contexts.
import { AIPersonaManager } from 'aiwf/lib/ai-persona-manager';Loads a persona configuration.
async loadPersona(name: string): Promise<Persona>Applies persona context to content.
applyPersona(content: string, persona: Persona): stringValidates persona configuration.
validatePersona(persona: Persona): ValidationResultProvides intelligent content compression.
Compresses content using specified strategy.
async compress(
content: string,
strategy: CompressionStrategy
): Promise<CompressedContent>Decompresses content.
async decompress(compressed: CompressedContent): Promise<string>Analyzes potential compression savings.
analyzeCompression(content: string): CompressionAnalysisEvaluates AI responses and code quality.
Evaluates content quality.
async evaluateQuality(
content: string,
criteria?: EvaluationCriteria
): Promise<QualityScore>Compares multiple AI responses.
compareResponses(responses: string[]): ComparisonResultGenerates evaluation report.
generateReport(evaluations: Evaluation[]): EvaluationReportAll AIWF APIs follow consistent error handling patterns:
try {
const result = await aiwfApi.someMethod();
} catch (error) {
if (error.code === 'RESOURCE_NOT_FOUND') {
// Handle missing resource
} else if (error.code === 'VALIDATION_ERROR') {
// Handle validation error
console.error(error.details);
} else {
// Handle unexpected error
throw error;
}
}RESOURCE_NOT_FOUND- Requested resource not foundVALIDATION_ERROR- Input validation failedSTATE_CONFLICT- State operation conflictPERMISSION_DENIED- Insufficient permissionsNETWORK_ERROR- Network operation failedTIMEOUT- Operation timed out
- Always use ResourceLoader for accessing framework resources
- Prefer async methods for I/O operations
- Handle resource not found errors gracefully
- Cache expensive operations when possible
- Use atomic state updates to prevent conflicts
- Create checkpoints before major operations
- Validate state transitions
- Handle concurrent modifications
- Use specific error codes for different scenarios
- Provide meaningful error messages
- Include context in error details
- Log errors appropriately
- Use streaming for large files
- Implement pagination for lists
- Cache frequently accessed data
- Monitor memory usage
import { ResourceLoader } from 'aiwf/lib/resource-loader';
import { StateIndexManager } from 'aiwf/lib/state/state-index';
export default class CustomCommand {
constructor() {
this.loader = new ResourceLoader();
this.stateManager = new StateIndexManager('.aiwf');
}
async execute(args) {
// Load current state
const state = await this.stateManager.loadState();
// Perform operations
// ...
// Save updated state
await this.stateManager.saveState(state);
}
}export default {
name: 'my-plugin',
version: '1.0.0',
async init(context) {
this.logger = context.logger;
this.logger.info('My plugin initialized');
},
commands: {
'my-command': {
description: 'My custom command',
handler: async (args, options) => {
// Command implementation
}
}
},
hooks: {
'after-state-change': async (oldState, newState) => {
this.logger.info('State changed', {
from: oldState.workflow_mode,
to: newState.workflow_mode
});
}
}
};import { CompressionEngine } from 'aiwf/utils/compression-engine';
const engine = new CompressionEngine();
// Analyze before compression
const analysis = engine.analyzeCompression(largeContent);
console.log(`Potential savings: ${analysis.savingsPercent}%`);
// Compress with specific strategy
const compressed = await engine.compress(largeContent, {
strategy: 'aggressive',
preserveStructure: true
});
// Later, decompress
const original = await engine.decompress(compressed);-
v0.3.x - Current stable release
- Complete API redesign
- Plugin system introduction
- Enhanced state management
-
v0.2.x - Legacy version
- Basic command structure
- Initial resource loader
-
v0.1.x - Initial release
- Core framework setup
For detailed changelog, see CHANGELOG.md.