@recursorsdk/sdk
v1.1.0
Published
Recursor SDK for Node.js
Readme
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
npm install @recursorsdk/sdkQuick Start
Basic Usage
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
// Register a new user
const user = await sdk.register({
email: "[email protected]",
password: "SecurePass123",
username: "johndoe",
full_name: "John Doe",
});
// Login
const { access_token } = await sdk.login({
email: "[email protected]",
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
// 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
// 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
// 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
// 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
// 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
// Get settings
const settings = await sdk.getSettings();
// Update account
await sdk.updateAccount({
full_name: "John Smith",
email: "[email protected]",
});
// Update preferences
await sdk.updatePreferences({
theme: "dark",
notifications: true,
});
// Get guidelines
const guidelines = await sdk.getGuidelines();WebSocket (Real-time Updates)
import { RecursorSDK, RecursorWebSocket } from "@recursorsdk/sdk";
// Login first to get access token
await sdk.login({ email: "[email protected]", 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
// 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:
- Local Indexing First:
client.syncFile()indexes files locally before attempting cloud sync. - 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:
npx @recursorsdk/sdk init-ingestionThis 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 authenticationRECURSOR_ACCESS_TOKEN- Access token for authentication
API Reference
Authentication Methods
register(userData)- Register new userlogin(credentials)- Login and get access tokenlogout()- Logout current userrefreshToken(refreshToken)- Refresh access tokengetProfile()- Get user profileupdateProfile(updates)- Update user profilechangePassword(passwordChange)- Change passwordgenerateApiKey()- Generate API keyrevokeApiKey()- Revoke API keygetPasswordRequirements()- Get password requirements
Project Methods
createProject(projectData)- Create projectgetProject(projectId)- Get projectlistProjects()- List projectsupdateProject(projectId, updates)- Update projectdeleteProject(projectId)- Delete projectregenerateProjectApiKey(projectId)- Regenerate API keygetMcpConfig(projectId)- Get MCP configurationgetMcpStats(projectId)- Get MCP statistics
Correction Methods
createCorrection(correctionData)- Create correctionlistCorrections(options?)- List correctionssearchCorrections(query, limit)- Search correctionsgetCorrection(correctionId)- Get correctionupdateCorrection(correctionId, updates)- Update correctiongetCorrectionStats()- Get statistics
Code Intelligence Methods
detectIntent(args)- Detect intentgetIntentHistory(limit, projectId?)- Get intent historycorrectCode(code, language, projectProfile?)- Correct codecorrectConfig(config, configType)- Correct configcorrectDocumentation(markdown, docType)- Correct documentationapplyAutoCorrections(userId, modelName, corrections)- Apply auto correctionsgetTrustScore(userId, modelName)- Get trust scoresubmitFeedback(predictionId, accepted)- Submit feedbackgetAutoCorrectStats(userId)- Get auto correction statsgetPatterns(userId?)- Get patternsgetAnalyticsDashboard(userId, period, projectId?)- Get analytics dashboardgetTimeSaved(userId, period, projectId?)- Get time saved metricsgetQualityMetrics(userId, period, projectId?)- Get quality metricsgetAIAgentMetrics(userId, projectId?)- Get AI agent metrics
Billing Methods
getUsage()- Get current usagegetUsageHistory(days, resourceType?)- Get usage historylistBillingPlans()- List billing plansgetSubscription()- Get subscription
Notification Methods
listNotifications()- List notificationsmarkNotificationAsRead(notificationId)- Mark as readmarkAllNotificationsAsRead()- Mark all as readdeleteNotification(notificationId)- Delete notification
Settings Methods
getSettings()- Get settingsupdateAccount(updates)- Update accountupdatePreferences(preferences)- Update preferencesgetGuidelines()- Get guidelineschangePasswordViaSettings(passwordChange)- Change passworddeleteAccount(confirm)- Delete account
Activity Methods
listActivityLogs(page, pageSize)- List activity logsexportActivityLogs()- Export activity logs
WebSocket Methods
createWebSocket()- Create WebSocket clientconnectWebSocket()- Connect WebSocketdisconnectWebSocket()- Disconnect WebSocket
Error Handling
The SDK throws errors for failed requests:
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.
