Back to API Overview

JavaScript SDK Documentation

A modular TypeScript SDK for integrating human-in-the-loop API into your JavaScript/TypeScript applications.

Installation

Install the CodeVF JavaScript SDK using your preferred package manager:

npm

npm install codevf-js-sdk

yarn

yarn add codevf-js-sdk

bun

bun add codevf-js-sdk

Requirements

  • • Node.js 16+ or Bun 1.0+
  • • TypeScript 5+ (for TypeScript projects)

Quick Start

Get started with the SDK in just a few lines of code:

import { createClient, createProject, createTask } from 'codevf-js-sdk';

// Initialize the SDK with your API key
const client = createClient({
  apiKey: process.env.CODEVF_API_KEY
});

// Create a project
const project = await createProject(client, {
  name: 'My API Project',
  description: 'Project for API integration'
});

// Submit a task for human review
const task = await createTask(client, {
  prompt: 'Review this authentication system for security issues',
  projectId: project.id,
  maxCredits: 100,
  mode: 'fast'
});

console.log('Task created:', task.id);
console.log('Status:', task.status);

TypeScript Support

The SDK is written in TypeScript and provides full type definitions out of the box.

Projects

Projects help you organize and group related tasks together.

Create a Project

import { createProject } from 'codevf-js-sdk';

const project = await createProject(client, {
  name: 'Authentication System Review',
  description: 'Security audit for OAuth implementation'
});

console.log('Project ID:', project.id);
console.log('Created at:', project.createdAt);

Project Reuse

If a project with the same name already exists, the API will return the existing project instead of creating a duplicate.

Tasks

Tasks represent work submitted for human engineer review.

Create a Task

import { createTask } from 'codevf-js-sdk';

const task = await createTask(client, {
  prompt: 'Review this authentication flow for security vulnerabilities',
  projectId: project.id,
  maxCredits: 150,
  mode: 'fast', // 'realtime_answer', 'fast', or 'standard'
  metadata: {
    environment: 'production',
    priority: 'high'
  },
  attachments: [
    {
      fileName: 'auth-flow.ts',
      content: 'export function authenticate(user) { ... }',
      mimeType: 'text/typescript'
    }
  ]
});

📊 Structured Responses (New)

Get type-safe, structured JSON responses perfect for programmatic consumption. Define a JSON Schema and receive data matching your exact structure.

✅ Best for: Data extraction, code analysis results, API data generation
⚡ With realtime_answer mode: Instant AI-generated response
👨‍💻 With other modes: Engineer validates AI output
import { createTask } from 'codevf-js-sdk';

// Request structured security analysis
const task = await createTask(client, {
  prompt: 'Analyze this code for security vulnerabilities',
  projectId: project.id,
  maxCredits: 150,
  mode: 'realtime_answer',
  responseSchema: {
    type: 'object',
    properties: {
      vulnerabilities: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            severity: { 
              type: 'string', 
              enum: ['critical', 'high', 'medium', 'low'] 
            },
            description: { type: 'string' },
            location: { type: 'string' },
            recommendation: { type: 'string' }
          },
          required: ['severity', 'description']
        }
      },
      securityScore: { 
        type: 'number', 
        minimum: 0, 
        maximum: 100 
      }
    },
    required: ['vulnerabilities', 'securityScore']
  }
});

// For realtime_answer, result is immediately available
console.log('Security Score:', task.result.securityScore);
console.log('Vulnerabilities:', task.result.vulnerabilities);
// Output:
// Security Score: 75
// Vulnerabilities: [
//   { severity: 'high', description: 'SQL injection risk...', ... }
// ]

Get Task Status

import { getTask } from 'codevf-js-sdk';

const taskStatus = await getTask(client, task.id);

console.log('Status:', taskStatus.status); // pending, processing, completed, cancelled
console.log('Credits used:', taskStatus.creditsUsed);

if (taskStatus.status === 'completed') {
  console.log('Result:', taskStatus.result.message);
  console.log('Deliverables:', taskStatus.result.deliverables);
}

Cancel a Task

import { cancelTask } from 'codevf-js-sdk';

const result = await cancelTask(client, task.id);

console.log(result.message); // 'Task cancelled successfully'
console.log('Credits returned:', result.creditsReturned);

Service Modes

  • realtime_answer: Instant response (2x multiplier, 1-10 credits)
  • fast: 4-hour SLA (1.5x multiplier, 4-1920 credits)
  • standard: 24-hour SLA (1x multiplier, 4-1920 credits)

File Attachments

Attach up to 5 files per task. Supported types:

  • • Images: PNG, JPG, GIF, WebP (10MB max, base64 encoded)
  • • Documents: PDF (10MB max, base64 encoded)
  • • Source code: JS, TS, Python, etc. (1MB max, raw text)
  • • Text files: JSON, XML, CSV, logs (1MB max, raw text)

Credits

Monitor your credit balance and usage across tasks.

Check Balance

import { getBalance } from 'codevf-js-sdk';

const balance = await getBalance(client);

console.log('Available credits:', balance.available);
console.log('Credits on hold:', balance.onHold);
console.log('Total credits:', balance.total);

Credit System

Credits are held when a task starts and charged when completed. Cancelled tasks return held credits to your balance. 1 credit = 1 second of human time.

Error Handling

🎯 Rich Exception Types: All SDK errors include typed properties, helper methods, and actionable URLs for seamless error handling.

Compatible with both JavaScript and Python SDKs (Issues #118, #119)

The SDK provides typed error classes with contextual information and helper methods:

Basic Error Handling

import {
  createTask,
  InsufficientCreditsError,
  RateLimitError,
  UnauthorizedError,
  InvalidRequestError
} from 'codevf-js-sdk';

try {
  const task = await createTask(client, {
    prompt: 'Review this code',
    projectId: 123,
    maxCredits: 50,
    mode: 'fast'
  });
} catch (error) {
  if (error instanceof InsufficientCreditsError) {
    console.error(`Need ${error.needed} more credits`);
    console.error(`Purchase at: ${error.getPurchaseUrl()}`);
  } else if (error instanceof RateLimitError) {
    console.error(`Retry after ${error.retryAfter} seconds`);
    await new Promise(r => setTimeout(r, error.retryAfter * 1000));
    // Retry logic here
  } else if (error instanceof UnauthorizedError) {
    console.error(`Get API key: ${error.getApiKeyUrl()}`);
  } else if (error instanceof InvalidRequestError) {
    console.error('Validation errors:', error.details);
  }
}

Advanced Error Properties

// InsufficientCreditsError - Rich credit information
try {
  await createTask(client, params);
} catch (error) {
  if (error instanceof InsufficientCreditsError) {
    console.log('Available:', error.balance);      // e.g., 600
    console.log('Required:', error.required);       // e.g., 3000
    console.log('Needed:', error.needed);           // Computed: 2400
    console.log('Buy URL:', error.getPurchaseUrl()); // Actionable link
  }
}

// RateLimitError - Smart retry handling
try {
  await createTask(client, params);
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log('Retry After:', error.retryAfter);  // Seconds to wait
    console.log('Reset At:', error.resetAt);        // ISO timestamp
    console.log('Limit:', error.limit);             // "1 req/sec"
  }
}

// InvalidRequestError - Field-level validation
try {
  await createTask(client, params);
} catch (error) {
  if (error instanceof InvalidRequestError) {
    error.details.errors.forEach(err => {
      console.log(`Field: ${err.field}, Error: ${err.message}`);
    });
  }
}

// InternalError - Support tracking
try {
  await createTask(client, params);
} catch (error) {
  if (error instanceof InternalError) {
    console.log('Request ID:', error.requestId);
    console.log('Support:', error.getSupportUrl());
    console.log('Status:', InternalError.getStatusUrl()); // Static method
  }
}

Available Error Classes

400
InvalidRequestError
Invalid parameters or malformed request
401
UnauthorizedError
Invalid or missing API key
402
InsufficientCreditsError
Not enough credits to complete task
408
HumanTimeoutError
No engineer available or request timed out
429
RateLimitError
Rate limit exceeded (1 req/sec)
500
InternalError
Internal server error
Base
CodeVFError
Base class for all CodeVF errors

SDK Architecture

The SDK follows a modular architecture with clear separation of concerns:

  • Core - Internal HTTP client, authentication, and error handling
  • Modules - Feature domains (projects, tasks, credits, tags)
  • Types - Shared TypeScript interfaces