npm package: @recursorsdk/sdk
Description: Recursor SDK for Node.js
Latest version: 1.1.0

# Recursor SDK (Node.js)

Complete Node.js SDK for interacting with the Recursor API. Provides authentication, project management, real-time updates via WebSocket, and full access to all platform features.

## Installation

```bash
npm install @recursorsdk/sdk
```


## Quick Start

### Basic Usage

```typescript
import { RecursorSDK } from "@recursorsdk/sdk";

const sdk = new RecursorSDK({
  baseUrl: "https://api.recursor.dev/api/v1",
});

// Check health
const healthy = await sdk.checkHealth();
console.log("API is healthy:", healthy);
```

### Authentication

```typescript
// Register a new user
const user = await sdk.register({
  email: "user@example.com",
  password: "SecurePass123",
  username: "johndoe",
  full_name: "John Doe",
});

// Login
const { access_token } = await sdk.login({
  email: "user@example.com",
  password: "SecurePass123",
});
// Access token is automatically set for future requests

// Get user profile
const profile = await sdk.getProfile();
console.log("User:", profile.email);

// Update profile
const updated = await sdk.updateProfile({
  full_name: "John Smith",
});

// Change password
await sdk.changePassword({
  current_password: "SecurePass123",
  new_password: "NewSecurePass456",
});
```

### Project Management

```typescript
// Create a project
const project = await sdk.createProject({
  name: "My Project",
  description: "Project description",
});

// Get project
const projectDetails = await sdk.getProject(project.id);

// List projects
const projects = await sdk.listProjects();

// Get MCP configuration
const mcpConfig = await sdk.getMcpConfig(project.id);
console.log("MCP Config:", mcpConfig);

// Regenerate API key
const { api_key } = await sdk.regenerateProjectApiKey(project.id);

// Update project
const updated = await sdk.updateProject(project.id, {
  name: "Updated Project Name",
  description: "New description",
});

// Delete project
await sdk.deleteProject(project.id);
```

### Corrections

```typescript
// Create correction
const correction = await sdk.createCorrection({
  input_text: "incorrect code",
  output_text: "correct code",
  expected_output: "correct code",
  context: { explanation: "Fix bug" },
  correction_type: "bug",
});

// List corrections
const { corrections, total } = await sdk.listCorrections({
  page: 1,
  page_size: 50,
});

// Search corrections
const results = await sdk.searchCorrections("authentication", 10);

// Get correction
const correctionDetails = await sdk.getCorrection(correction.id);

// Update correction
const updated = await sdk.updateCorrection(correction.id, {
  context: { explanation: "Updated explanation" },
});

// Get statistics
const stats = await sdk.getCorrectionStats();
```

### Code Intelligence

```typescript
// Detect intent
const intent = await sdk.detectIntent({
  user_request: "Add error handling to login",
  current_file: "auth.ts",
  tags: ["error-handling"],
});

// Get intent history
const history = await sdk.getIntentHistory(50);

// Correct code
const result = await sdk.correctCode(
  "def func(): pass",
  "python"
);

// Get analytics
const dashboard = await sdk.getAnalyticsDashboard("user-123", "30d");
const timeSaved = await sdk.getTimeSaved("user-123", "30d");
const quality = await sdk.getQualityMetrics("user-123", "30d");
```

### Billing & Usage

```typescript
// Get current usage
const usage = await sdk.getUsage();
console.log("API Calls:", usage.api_calls.used, "/", usage.api_calls.limit);

// Get usage history
const history = await sdk.getUsageHistory(30, "api_call");

// List billing plans
const plans = await sdk.listBillingPlans();

// Get subscription
const subscription = await sdk.getSubscription();
```

### Notifications

```typescript
// List notifications
const notifications = await sdk.listNotifications();

// Mark as read
await sdk.markNotificationAsRead("notification-123");

// Mark all as read
await sdk.markAllNotificationsAsRead();

// Delete notification
await sdk.deleteNotification("notification-123");
```

### Settings

```typescript
// Get settings
const settings = await sdk.getSettings();

// Update account
await sdk.updateAccount({
  full_name: "John Smith",
  email: "newemail@example.com",
});

// Update preferences
await sdk.updatePreferences({
  theme: "dark",
  notifications: true,
});

// Get guidelines
const guidelines = await sdk.getGuidelines();
```

### WebSocket (Real-time Updates)

```typescript
import { RecursorSDK, RecursorWebSocket } from "@recursorsdk/sdk";

// Login first to get access token
await sdk.login({ email: "user@example.com", password: "password" });

// Create WebSocket connection
const ws = await sdk.connectWebSocket();

// Subscribe to events
ws.on("connected", (data) => {
  console.log("WebSocket connected:", data);
});

ws.on("notification.new", (notification) => {
  console.log("New notification:", notification);
});

ws.on("usage.updated", (usage) => {
  console.log("Usage updated:", usage);
});

ws.on("activity.new", (activity) => {
  console.log("New activity:", activity);
});

// Send ping (automatic, but can be manual)
ws.send({ type: "ping" });

// Disconnect when done
sdk.disconnectWebSocket();
```

### Gateway Endpoints

```typescript
// LLM Gateway
const policy = await sdk.getLLMGatewayPolicy();
const chatResponse = await sdk.gatewayChat({
  provider: "openai",
  model: "gpt-4",
  messages: [
    { role: "user", content: "Hello!" }
  ],
  call_provider: true,
});

// Robotics Gateway
const roboticsPolicy = await sdk.getRoboticsGatewayPolicy();
const roboticsResult = await sdk.roboticsGatewayObserve({
  state: { position: [0, 0, 0] },
  command: { action: "move" },
});

// AV Gateway
const avPolicy = await sdk.getAvGatewayPolicy();
const avResult = await sdk.avGatewayObserve({
  sensors: { camera: "data" },
  state: { speed: 60 },
  action: { brake: false },
  timestamp: Date.now(),
  timestamp: Date.now(),
  vehicle_id: "vehicle-123",
});
```

## Offline & Self-Reliant Features

Recursor is designed to be resilient. The SDK includes logic to handle offline states:

1.  **Local Indexing First**: `client.syncFile()` indexes files locally before attempting cloud sync.
2.  **Offline Queue**: If the network is down or API key is invalid, events are queued locally instead of crashing.

### Auto-Ingestion
To bootstrap a project with local indexing capabilities (No API Key required), run:

```bash
npx @recursorsdk/sdk init-ingestion
```

This generates `ingest-codebase.mts` in your project root, pre-configured to:
- Crawl your codebase.
- Populate the local Recursor index.

## Environment Variables

- `RECURSOR_API_URL` - API base URL (default: `http://localhost:8000/api/v1`)
- `RECURSOR_API_KEY` - API key for authentication
- `RECURSOR_ACCESS_TOKEN` - Access token for authentication

## API Reference

### Authentication Methods
- `register(userData)` - Register new user
- `login(credentials)` - Login and get access token
- `logout()` - Logout current user
- `refreshToken(refreshToken)` - Refresh access token
- `getProfile()` - Get user profile
- `updateProfile(updates)` - Update user profile
- `changePassword(passwordChange)` - Change password
- `generateApiKey()` - Generate API key
- `revokeApiKey()` - Revoke API key
- `getPasswordRequirements()` - Get password requirements

### Project Methods
- `createProject(projectData)` - Create project
- `getProject(projectId)` - Get project
- `listProjects()` - List projects
- `updateProject(projectId, updates)` - Update project
- `deleteProject(projectId)` - Delete project
- `regenerateProjectApiKey(projectId)` - Regenerate API key
- `getMcpConfig(projectId)` - Get MCP configuration
- `getMcpStats(projectId)` - Get MCP statistics


### Correction Methods
- `createCorrection(correctionData)` - Create correction
- `listCorrections(options?)` - List corrections
- `searchCorrections(query, limit)` - Search corrections
- `getCorrection(correctionId)` - Get correction
- `updateCorrection(correctionId, updates)` - Update correction
- `getCorrectionStats()` - Get statistics

### Code Intelligence Methods
- `detectIntent(args)` - Detect intent
- `getIntentHistory(limit, projectId?)` - Get intent history
- `correctCode(code, language, projectProfile?)` - Correct code
- `correctConfig(config, configType)` - Correct config
- `correctDocumentation(markdown, docType)` - Correct documentation
- `applyAutoCorrections(userId, modelName, corrections)` - Apply auto corrections
- `getTrustScore(userId, modelName)` - Get trust score
- `submitFeedback(predictionId, accepted)` - Submit feedback
- `getAutoCorrectStats(userId)` - Get auto correction stats
- `getPatterns(userId?)` - Get patterns
- `getAnalyticsDashboard(userId, period, projectId?)` - Get analytics dashboard
- `getTimeSaved(userId, period, projectId?)` - Get time saved metrics
- `getQualityMetrics(userId, period, projectId?)` - Get quality metrics
- `getAIAgentMetrics(userId, projectId?)` - Get AI agent metrics

### Billing Methods
- `getUsage()` - Get current usage
- `getUsageHistory(days, resourceType?)` - Get usage history
- `listBillingPlans()` - List billing plans
- `getSubscription()` - Get subscription

### Notification Methods
- `listNotifications()` - List notifications
- `markNotificationAsRead(notificationId)` - Mark as read
- `markAllNotificationsAsRead()` - Mark all as read
- `deleteNotification(notificationId)` - Delete notification

### Settings Methods
- `getSettings()` - Get settings
- `updateAccount(updates)` - Update account
- `updatePreferences(preferences)` - Update preferences
- `getGuidelines()` - Get guidelines
- `changePasswordViaSettings(passwordChange)` - Change password
- `deleteAccount(confirm)` - Delete account

### Activity Methods
- `listActivityLogs(page, pageSize)` - List activity logs
- `exportActivityLogs()` - Export activity logs

### WebSocket Methods
- `createWebSocket()` - Create WebSocket client
- `connectWebSocket()` - Connect WebSocket
- `disconnectWebSocket()` - Disconnect WebSocket

## Error Handling

The SDK throws errors for failed requests:

```typescript
try {
  await sdk.login({ email: "wrong", password: "wrong" });
} catch (error) {
  console.error("Login failed:", error.message);
  // Error: HTTP 401: Incorrect email or password
}
```

## TypeScript Support

Full TypeScript support with type definitions included. All methods are typed with proper interfaces.

## License

MIT License. See `LICENSE` file.