import { LocalAIConfig, LocalAIResponse } from './local-ai.js'; export interface HisConfig { projectRoot: string; historyDir?: string; maxCacheAge?: number; autoCleanup?: boolean; localAI?: { modelPath?: string; tokenizerPath?: string; autoDownload?: boolean; repoUrl?: string; modelUrl?: string; tokenizerUrl?: string; contextSize?: number; maxTokens?: number; temperature?: number; enableCache?: boolean; }; } export interface RequiredHisConfig { projectRoot: string; historyDir: string; maxCacheAge: number; autoCleanup: boolean; localAI?: LocalAIConfig; } export interface Session { session_id: string; model: string; provider: string; /** * Trace identifier for the overall job / workflow. * Useful when multiple sessions or agents participate in the same logical task. */ trace_id?: string; started_at: string; user_intent: string; status: 'active' | 'completed' | 'aborted'; } export interface Event { event_id: string; session_id: string; /** * Optional tracing identifiers so callers can stitch together * multi‑agent / multi‑step workflows. */ trace_id?: string; span_id?: string; parent_span_id?: string | null; type: 'file_edit' | 'file_create' | 'file_delete' | 'command' | 'analysis' | 'message'; target: string; before: string | null; after: string | null; diff: string; /** * Optional metadata for provider‑agnostic information such as: * - agent role * - model / provider details * - token counts * - arbitrary structured data */ metadata?: Record; timestamp: string; } export interface TraceNode { trace_id?: string; span_id?: string; parent_span_id?: string | null; /** * All events that share this span_id. */ events: Event[]; /** * Optional human friendly name / role carried via metadata. */ name?: string; role?: string; metadata?: Record; children: TraceNode[]; } export interface TodoStep { id: number; action: string; status: 'pending' | 'active' | 'done' | 'failed'; } export interface Todo { task_id: string; goal: string; steps: TodoStep[]; created_at: string; status: 'active' | 'done' | 'aborted'; } export interface Summary { project: string; architecture: string; decisions: string[]; updated_at: string; } export interface CacheEntry { context: any; expires_at: string; } export interface Index { sessions: string[]; events: string[]; todos: string[]; last_updated: string; } export interface Feedback { rating?: 1 | 2 | 3 | 4 | 5; comment?: string; userCorrectedText?: string; tags?: string[]; created_at: string; } export interface EventWithFeedback extends Event { feedback?: Feedback; } export interface AnalyticsQuery { timeRange?: '1d' | '7d' | '30d' | '90d' | 'custom'; startDate?: string; endDate?: string; metrics?: AnalyticsMetric[]; models?: string[]; providers?: string[]; filters?: { eventTypes?: EventType[]; taskStatus?: TodoStep['status'][]; sessionStatus?: Session['status'][]; }; groupBy?: 'model' | 'provider' | 'day' | 'week' | 'month'; } export type AnalyticsMetric = 'session_count' | 'event_count' | 'task_completion_rate' | 'error_rate' | 'productivity_score' | 'avg_session_duration' | 'code_changes_per_session' | 'model_usage' | 'cost_analysis' | 'success_rate'; export type EventType = Event['type']; export interface AnalyticsResult { query: AnalyticsQuery; data: AnalyticsData[]; summary: AnalyticsSummary; insights: string[]; recommendations: string[]; } export interface AnalyticsData { timestamp: string; dimensions: Record; metrics: Record; } export interface AnalyticsSummary { totalSessions: number; totalEvents: number; totalTasks: number; avgProductivity: number; topModel: string; topProvider: string; period: string; } export interface PatternDetection { type: 'repeated_errors' | 'productivity_patterns' | 'model_preferences' | 'task_complexity'; threshold: number; confidence: number; } export interface Pattern { id: string; type: PatternDetection['type']; description: string; frequency: number; confidence: number; examples: any[]; recommendations: string[]; detected_at: string; } export interface ModelPerformance { model: string; provider: string; metrics: { avgResponseTime: number; successRate: number; errorRate: number; taskCompletionRate: number; codeQualityScore: number; costPerTask: number; userSatisfaction: number; }; usage: { sessionCount: number; totalEvents: number; totalTasks: number; costBreakdown: Record; }; comparison: { rank: number; betterThan: string[]; worseThan: string[]; }; } export interface CostAnalysis { period: string; totalCost: number; byModel: Record; byProvider: Record; byTaskType: Record; trends: { daily: number[]; weekly: number[]; monthly: number[]; }; projections: { nextMonth: number; nextQuarter: number; nextYear: number; }; } export interface CollaborationSession { collaboration_id: string; participants: CollaborationParticipant[]; started_at: string; status: 'active' | 'completed' | 'paused'; shared_context: any; communication_log: CommunicationEvent[]; } export interface CollaborationParticipant { model: string; provider: string; role: 'architect' | 'implementer' | 'reviewer' | 'tester'; status: 'active' | 'idle' | 'disconnected'; capabilities: string[]; } export interface CommunicationEvent { event_id: string; from: string; to: string | string[]; type: 'message' | 'task_assignment' | 'review' | 'approval' | 'rejection'; content: string; timestamp: string; metadata?: any; } export interface HisPlugin { name: string; version: string; description: string; author: string; dependencies?: string[]; initialize(his: HisJS): Promise; destroy?(): Promise; onSessionStart?(session: Session): Promise; onSessionEnd?(session: Session): Promise; onEvent?(event: Event): Promise; onTodoCreate?(todo: Todo): Promise; onTodoUpdate?(todo: Todo): Promise; onAnalyticsQuery?(query: AnalyticsQuery): Promise; onAnalyticsResult?(result: AnalyticsResult): Promise; validateEvent?(event: Event): Promise; validateTodo?(todo: Todo): Promise; } export interface PluginRegistry { plugins: Map; hooks: Map; enabled: Set; } export interface TimelineConfig { view: 'gantt' | 'chronological' | 'kanban' | 'calendar'; filters?: { models?: string[]; providers?: string[]; eventTypes?: EventType[]; dateRange?: { start: string; end: string; }; }; grouping?: 'session' | 'model' | 'task' | 'day'; layout?: { width: number; height: number; theme: 'light' | 'dark' | 'auto'; }; } export interface DiffViewerConfig { format: 'side-by-side' | 'unified' | 'split'; syntax: boolean; lineNumbers: boolean; whitespace: boolean; context: number; } export interface SyncConfig { provider: 'aws-s3' | 'google-cloud' | 'azure' | 'github' | 'custom'; endpoint?: string; credentials: any; encryption: boolean; encryptionKey?: string; conflictResolution: 'manual' | 'auto_wins' | 'merge' | 'timestamp'; syncFrequency?: number; includePatterns?: string[]; excludePatterns?: string[]; } export interface BackupConfig { schedule: string; retention: number; compression: boolean; encryption: boolean; destinations: SyncConfig[]; } export interface SecurityConfig { encryption: { algorithm: string; keyRotation: number; atRest: boolean; inTransit: boolean; }; access: { authentication: 'none' | 'basic' | 'oauth' | 'saml' | 'ldap'; authorization: 'rbac' | 'abac' | 'none'; sessionTimeout: number; }; audit: { logLevel: 'debug' | 'info' | 'warn' | 'error'; retention: number; compliance: ['SOC2' | 'GDPR' | 'HIPAA' | 'ISO27001']; }; } export interface AuditReport { id: string; compliance: string; period: { start: string; end: string; }; findings: AuditFinding[]; score: number; recommendations: string[]; generated_at: string; } export interface AuditFinding { severity: 'low' | 'medium' | 'high' | 'critical'; category: string; description: string; evidence: any[]; remediation: string; } export interface DashboardConfig { port: number; host?: string; auth: 'none' | 'basic' | 'oauth' | 'api_key'; features: ('analytics' | 'timeline' | 'collaboration' | 'security' | 'settings')[]; theme: 'light' | 'dark' | 'auto'; branding?: { title: string; logo?: string; favicon?: string; }; } export interface APIConfig { endpoints: string[]; rateLimit: string; cors: boolean; authentication: 'none' | 'api_key' | 'oauth' | 'jwt'; documentation: boolean; version: string; } export interface HNVLoadOptions { /** * Base directory to resolve the env file from. * Defaults to process.cwd(). */ projectRoot?: string; /** * Env filename, e.g. ".env", ".env.local". * Defaults to ".env". */ fileName?: string; /** * Keys that must be present after loading (in env or defaults). */ required?: string[]; /** * Default values if not set anywhere else. */ defaults?: Record; /** * If true, values from the env file override existing process.env values. * By default, existing process.env wins. */ overrideExisting?: boolean; } export interface HNVLoadResult { /** * The resolved values (defaults + file + process.env). */ env: Record; /** * Any required keys that are still missing/empty after loading. */ missing: string[]; } export interface HTTPAdapterConfig { /** * Unique name for the adapter. */ name: string; /** * Provider label (e.g. "openai", "anthropic", "google", "ollama", "custom"). */ provider: string; /** * Default model identifier used if call.model is not set. */ defaultModel?: string; /** * Endpoint URL to send requests to. */ endpoint: string; /** * Optional static headers (e.g. Authorization). */ headers?: Record; /** * Optional function to compute headers dynamically from the call. */ buildHeaders?: (request: AIModelCall) => Record; /** * Convert the generic AIModelCall into the provider-specific JSON payload. */ buildRequestBody: (request: AIModelCall) => any; /** * Parse the provider-specific JSON response into AIModelResponse fields. */ parseResponse: (json: any, originalRequest: AIModelCall) => AIModelResponse; } export interface AIModelMessage { role: 'system' | 'user' | 'assistant' | 'tool' | string; content: string; name?: string; metadata?: Record; } export interface AIModelCall { /** * Model identifier, e.g. "gpt-4.1", "claude-3.5-sonnet", "gemini-2.0-pro". */ model: string; /** * Optional provider label, e.g. "openai", "anthropic", "google", "ollama", * "openrouter", "huggingface", "grok", or any custom string. */ provider?: string; messages: AIModelMessage[]; maxTokens?: number; temperature?: number; /** * Optional per-provider extras (e.g. tools, response format, etc.). */ extras?: Record; } export interface AIModelTokenUsage { input?: number; output?: number; total?: number; } export interface AIModelResponse { id?: string; model: string; provider?: string; created_at?: string; content: string; tokens?: AIModelTokenUsage; /** * The raw provider response for advanced inspection. */ raw?: any; } export interface AIModelAdapter { /** * Unique name for this adapter, e.g. "openai:gpt-4.1" or "local:ollama:llama3". */ name: string; provider: string; /** * Optional default model identifier used if call.model is not set. */ defaultModel?: string; /** * Perform the provider‑specific call and return a normalized response. */ call(request: AIModelCall): Promise; } export interface PruneHistoryOptions { /** * If omitted, uses current session's messages. */ sessionId?: string; /** * Keep last N non-system messages verbatim. Default 5. */ keepLastN?: number; /** * If provided, always include this as the system message (even if the * stored history contains a different system message). */ systemPrompt?: string | AIModelMessage; /** * Choose how the middle chunk is summarized. */ summarizer?: { /** * Use a registered adapter by name to generate the summary. */ adapterName?: string; /** * If true and LocalAI is configured, prefer LocalAI summarization. */ preferLocalAI?: boolean; /** * Override the summarizer instruction prompt. */ instruction?: string; /** * Max tokens for the generated summary (provider-side). */ maxTokens?: number; }; /** * Optional token estimator. If not provided, a conservative heuristic is used. */ tokenEstimator?: (text: string) => number; } export interface MultiModelCandidate { adapterName: string; response: AIModelResponse; score: number; reason: string; } export interface MultiModelCodeResult { task: string; context?: any; best: MultiModelCandidate; candidates: MultiModelCandidate[]; } export interface AISessionConfig { /** * High-level description of what this AI session is trying to accomplish. */ userIntent: string; /** * One or more adapter names that this session is allowed to use. */ adapters: string[]; /** * Optional dedicated evaluator adapter for multi-model code selection. */ evaluationAdapterName?: string; /** * Optional initial trace identifier for this workflow. * If omitted, a new one is generated. */ traceId?: string; /** * Optional model/provider labels used when starting the underlying Session. * These are mostly for analytics; real calls are done via adapters. */ displayModel?: string; displayProvider?: string; } export interface AISessionHandle { /** * Underlying persisted session. */ session: Session; /** * Trace identifier for this workflow. */ traceId: string; /** * Ask a question / send a message via a specific adapter. * This automatically: * - records the user message * - prunes history to fit within maxTokens * - calls the adapter * - records the assistant message */ ask(message: string, options?: { adapterName?: string; maxTokens?: number; temperature?: number; systemPrompt?: string; }): Promise; /** * Ask multiple models to generate code and pick the best result. */ generateCode(task: string, options?: { context?: any; }): Promise; /** * Apply a file change with automatic before/after snapshot and rollback. */ commitFileChange(filePath: string, action: () => Promise): Promise<{ event: Event; rollback: () => Promise; }>; } export declare class HisJS { private config; private currentSession; private plugins; private eventEmitter; private localAI; private modelAdapters; constructor(config: HisConfig); initialize(): Promise; startSession(userIntent: string, model: string, provider: string, traceId?: string): Promise; endSession(status?: 'completed' | 'aborted'): Promise; getCurrentSession(): Session | null; getSession(sessionId: string): Promise; listSessions(): Promise; recordEvent(type: Event['type'], target: string, diff: string, before?: string | null, after?: string | null, options?: { traceId?: string; spanId?: string; parentSpanId?: string | null; metadata?: Record; }): Promise; getEvent(eventId: string): Promise; listEvents(sessionId?: string): Promise; /** * Record a chat message in the history as an event of type "message". * This is provider-agnostic: you can store OpenAI/Claude/Gemini/Ollama/etc. */ recordMessage(message: AIModelMessage, options?: { traceId?: string; spanId?: string; parentSpanId?: string | null; metadata?: Record; }): Promise; /** * List recorded chat messages (from events) for a session. */ listMessages(sessionId?: string): Promise; /** * Return a pruned message history that fits within maxTokens. * Keeps the system prompt (if present) + last N messages verbatim, and * summarizes the middle chunk using either: * - a registered adapter (any API provider) * - LocalAI (offline-ish) if configured * - a simple fallback summarizer */ getPrunedHistory(maxTokens: number, options?: PruneHistoryOptions): Promise; /** * Build a trace tree for a given trace_id across all events. * This lets you see a multi‑agent / multi‑step workflow as a hierarchy. */ getTraceTree(traceId: string): Promise; createTodo(goal: string, steps: string[]): Promise; updateTodoStep(taskId: string, stepId: number, status: TodoStep['status']): Promise; /** * Convenience helper to create a TODO from an AI model adapter. * This works with any provider (OpenAI, Claude, Gemini, Ollama, etc.) * as long as you register an AIModelAdapter. */ generateTodoWithModel(adapterName: string, goal: string, options?: { context?: any; call?: Partial>; }): Promise<{ todo: Todo; aiResponse: AIModelResponse; }>; getTodo(taskId: string): Promise; listTodos(): Promise; updateSummary(summary: Omit): Promise; getSummary(): Promise; setCache(key: string, context: any, ttl?: number): Promise; getCache(key: string): Promise; deleteCache(key: string): Promise; cleanCache(): Promise; getAnalytics(query: AnalyticsQuery): Promise; detectPatterns(detection: PatternDetection): Promise; compareModels(options: { models: string[]; tasks?: string[]; timeRange?: string; }): Promise; getCostBreakdown(period: string): Promise; startCollaboration(participants: CollaborationParticipant[]): Promise; sendMessageToCollaboration(collaborationId: string, from: string, to: string | string[], content: string, type?: CommunicationEvent['type']): Promise; use(plugin: HisPlugin): Promise; removePlugin(name: string): Promise; listPlugins(): HisPlugin[]; createTimeline(config: TimelineConfig): any; showDiff(sessionId: string, config: DiffViewerConfig): any; on(event: string, callback: (data: any) => void): void; off(event: string, callback: (data: any) => void): void; private emitEvent; generateTodoWithAI(input: string, context?: any): Promise<{ todo: Todo; aiResponse: LocalAIResponse; }>; generateQuickSummary(input: string, context?: any): Promise; analyzeWithAI(input: string, context?: any): Promise; getSuggestionsWithAI(input: string, context?: any): Promise; getLocalAIStatus(): { isConfigured: boolean; isReady: boolean; cacheStats?: { size: number; keys: string[]; }; }; clearLocalAICache(): void; unloadLocalAI(): Promise; replaySession(sessionId: string): Promise; getSessionTimeline(sessionId: string): Promise<{ session: Session; events: Event[]; todos: Todo[]; }>; /** * Create a high-level AI session handle that wraps: * - Session lifecycle * - Message recording * - History pruning * - Adapter calls * - Multi-model code generation * - File change commits with snapshots */ createAISession(config: AISessionConfig): Promise; /** * Perform a file action while automatically capturing before/after snapshots * and recording an event. Returns a rollback function that restores the * previous state. */ recordFileActionWithSnapshot(type: Extract, absoluteFilePath: string, action: () => Promise, options?: { traceId?: string; spanId?: string; parentSpanId?: string | null; metadata?: Record; }): Promise<{ event: Event; rollback: () => Promise; }>; private getHistoryPath; private writeSession; private writeEvent; /** * Attach structured feedback (rating, comments, corrected text) to an event. * This powers post‑hoc evaluation and export of low‑rated interactions. */ addFeedbackToEvent(eventId: string, feedback: Omit): Promise; /** * Return all events that have feedback, optionally filtered by rating. * Useful for exporting "low rated" logs to understand prompt / model issues. */ listEventsWithFeedback(options?: { minRating?: number; maxRating?: number; }): Promise; private writeTodo; private readIndex; private writeIndex; /** * Register an AI model adapter that can call any provider (OpenAI, Claude, * Gemini, Ollama, OpenRouter, Hugging Face, Grok, offline models, etc.). */ registerModelAdapter(adapter: AIModelAdapter): void; /** * Remove a previously registered model adapter. */ unregisterModelAdapter(name: string): void; /** * List all registered model adapters. */ listModelAdapters(): AIModelAdapter[]; /** * Ask multiple models (via adapters) to generate code for the same task, * optionally evaluate their outputs, and return the best candidate plus all * alternatives. This is provider-agnostic: adapters can wrap OpenAI, Claude, * Gemini, Ollama, Grok, HuggingFace, local models, etc. */ generateCodeWithMultipleModels(options: { task: string; adapters: string[]; context?: any; /** * Optional dedicated evaluator adapter name. If provided, that adapter * will be asked to choose the best candidate; otherwise a simple heuristic * is used (non-empty, longer, fewer obvious error markers). */ evaluationAdapterName?: string; /** * Optional trace/span identifiers so this orchestration is visible as a * single workflow in the trace tree. */ traceId?: string; spanId?: string; parentSpanId?: string | null; }): Promise; private filterData; private calculateMetrics; private generateSummary; private generateInsights; private generateRecommendations; private detectRepeatedErrors; private detectProductivityPatterns; private detectModelPreferences; private detectTaskComplexity; private calculateModelPerformance; private calculateCosts; private writeCollaboration; private getCollaboration; private registerPluginHooks; private unregisterPluginHooks; private prepareTimelineData; private renderTimeline; private prepareDiffData; private renderDiff; private getTimeRangeFilter; private isInTimeRange; private groupDataByDimension; private getTimestampForGroup; private calculateTaskCompletionRate; private calculateErrorRate; private calculateProductivityScore; private calculateAvgSessionDuration; private calculateCodeChangesPerSession; private calculateModelUsage; private estimateCosts; private calculateSuccessRate; private calculateAvgResponseTime; private estimateCodeQuality; private estimateCostPerTask; private estimateUserSatisfaction; private calculateCostBreakdownByType; private estimateSessionCost; /** * Return the sequence of file-related events for a given target path, * ordered by timestamp. */ getFileHistory(targetPath: string): Promise; /** * Reconstruct the contents of a file at a particular point in HIS history. * If no events have touched the file yet, returns null. */ reconstructFileAt(targetPath: string, options: { timestamp?: string; eventId?: string; }): Promise; /** * High-level timeline for a given session, trace, or file. */ getTimeline(options: { sessionId?: string; traceId?: string; targetPath?: string; }): Promise<{ sessions: Session[]; events: Event[]; todos: Todo[]; }>; /** * Simple aggregated view of model/provider usage across sessions. */ getModelUsageOverview(): Promise<{ byModel: Record; byProvider: Record; totalSessions: number; }>; /** * Combined cost & quality snapshot suitable for a dashboard. */ getCostAndQualityOverview(): Promise<{ cost: CostAnalysis; topModels: ModelPerformance[]; recentPatterns: Pattern[]; }>; private estimateTokensHeuristic; private estimateMessageTokens; private estimateMessagesTokens; private enforceTokenBudget; private summarizeText; private scoreCandidatesWithEvaluator; private scoreCandidatesHeuristically; } /** * hnv: simple, deterministic env loader for HIS-aware apps. * * Usage: * const { env, missing } = await hnv.load({ * projectRoot: '/path/to/project', * fileName: '.env', * required: ['OPENAI_API_KEY'], * defaults: { NODE_ENV: 'development' } * }); */ export declare const hnv: { readonly load: (options?: HNVLoadOptions) => Promise; }; /** * Create a generic HTTP-based adapter that can talk to many different * providers (OpenAI-style APIs, hosted models, custom gateways, etc.). * * You supply how to build the request body and how to parse the response. */ export declare function createHTTPAdapter(config: HTTPAdapterConfig): AIModelAdapter; export default HisJS; //# sourceMappingURL=index.d.ts.map