npm package: @onshoreoutsourcing/ai-traceability-sdk
Description: AI Traceability TypeScript SDK for comprehensive activity tracking and MCP integration
Author: AI Traceability Team
Latest version: 1.1.0

# AI Traceability TypeScript SDK

TypeScript SDK for comprehensive AI activity tracking with full feature parity to the Python SDK.

## Features

- ✅ **Complete Type Safety** - Full TypeScript type definitions
- ✅ **Async/Promise Support** - Native async/await patterns  
- ✅ **Automatic Batching** - Configurable batch processing
- ✅ **Retry Logic** - Exponential backoff with configurable retries
- ✅ **Session Management** - Context managers for activity grouping
- ✅ **Complete Tool Call Tracking** - All 25+ fields supported
- ✅ **File Tracking & Security** - Epic 4 file operation monitoring
- ✅ **MCP Integration** - Claude/Cursor IDE support
- ✅ **Browser & Node.js** - Isomorphic JavaScript support
- ✅ **Error Handling** - Comprehensive error types and handling

## Installation

```bash
npm install @onshoreoutsourcing/ai-traceability-sdk
```

## Quick Start

```typescript
import { AITraceabilityClient } from '@onshoreoutsourcing/ai-traceability-sdk';

// Initialize client
const client = new AITraceabilityClient({
  apiKey: 'your-api-key',
  serviceUrl: 'https://api.ai-traceability.com'
});

// Use with session context
await client.withSession({
  agentType: 'my-agent',
  userId: 'user123'
}, async (session) => {
  // Log a chat message
  await session.logChat('user', 'Hello, how can I help?');
  
  // Log tool usage with complete tracking
  await session.logToolCall({
    toolName: 'web_search',
    toolCategory: 'research',
    requestParams: { query: 'AI news' },
    responseData: { results: ['...'] },
    durationMs: 150,
    estimatedCostCents: 5,
    mcpServerName: 'my-mcp-server',
    status: 'completed'
  });
  
  // Log AI decision
  await session.logDecision({
    name: 'search_strategy',
    reasoningSteps: [
      'Analyzed user query',
      'Selected web search tool',
      'Formatted search parameters'
    ],
    confidenceScore: 0.9,
    selectedOption: { strategy: 'web_search' },
    alternativesConsidered: [
      { strategy: 'knowledge_base' },
      { strategy: 'direct_answer' }
    ]
  });
});

// Close client
await client.close();
```

## Advanced Usage

### Manual Session Management

```typescript
const session = client.createSession({
  agentType: 'my-agent',
  sessionId: 'custom-session-123'
});

await session.start();

try {
  await session.logActivity('processing', {
    content: 'Processing user request',
    metadata: { requestId: '123' }
  });
  
  // ... more activities
} finally {
  await session.end();
}
```

### Complete Tool Call Tracking

```typescript
await client.logToolCall('session-id', {
  // Core fields
  toolName: 'database_query',
  toolCategory: 'data',
  toolVersion: '2.1.0',
  
  // MCP server fields
  mcpServerName: 'claude-desktop',
  mcpServerVersion: '1.5.0',
  
  // Request/Response
  requestParams: { table: 'users', filters: {} },
  responseData: { count: 150, rows: [] },
  
  // Performance tracking
  startTime: new Date('2024-01-01T10:00:00Z'),
  endTime: new Date('2024-01-01T10:00:00.150Z'),
  durationMs: 150,
  cpuMs: 45,
  memoryMb: 12,
  networkBytes: 2048,
  
  // Cost tracking
  estimatedCostCents: 3,
  billingModel: 'per-query',
  rateLimitConsumed: 1,
  
  // Status
  status: 'completed',
  retryCount: 0,
  
  // Data classification
  dataClassification: 'internal',
  containsPii: true,
  
  // Tracing
  correlationId: 'req-123',
  traceId: 'trace-456',
  
  // Context
  userAgent: 'MyApp/1.0',
  sourceLocation: 'handlers/user.ts:45',
  additionalMetadata: {
    queryComplexity: 'simple',
    cacheHit: false
  }
});
```

### Configuration Options

```typescript
const client = new AITraceabilityClient({
  apiKey: 'your-api-key',
  serviceUrl: 'https://api.ai-traceability.com',
  
  // Timeout configuration
  timeout: 30000, // 30 seconds
  
  // Retry configuration
  retryAttempts: 3,
  retryDelay: 1000, // 1 second base delay
  
  // Batching configuration
  batchSize: 100,
  batchTimeout: 5000, // 5 seconds
  autoFlush: true,
  
  // Debug mode
  debug: true,
  
  // SSL verification
  verifySSL: true
});
```

### File Tracking & Security Analysis

The SDK provides comprehensive file operation tracking and security analysis capabilities:

```typescript
import { 
  FileOperationType,
  FileOperationData,
  SecurityAnalysisData 
} from '@onshoreoutsourcing/ai-traceability-sdk';

// Track basic file operations
await client.logFileRead('session-id', {
  filePath: '/app/data/config.json',
  fileSize: 1024,
  partialRead: false,
  userId: 'user@example.com',
  projectId: 'project-123'
});

await client.logFileWrite('session-id', {
  filePath: '/app/output/results.json',
  contentSize: 2048,
  operationType: 'write',
  contentHashBefore: 'abc123',
  contentHashAfter: 'def456',
  userId: 'user@example.com',
  projectId: 'project-123'
});

// Track file moves and copies
await client.logFileMove('session-id', {
  sourcePath: '/old/location.txt',
  destinationPath: '/new/location.txt',
  fileSize: 1536,
  userId: 'user@example.com'
});

// Security analysis
const securityResult = await client.analyzeFileSecurity('session-id', {
  filePath: '/suspicious/script.sh',
  operation: FileOperationType.WRITE,
  content: '#!/bin/bash\nrm -rf /',
  fileSize: 1024
});

console.log(`Risk Score: ${securityResult.riskScore}`);
console.log(`Threats: ${securityResult.threats.join(', ')}`);

// Anomaly detection
const anomalies = await client.detectFileAnomalies('session-id', {
  sessionId: 'session-id',
  timeWindowMinutes: 60
});

// Risk scoring
const riskScore = await client.calculateFileRiskScore('session-id', {
  filePath: '/system/critical.exe',
  operation: FileOperationType.DELETE,
  isSensitive: true,
  isExecutable: true,
  isSystem: true
});

// Batch file operations
await client.logFileOperationsBatch('session-id', [
  {
    operationType: FileOperationType.READ,
    sessionId: 'session-id',
    filePath: '/batch/file1.txt',
    fileSize: 1024
  },
  {
    operationType: FileOperationType.WRITE,
    sessionId: 'session-id', 
    filePath: '/batch/file2.txt',
    contentSize: 2048
  }
]);
```

### Error Handling

```typescript
import {
  AuthenticationError,
  RateLimitError,
  ValidationError,
  NetworkError,
  TimeoutError,
  ServerError
} from '@onshoreoutsourcing/ai-traceability-sdk';

try {
  await client.logActivity('session', 'chat', { content: 'test' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after: ${error.retryAfter} seconds`);
  } else if (error instanceof ValidationError) {
    console.error('Invalid request data');
  } else if (error instanceof NetworkError) {
    console.error('Network connectivity issue');
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (error instanceof ServerError) {
    console.error(`Server error: ${error.statusCode}`);
  }
}
```

## Browser Support

The SDK works in both Node.js and browser environments:

```html
<script type="module">
import { AITraceabilityClient } from '@onshoreoutsourcing/ai-traceability-sdk';

const client = new AITraceabilityClient({
  apiKey: 'your-api-key'
});

// Use as normal...
</script>
```

## Testing

```bash
# Run tests
npm test

# Run with coverage
npm run test:coverage

# Watch mode
npm run test:watch
```

## Building

```bash
# Build TypeScript
npm run build

# Development watch mode
npm run dev
```

## API Reference

### Client Methods

#### Core Activity Tracking
- `logActivity(sessionId, activityType, data, activitySubtype?, durationMs?, tokenCount?)` - Log an activity
- `logToolCall(sessionId, toolCall)` - Log tool usage with complete schema
- `logDecision(sessionId, decision)` - Log AI decision with reasoning

#### File Tracking & Security (Epic 4)
- `logFileRead(sessionId, operationData)` - Track file read operations
- `logFileWrite(sessionId, operationData)` - Track file write operations
- `logFileDelete(sessionId, operationData)` - Track file deletion operations
- `logFileMove(sessionId, operationData)` - Track file move/rename operations
- `logFileCopy(sessionId, operationData)` - Track file copy operations
- `analyzeFileSecurity(sessionId, analysisData)` - Perform comprehensive security analysis
- `detectFileAnomalies(sessionId, detectionData)` - Detect anomalous file access patterns
- `calculateFileRiskScore(sessionId, riskData)` - Calculate comprehensive risk scores
- `logFileOperationsBatch(sessionId, operations)` - Process multiple file operations in batch

#### Session & Batch Management
- `flush()` - Manually flush batch queue
- `withSession(config, callback)` - Execute callback with session context
- `createSession(config)` - Create manual session
- `getStats()` - Get client statistics
- `close()` - Close client and cleanup

### Session Methods

- `start()` - Start the session
- `end()` - End the session
- `logActivity(type, data, ...)` - Log activity in session
- `logToolCall(toolCall)` - Log tool call in session
- `logDecision(decision)` - Log decision in session
- `logChat(role, content, metadata?)` - Convenience method for chat
- `getSessionId()` - Get session ID
- `isActive()` - Check if session is active

### Error Types

- `TraceabilityClientError` - Base error class
- `AuthenticationError` - Invalid API key
- `RateLimitError` - Rate limit exceeded
- `ValidationError` - Invalid request data
- `NetworkError` - Network connectivity issues
- `TimeoutError` - Request timeout
- `ServerError` - Server-side errors

## License

MIT