> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiagentshouse.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Types

> Complete TypeScript type definitions for the AI Agents House SDK

This page provides comprehensive TypeScript type definitions for all interfaces, types, and enums used throughout the AI Agents House SDK.

## Core Configuration Types

### AgentMonitoringConfig

Main configuration interface for the AgentMonitor class.

```typescript theme={null}
interface AgentMonitoringConfig {
  apiKey: string;                    // Required: Your governance API key
  organizationId: string;            // Required: Your organization ID
  endpoint?: string;                 // Optional: Custom API endpoint
  environment?: Environment;         // Optional: Deployment environment
  batchSize?: number;               // Optional: Events per batch (1-1000)
  flushInterval?: number;           // Optional: Flush interval in ms (min 100)
  enableComplianceChecks?: boolean; // Optional: Enable compliance monitoring
  enableLogging?: boolean;          // Optional: Enable SDK logging
  logLevel?: LogLevel;              // Optional: Minimum log level
  retryAttempts?: number;           // Optional: Retry attempts (0-10)
  retryDelay?: number;              // Optional: Delay between retries in ms
}

type Environment = 'production' | 'staging' | 'development';
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
```

### MonitoringOptions

Optional configuration for individual interactions.

```typescript theme={null}
interface MonitoringOptions {
  requestId?: string;               // Custom request identifier
  userId?: string;                  // User identifier for the interaction
  sessionId?: string;               // Override session ID
  agentCategory?: AgentCategory;    // Agent category for this interaction
  agentSpecialty?: BankingSpecialty; // Agent specialty for this interaction
  trackConversationStart?: boolean; // Whether to track conversation start
  complianceChecks?: boolean;       // Override global compliance setting
}
```

## Agent Types

### AgentInfo

Complete agent registration information.

```typescript theme={null}
interface AgentInfo {
  id: string;                       // Unique agent identifier
  name: string;                     // Human-readable agent name
  category: AgentCategory;          // Agent type classification
  specialty?: BankingSpecialty;     // Banking domain specialty
  version: string;                  // Agent version string
  llmProvider: string;              // LLM provider name
  model: string;                    // Model name/version
  description: string;              // Detailed agent description
  systemPrompt?: string;            // System prompt used
  availableTools?: ToolInfo[];      // Tools available to the agent
  complianceSettings?: ComplianceSettings; // Compliance configuration
}

type AgentCategory = 'persona' | 'tool_calling' | 'workflow' | 'autonomous';

type BankingSpecialty =
  | 'generalist'
  | 'personal_banking'
  | 'business_banking'
  | 'wealth_management'
  | 'mortgage_lending'
  | 'investment_services'
  | 'fraud_detection'
  | 'customer_service'
  | 'compliance';
```

### ToolInfo

Information about tools available to agents.

```typescript theme={null}
interface ToolInfo {
  name: string;                     // Tool name
  description: string;              // Tool description
  category: string;                 // Tool category
  riskLevel: RiskLevel;            // Risk level for compliance
  version?: string;                 // Tool version
  parameters?: ToolParameters;      // Tool parameter schema
}

type RiskLevel = 'low' | 'medium' | 'high';

interface ToolParameters {
  type: 'object';
  properties: Record<string, {
    type: string;
    description: string;
    required?: boolean;
    default?: any;
  }>;
  required?: string[];
}
```

### ComplianceSettings

Agent-specific compliance configuration.

```typescript theme={null}
interface ComplianceSettings {
  sr11_7_enabled: boolean;          // SR 11-7 model validation compliance
  fair_lending_monitoring: boolean; // Fair lending compliance monitoring
  bsa_aml_checks: boolean;          // BSA/AML compliance checks
  custom_rules?: string[];          // IDs of custom rules to apply
  risk_threshold?: number;          // Custom risk threshold (0-100)
}
```

## Event Types

### InteractionEvent

Generic event interface for the `track()` method.

```typescript theme={null}
interface InteractionEvent {
  sessionId: string;                // Required: Session identifier
  conversationId?: string;          // Optional: Conversation identifier
  userId?: string;                  // Optional: User identifier
  interactionType: EventType;       // Required: Type of interaction
  content?: string;                 // Content for message/error events
  toolName?: string;                // Tool name for tool events
  toolParameters?: any;             // Parameters for tool calls
  toolResult?: any;                 // Results from tool execution
  metadata?: EventMetadata;         // Additional event metadata

  // Error-specific fields (convenience for error events)
  errorType?: string;               // Error type classification
  errorCode?: string;               // Specific error code
  severity?: ErrorSeverity;         // Error severity level
}

type EventType =
  | 'conversation_start'
  | 'user_message'
  | 'agent_response'
  | 'tool_call'
  | 'tool_result'
  | 'error'
  | 'conversation_end';

type ErrorSeverity = 'low' | 'medium' | 'high' | 'critical';
```

### EventMetadata

Flexible metadata interface for events.

```typescript theme={null}
interface EventMetadata {
  // LLM Performance Metrics
  llmLatency?: number;              // LLM response time in ms
  tokensUsed?: TokenUsage;          // Token usage statistics
  cost?: number;                    // Calculated cost for the request
  temperature?: number;             // LLM temperature setting
  maxTokens?: number;               // Maximum tokens setting

  // Quality Metrics
  responseQuality?: number;         // Response quality score (0-100)
  relevanceScore?: number;          // Relevance score (0-100)
  coherenceScore?: number;          // Coherence score (0-100)
  helpfulnessScore?: number;        // Helpfulness score (0-100)

  // Tool Execution
  toolExecutionTime?: number;       // Tool execution time in ms
  toolVersion?: string;             // Version of tool used
  cacheHit?: boolean;               // Whether result was cached

  // Error Context
  errorStack?: string;              // Error stack trace
  recoverable?: boolean;            // Whether error is recoverable
  userImpact?: ImpactLevel;         // Impact on user experience
  systemImpact?: ImpactLevel;       // Impact on system functionality
  errorSource?: ErrorSource;        // Source of the error
  originalError?: any;              // Original error object

  // Conversation Context
  duration?: number;                // Conversation duration in ms
  messageCount?: number;            // Total message count
  userSatisfaction?: number;        // User satisfaction (1-10)
  resolutionStatus?: ResolutionStatus; // How conversation ended
  endReason?: EndReason;            // Reason for ending
  followUpRequired?: boolean;       // Whether follow-up is needed
  escalationReason?: string;        // Reason for escalation

  // Business Context
  customerTier?: string;            // Customer tier/segment
  channel?: string;                 // Communication channel
  deviceFingerprint?: string;       // Device identification
  geolocation?: string;             // Geographic location

  // Custom fields
  [key: string]: any;               // Allow additional custom metadata
}

interface TokenUsage {
  input: number;                    // Input tokens used
  output: number;                   // Output tokens used
  total: number;                    // Total tokens used
}

type ImpactLevel = 'none' | 'minimal' | 'moderate' | 'high';
type ErrorSource = 'client' | 'server' | 'external' | 'unknown';
type ResolutionStatus = 'resolved' | 'unresolved' | 'escalated' | 'abandoned';
type EndReason = 'user_initiated' | 'timeout' | 'error' | 'system_initiated';
```

## Detailed Event Types

The SDK internally uses more detailed event types for specific tracking:

### ConversationStartEvent

```typescript theme={null}
interface ConversationStartEvent extends BaseEvent {
  interactionType: 'conversation_start';
  metadata?: {
    userAgent?: string;             // User's browser/client info
    ipAddress?: string;             // User's IP address
    referrer?: string;              // Referring page/application
    channel?: string;               // Communication channel
    customerType?: string;          // Type of customer
    [key: string]: any;
  };
}
```

### UserMessageEvent

```typescript theme={null}
interface UserMessageEvent extends BaseEvent {
  interactionType: 'user_message';
  content: string;                  // The user's message content
  contentHash?: string;             // Hash of the content
  contentLength: number;            // Length of the content
  metadata?: {
    messageId?: string;             // Unique message identifier
    threadId?: string;              // Thread identifier
    attachments?: AttachmentInfo[]; // File attachments
    sentiment?: string;             // Detected sentiment
    language?: string;              // Detected language
    [key: string]: any;
  };
}

interface AttachmentInfo {
  type: string;                     // MIME type
  size: number;                     // File size in bytes
  name: string;                     // Original filename
  hash?: string;                    // File hash for integrity
}
```

### AgentResponseEvent

```typescript theme={null}
interface AgentResponseEvent extends BaseEvent {
  interactionType: 'agent_response';
  content: string;                  // The agent's response content
  contentHash?: string;             // Hash of the content
  contentLength: number;            // Length of the content
  llmMetadata?: LLMMetadata;        // LLM-specific metadata
  qualityMetrics?: QualityMetrics;  // Response quality metrics
  complianceFlags?: ComplianceFlag[]; // Compliance violations
  riskScore?: number;               // Calculated risk score
  requiresReview?: boolean;         // Whether human review is needed
}

interface LLMMetadata {
  model: string;                    // Model used
  provider: string;                 // LLM provider
  latency: number;                  // Response latency in ms
  tokensUsed: TokenUsage;           // Token usage
  cost?: number;                    // Calculated cost
  temperature?: number;             // Temperature setting
  maxTokens?: number;               // Max tokens setting
  topP?: number;                    // Top-p sampling parameter
  frequencyPenalty?: number;        // Frequency penalty
  presencePenalty?: number;         // Presence penalty
}

interface QualityMetrics {
  responseQuality: number;          // Overall quality score (0-100)
  relevanceScore: number;           // Relevance to user query (0-100)
  coherenceScore: number;           // Internal coherence (0-100)
  helpfulnessScore: number;         // Helpfulness rating (0-100)
  factualAccuracy?: number;         // Factual accuracy (0-100)
  completeness?: number;            // Response completeness (0-100)
}
```

### ToolCallEvent

```typescript theme={null}
interface ToolCallEvent extends BaseEvent {
  interactionType: 'tool_call';
  toolName: string;                 // Name of the tool called
  toolParameters: any;              // Parameters passed to tool
  toolCategory?: string;            // Category of the tool
  riskLevel?: RiskLevel;            // Risk level of the tool
  metadata?: {
    toolVersion?: string;           // Version of the tool
    executionContext?: string;      // Execution context
    timeout?: number;               // Tool timeout setting
    retryAttempts?: number;         // Number of retry attempts
    [key: string]: any;
  };
}
```

### ToolResultEvent

```typescript theme={null}
interface ToolResultEvent extends BaseEvent {
  interactionType: 'tool_result';
  toolName: string;                 // Name of the tool
  toolResult: any;                  // Result from tool execution
  toolError?: string;               // Error message if tool failed
  executionTime: number;            // Execution time in ms
  success: boolean;                 // Whether execution succeeded
  metadata?: {
    cacheHit?: boolean;             // Whether result was cached
    dataSource?: string;            // Source of the data
    resultSize?: number;            // Size of result in bytes
    retryCount?: number;            // Number of retries needed
    [key: string]: any;
  };
}
```

### ErrorEvent

```typescript theme={null}
interface ErrorEvent extends BaseEvent {
  interactionType: 'error';
  errorType: string;                // Classification of error type
  errorMessage: string;             // Human-readable error message
  errorStack?: string;              // Stack trace if available
  errorCode?: string;               // Specific error code
  severity: ErrorSeverity;          // Severity level
  recoverable: boolean;             // Whether error is recoverable
  metadata?: {
    userImpact: ImpactLevel;        // Impact on user experience
    systemImpact: ImpactLevel;      // Impact on system
    errorSource: ErrorSource;       // Source of the error
    originalError?: any;            // Original error object
    contextInfo?: any;              // Additional context
    [key: string]: any;
  };
}
```

### ConversationEndEvent

```typescript theme={null}
interface ConversationEndEvent extends BaseEvent {
  interactionType: 'conversation_end';
  duration: number;                 // Total conversation duration in ms
  messageCount: number;             // Total messages exchanged
  userSatisfaction?: number;        // User satisfaction rating (1-10)
  resolutionStatus: ResolutionStatus; // How conversation was resolved
  metadata?: {
    endReason: EndReason;           // Reason for ending
    followUpRequired: boolean;       // Whether follow-up is needed
    escalationReason?: string;      // Reason for escalation if any
    avgResponseTime?: number;       // Average response time
    toolCallCount?: number;         // Number of tool calls made
    errorCount?: number;            // Number of errors encountered
    [key: string]: any;
  };
}
```

## Compliance Types

### ComplianceRule

Interface for defining compliance rules.

```typescript theme={null}
interface ComplianceRule {
  id: string;                       // Unique rule identifier
  name: string;                     // Human-readable rule name
  description: string;              // Detailed rule description
  category: ComplianceCategory;     // Compliance category
  severity: ComplianceSeverity;     // Severity of violations
  isActive: boolean;                // Whether rule is active
  ruleFunction: (context: InteractionContext) => ComplianceResult; // Rule logic
  version?: string;                 // Rule version
  createdAt?: string;               // Rule creation timestamp
  updatedAt?: string;               // Rule last update timestamp
  tags?: string[];                  // Tags for organization
}

type ComplianceCategory =
  | 'sr_11_7'                       // Model validation requirements
  | 'fair_lending'                  // Fair lending compliance
  | 'bsa_aml'                       // Bank Secrecy Act / Anti-Money Laundering
  | 'privacy'                       // Privacy and PII protection
  | 'consumer_protection'           // Consumer protection regulations
  | 'custom';                       // Organization-specific rules

type ComplianceSeverity = 'info' | 'warning' | 'violation';
```

### InteractionContext

Context provided to compliance rules for evaluation.

```typescript theme={null}
interface InteractionContext {
  agentId: string;                  // Agent identifier
  agentCategory: AgentCategory;     // Agent category
  agentSpecialty?: BankingSpecialty; // Agent specialty
  userMessage?: string;             // User's message content
  agentResponse?: string;           // Agent's response content
  toolsUsed?: ToolUsageInfo[];      // Tools used in interaction
  userId?: string;                  // User identifier
  sessionId: string;                // Session identifier
  timestamp: number;                // Interaction timestamp
  metadata?: any;                   // Additional metadata

  // Extended context for banking compliance
  customerProfile?: CustomerProfile; // Customer information
  transactionContext?: TransactionContext; // Transaction details
  riskFactors?: string[];           // Identified risk factors
}

interface ToolUsageInfo {
  name: string;                     // Tool name
  parameters: any;                  // Parameters used
  result: any;                      // Result returned
  executionTime?: number;           // Execution time
  success: boolean;                 // Whether execution succeeded
}

interface CustomerProfile {
  customerId: string;               // Customer identifier
  customerTier?: string;            // Customer tier/segment
  riskRating?: string;              // Customer risk rating
  accountTypes?: string[];          // Types of accounts held
  relationshipLength?: number;      // Length of relationship in months
  previousViolations?: number;      // Number of previous violations
}

interface TransactionContext {
  transactionId?: string;           // Transaction identifier
  amount?: number;                  // Transaction amount
  transactionType?: string;         // Type of transaction
  frequency?: string;               // Transaction frequency
  location?: string;                // Transaction location
  merchantCategory?: string;        // Merchant category code
}
```

### ComplianceResult

Result returned by compliance rule evaluation.

```typescript theme={null}
interface ComplianceResult {
  isCompliant: boolean;             // Overall compliance status
  violations: ComplianceViolation[]; // Array of violations found
  riskScore: number;                // Calculated risk score (0-100)
  requiresReview: boolean;          // Whether human review is needed
  metadata?: {
    evaluationTime?: number;        // Time taken to evaluate
    rulesEvaluated?: number;        // Number of rules checked
    confidence?: number;            // Confidence in result (0-1)
    [key: string]: any;
  };
}

interface ComplianceViolation {
  rule: string;                     // ID of rule that detected violation
  severity: ComplianceSeverity;     // Severity level
  description: string;              // Human-readable description
  context?: ViolationContext;       // Additional context
  recommendation?: string;          // Suggested remediation
  confidence?: number;              // Confidence in detection (0-1)
  timestamp?: number;               // When violation was detected
}

interface ViolationContext {
  detectedContent?: string;         // Content that triggered violation
  detectedPattern?: string;         // Pattern that was matched
  riskFactors?: string[];           // Contributing risk factors
  relatedViolations?: string[];     // Related violation IDs
  customerImpact?: ImpactLevel;     // Impact on customer
  businessImpact?: ImpactLevel;     // Impact on business
  regulatoryImpact?: string;        // Potential regulatory impact
  [key: string]: any;               // Additional context fields
}
```

## Event Batching Types

### EventBatch

Structure for batched event transmission.

```typescript theme={null}
interface EventBatch {
  batchId: string;                  // Unique batch identifier
  organizationId: string;           // Organization identifier
  timestamp: number;                // Batch creation timestamp
  events: DetailedEvent[];          // Array of events in batch
  eventCount: number;               // Number of events
  totalSize: number;                // Total size in bytes
  checksum?: string;                // Batch integrity checksum
  metadata?: {
    batchVersion?: string;          // Batch format version
    compressionType?: string;       // Compression algorithm used
    encryptionInfo?: string;        // Encryption information
    [key: string]: any;
  };
}

type DetailedEvent =
  | ConversationStartEvent
  | UserMessageEvent
  | AgentResponseEvent
  | ToolCallEvent
  | ToolResultEvent
  | ErrorEvent
  | ConversationEndEvent;
```

### EventBatcherConfig

Configuration for the EventBatcher class.

```typescript theme={null}
interface EventBatcherConfig {
  batchSize: number;                // Events per batch
  flushInterval: number;            // Flush interval in ms
  onFlush: (events: DetailedEvent[]) => Promise<void>; // Flush callback
  logger: Logger;                   // Logger instance
  maxRetries?: number;              // Maximum retry attempts
  retryDelay?: number;              // Delay between retries
  compression?: boolean;            // Enable compression
  encryption?: EncryptionConfig;    // Encryption configuration
}

interface EncryptionConfig {
  enabled: boolean;                 // Whether encryption is enabled
  algorithm?: string;               // Encryption algorithm
  keyId?: string;                   // Key identifier
}
```

## Utility Types

### BaseEvent

Base interface for all events.

```typescript theme={null}
interface BaseEvent {
  eventId: string;                  // Unique event identifier
  timestamp: number;                // Event timestamp
  sessionId: string;                // Session identifier
  agentId: string;                  // Agent identifier
  userId?: string;                  // User identifier
  conversationId?: string;          // Conversation identifier
  environment: Environment;         // Environment designation
  requestId: string;                // Request identifier
  version?: string;                 // Event schema version
}
```

### Logger

Interface for logging functionality.

```typescript theme={null}
interface Logger {
  debug(message: string, data?: any): void;
  info(message: string, data?: any): void;
  warn(message: string, data?: any): void;
  error(message: string, data?: any): void;
}
```

### HttpOptions

Options for HTTP requests.

```typescript theme={null}
interface HttpOptions {
  method: string;                   // HTTP method
  headers?: Record<string, string>; // Request headers
  body?: string;                    // Request body
  timeout?: number;                 // Request timeout in ms
  retries?: number;                 // Number of retry attempts
  retryDelay?: number;              // Delay between retries
}
```

## Validation Types

### ValidationError

Error type for validation failures.

```typescript theme={null}
interface ValidationError extends Error {
  name: 'ValidationError';
  details: ValidationDetail[];      // Detailed validation errors
  field?: string;                   // Field that failed validation
  value?: any;                      // Value that failed validation
}

interface ValidationDetail {
  field: string;                    // Field path
  message: string;                  // Error message
  code: string;                     // Error code
  value?: any;                      // Invalid value
}
```

## Export Summary

All types are exported from the main module:

```typescript theme={null}
// Core configuration
export type {
  AgentMonitoringConfig,
  MonitoringOptions,
  Environment,
  LogLevel
};

// Agent types
export type {
  AgentInfo,
  AgentCategory,
  BankingSpecialty,
  ToolInfo,
  RiskLevel,
  ComplianceSettings
};

// Event types
export type {
  InteractionEvent,
  EventType,
  EventMetadata,
  TokenUsage,
  ErrorSeverity,
  ImpactLevel,
  ErrorSource,
  ResolutionStatus,
  EndReason
};

// Detailed event types
export type {
  ConversationStartEvent,
  UserMessageEvent,
  AgentResponseEvent,
  ToolCallEvent,
  ToolResultEvent,
  ErrorEvent,
  ConversationEndEvent,
  LLMMetadata,
  QualityMetrics
};

// Compliance types
export type {
  ComplianceRule,
  ComplianceCategory,
  ComplianceSeverity,
  InteractionContext,
  ComplianceResult,
  ComplianceViolation,
  ViolationContext,
  ToolUsageInfo,
  CustomerProfile,
  TransactionContext
};

// Utility types
export type {
  BaseEvent,
  EventBatch,
  EventBatcherConfig,
  Logger,
  HttpOptions,
  ValidationError,
  ValidationDetail
};
```

## Type Usage Examples

### Custom Rule with Full Typing

```typescript theme={null}
import type { ComplianceRule, InteractionContext, ComplianceResult } from '@agent-governance/node';

const customRule: ComplianceRule = {
  id: 'banking-hours-compliance',
  name: 'Banking Hours Compliance',
  description: 'Ensures banking hours are mentioned correctly',
  category: 'consumer_protection',
  severity: 'warning',
  isActive: true,
  ruleFunction: (context: InteractionContext): ComplianceResult => {
    const violations = [];
    const response = context.agentResponse || '';

    if (response.includes('banking hours') && !response.includes('Monday through Friday')) {
      violations.push({
        rule: 'banking-hours-compliance',
        severity: 'warning' as const,
        description: 'Banking hours mentioned without complete schedule',
        context: {
          detectedContent: response,
          missingInfo: 'complete_schedule'
        },
        recommendation: 'Include full banking hours (Monday through Friday, 9 AM to 5 PM)'
      });
    }

    return {
      isCompliant: violations.length === 0,
      violations,
      riskScore: violations.length * 10,
      requiresReview: violations.length > 0
    };
  }
};
```

### Strongly Typed Event Tracking

```typescript theme={null}
import type { InteractionEvent, EventMetadata, TokenUsage } from '@agent-governance/node';

const trackAgentResponse = (
  monitor: AgentMonitor,
  agentId: string,
  sessionId: string,
  content: string,
  metadata: EventMetadata
) => {
  const event: InteractionEvent = {
    sessionId,
    interactionType: 'agent_response',
    content,
    metadata: {
      llmLatency: metadata.llmLatency,
      tokensUsed: metadata.tokensUsed,
      responseQuality: metadata.responseQuality,
      cost: metadata.cost
    }
  };

  monitor.track(agentId, event);
};
```

### Type-Safe Configuration

```typescript theme={null}
import type { AgentMonitoringConfig, AgentInfo } from '@agent-governance/node';

const config: AgentMonitoringConfig = {
  apiKey: process.env.AGENT_GOVERNANCE_API_KEY!,
  organizationId: process.env.AGENT_GOVERNANCE_ORG_ID!,
  environment: 'production',
  batchSize: 100,
  flushInterval: 5000,
  enableComplianceChecks: true,
  enableLogging: false,
  logLevel: 'error',
  retryAttempts: 3,
  retryDelay: 1000
};

const agentInfo: AgentInfo = {
  id: 'banking-assistant',
  name: 'Personal Banking Assistant',
  category: 'tool_calling',
  specialty: 'personal_banking',
  version: '2.1.0',
  llmProvider: 'anthropic',
  model: 'claude-3-5-sonnet-20241022',
  description: 'AI assistant for personal banking services',
  complianceSettings: {
    sr11_7_enabled: true,
    fair_lending_monitoring: false,
    bsa_aml_checks: true
  }
};
```

## Next Steps

<CardGroup cols={2}>
  <Card title="AgentMonitor API" icon="chart-line" href="/api-reference/agent-monitor">
    Learn about the main monitoring class methods
  </Card>

  <Card title="ComplianceEngine API" icon="shield-check" href="/api-reference/compliance-engine">
    Explore compliance rule management
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/api-reference/errors">
    Understand error types and handling strategies
  </Card>

  <Card title="Examples" icon="play" href="/examples/basic-usage">
    See these types used in practical examples
  </Card>
</CardGroup>
