Complete API documentation for @dcyfr/ai framework.
Load and validate configuration from files or defaults.
Parameters:
options?: LoaderOptions- Configuration loader options
Returns: Promise<FrameworkConfig> - Validated configuration
Example:
import { loadConfig } from '@dcyfr/ai';
const config = await loadConfig({
projectRoot: '/path/to/project',
enableEnvOverrides: true,
});Configuration loader with three-layer merge.
Constructor:
new ConfigLoader(options?: LoaderOptions)Methods:
Load complete configuration with three-layer merge.
Validate configuration against schema.
Get path to configuration file if it exists.
Example:
import { ConfigLoader } from '@dcyfr/ai';
const loader = new ConfigLoader({
projectRoot: process.cwd(),
configFile: 'custom.yaml',
});
const config = await loader.load();All configuration schemas exported from @dcyfr/ai:
FrameworkConfigSchema- Main configurationTelemetryConfigSchema- Telemetry settingsProviderConfigSchema- Provider settingsValidationGateConfigSchema- Validation gatesPluginConfigSchema- Plugin settingsDesignTokenConfigSchema- Design token validationBarrelExportConfigSchema- Barrel export checkingPageLayoutConfigSchema- PageLayout enforcementTestDataConfigSchema- Test data safety
Core telemetry tracking engine.
Constructor:
new TelemetryEngine(options?: {
storage?: StorageType | StorageAdapter; // default: 'memory'
basePath?: string; // used by the 'file' storage type
})Methods:
Start a new telemetry session.
Parameters:
agent: AgentType- Agent identifieroptions: { taskType: TaskType; description: string }- Session metadata
Get an active session.
End an active session by ID.
Get statistics for an agent.
Compare all agents, with recommendations.
Summarize agent handoffs.
Example:
import { TelemetryEngine } from '@dcyfr/ai';
const engine = new TelemetryEngine({
storage: 'file',
basePath: '.dcyfr/telemetry',
});
const session = engine.startSession('anthropic', {
taskType: 'feature',
description: 'Add dark mode',
});A running session, returned by TelemetryEngine.startSession(). It is not constructed directly.
Methods:
recordMetric(metric: keyof TelemetryMetrics, value: number): voidrecordValidation(validation: string, status: ValidationStatus): voidrecordViolation(violation: Omit<ViolationRecord, 'timestamp'>): voidrecordHandoff(handoff: Omit<HandoffRecord, 'timestamp' | 'fromAgent'>): voidupdateCost(inputTokens: number, outputTokens: number): voidgetSession(): TelemetrySessionend(outcome: TaskOutcome): Promise<TelemetrySession>
Example:
import { TelemetryEngine } from '@dcyfr/ai';
const engine = new TelemetryEngine({ storage: 'memory' });
const session = engine.startSession('anthropic', {
taskType: 'feature',
description: 'Implement auth',
});
session.recordMetric('tokenCompliance', 0.95);
await session.end('success');Multi-provider AI with automatic fallback.
Constructor:
new ProviderRegistry(config: ProviderRegistryConfig)Config:
interface ProviderRegistryConfig {
primaryProvider: ProviderType;
fallbackChain: ProviderType[];
autoReturn: boolean; // return to the primary when it recovers
healthCheckInterval: number; // ms
sessionStatePath?: string;
validationLevel?: 'standard' | 'enhanced' | 'strict';
}Methods:
Run executor against the current provider, falling back along fallbackChain on failure.
Parameters:
task: TaskContext- Execution context (description,phase,filesInProgress)executor: (provider: ProviderType) => Promise<T>- Execution function
Get the active provider.
Get health status for every provider.
Stop health monitoring.
Example:
import { ProviderRegistry } from '@dcyfr/ai';
const registry = new ProviderRegistry({
primaryProvider: 'anthropic',
fallbackChain: ['github-models', 'ollama'],
autoReturn: true,
healthCheckInterval: 60000,
});
const result = await registry.executeWithFallback(
{
description: 'Implement feature',
phase: 'implementation',
filesInProgress: ['src/app.ts'],
},
async (provider) => {
return await callAI(provider);
}
);
registry.destroy();Dynamic plugin loading and management.
Constructor:
new PluginLoader(config?: PluginLoaderConfig)Config:
interface PluginLoaderConfig {
failureMode?: 'throw' | 'warn' | 'silent';
autoLoad?: boolean;
timeout?: number; // ms
}Methods:
Load a single plugin.
Load multiple plugins.
Run all loaded plugins.
Get number of loaded plugins.
Unload all plugins.
Example:
import { PluginLoader } from '@dcyfr/ai';
const loader = new PluginLoader({
failureMode: 'warn',
timeout: 30000,
});
await loader.loadPlugin({
manifest: {
name: 'my-validator',
version: '1.0.0',
description: 'Custom validator',
},
async onValidate(context) {
return {
valid: true,
violations: [],
warnings: [],
};
},
});interface Plugin {
manifest: PluginManifest;
onLoad?: () => void | Promise<void>;
onUnload?: () => void | Promise<void>;
onValidate?: (context: ValidationContext) => Promise<ValidationResult>;
onComplete?: () => void | Promise<void>;
}
interface PluginManifest {
name: string;
version: string;
description: string;
author?: string;
license?: string;
dependencies?: Record<string, string>;
}Orchestrate validation gates and plugins.
Constructor:
new ValidationFramework(config?: ValidationFrameworkConfig)Config:
interface ValidationFrameworkConfig {
gates?: ValidationGate[];
failureMode?: 'error' | 'warn' | 'block';
parallel?: boolean;
timeout?: number;
}
interface ValidationGate {
name: string;
plugins: string[];
required: boolean;
failureMode: 'error' | 'warn' | 'skip';
}Methods:
Load plugins into framework.
Run validation with all gates.
Parameters:
context: ValidationContext
Returns: Promise<ValidationReport>
A gate whose plugins are all missing or disabled runs nothing and is reported with skipped: true:
- A
requiredgate that is skipped fails, with agate-skippedviolation (severityerror) naming the plugins. - An optional gate that is skipped passes with a
gate-skippedwarning. report.validistrueonly when no gate failed and at least one gate ran. A run where every gate was skipped, or with no gates, is not valid.
interface ValidationReport {
valid: boolean;
gates: {
name: string;
passed: boolean;
skipped: boolean;
violations: ValidationViolation[];
warnings: ValidationViolation[];
executionTime: number;
}[];
summary: {
totalGates: number;
passedGates: number;
failedGates: number;
skippedGates: number;
totalViolations: number;
totalWarnings: number;
executionTime: number;
};
}Get configured gates.
Example:
import { ValidationFramework } from '@dcyfr/ai';
const framework = new ValidationFramework({
gates: [
{
name: 'code-quality',
plugins: ['eslint', 'typescript'],
required: true,
failureMode: 'error',
},
],
parallel: true,
});
const report = await framework.validate({
projectRoot: process.cwd(),
files: ['src/**/*.ts'],
config: {},
});// Agent types
type AgentType = 'ollama' | 'workbench' | 'github-models' | 'anthropic';
// Task types
type TaskType =
| 'feature' | 'bug' | 'refactor' | 'quick-fix' | 'research'
| 'documentation' | 'testing' | 'plugin_installation';
// Task outcomes
type TaskOutcome = 'success' | 'escalated' | 'failed' | 'partial';
// Validation severity
type ValidationSeverity = 'error' | 'warning' | 'info';
// Storage types
type StorageType = 'memory' | 'file' | 'redis' | 'database';interface TelemetrySession {
sessionId: string;
agent: AgentType;
taskType: TaskType;
taskDescription: string;
startTime: Date;
endTime?: Date;
outcome?: TaskOutcome;
metrics: TelemetryMetrics;
violations: ViolationRecord[];
handoffs: HandoffRecord[];
cost: { provider: string; inputTokens: number; outputTokens: number; estimatedCost: number; currency: 'USD' | 'EUR' | 'GBP' };
}
interface TelemetryMetrics {
tokenCompliance: number;
testPassRate: number;
lintViolations: number;
typeErrors: number;
executionTime: number;
tokensUsed: number;
filesModified: number;
linesChanged: number;
validations: Record<string, ValidationStatus>;
}type ProviderType = 'local' | 'ollama' | 'workbench' | 'github-models' | 'anthropic';
interface ProviderConfig {
name: ProviderType;
apiEndpoint?: string;
healthCheckUrl?: string;
maxRetries: number;
retryDelay: number;
timeout: number;
enabled?: boolean;
}
interface ProviderHealth {
provider: ProviderType;
available: boolean;
responseTime?: number;
lastChecked: Date;
rateLimitRemaining?: number;
rateLimitReset?: Date;
error?: string;
}interface ValidationContext {
projectRoot: string;
files: string[];
config: Record<string, unknown>;
metadata?: Record<string, unknown>;
}
interface ValidationResult {
valid: boolean;
violations: ValidationViolation[];
warnings: ValidationViolation[];
metadata?: Record<string, unknown>;
}
interface ValidationViolation {
type: string;
severity: 'error' | 'warning' | 'info';
message: string;
file?: string;
line?: number;
column?: number;
fixed?: boolean;
}
interface ValidationReport {
valid: boolean;
gates: GateResult[];
summary: ValidationSummary;
}Thrown when provider rate limit is exceeded.
class RateLimitError extends Error {
constructor(message: string, provider: ProviderType, retryAfter?: number);
}Thrown when provider is unavailable.
class ProviderUnavailableError extends Error {
constructor(message: string, provider: ProviderType);
}Thrown when plugin fails to load.
class PluginLoadError extends Error {
constructor(message: string, pluginName: string, cause?: Error);
}Thrown when plugin manifest is invalid.
class PluginValidationError extends Error {
constructor(message: string, pluginName: string);
}interface StorageAdapter {
type: StorageType;
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T): Promise<void>;
delete(key: string): Promise<void>;
list(prefix?: string): Promise<string[]>;
clear(): Promise<void>;
}
// Built-in adapters and factory
class MemoryStorageAdapter implements StorageAdapter { }
class FileStorageAdapter implements StorageAdapter { }
function createStorageAdapter(type: StorageType, options?: { basePath?: string }): StorageAdapter;// Default configuration
export const DEFAULT_CONFIG: FrameworkConfig;For more examples and guides, see: