You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

@cognitora/sdk

Package Overview
Dependencies
Maintainers
0
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cognitora/sdk

Official JavaScript/TypeScript SDK for Cognitora - Operating System for Autonomous AI Agents

1.6.0
latest
Source
npmnpm
Version published
Weekly downloads
164
17.14%
Maintainers
0
Weekly downloads
 
Created
Source

Cognitora JavaScript/TypeScript SDK

The official JavaScript/TypeScript SDK for Cognitora - Operating System for Autonomous AI Agents.

Features

  • Code Interpreter: Execute Python, JavaScript, and Bash code in secure sandboxed environments
  • Containers Platform: Run containerized workloads with flexible resource allocation
  • Session Management: Persistent sessions with state management and automatic cleanup
  • Execution Control: Start, monitor, and cancel long-running compute tasks
  • File Operations: Upload and manipulate files in execution environments
  • Networking Control: Optional internet access with security-focused defaults
  • Full TypeScript Support: Complete type definitions for excellent developer experience
  • Promise-based API: Modern async/await support
  • Error Handling: Comprehensive error types and handling

Installation

# npm
npm install @cognitora/sdk

# yarn
yarn add @cognitora/sdk

# pnpm
pnpm add @cognitora/sdk

Quick Start

import { Cognitora } from '@cognitora/sdk';

// Initialize the client
const client = new Cognitora({
  apiKey: 'your_api_key_here'
});

// Execute Python code with networking
const result = await client.codeInterpreter.execute({
  code: "print('Hello from Cognitora!')",
  language: 'python',
  networking: true  // Enable internet access (default for code interpreter)
});

console.log(`Status: ${result.data.status}`);
result.data.outputs.forEach(output => {
  console.log(`${output.type}: ${output.data}`);
});

Authentication

Get your API key from the Cognitora Dashboard:

// Method 1: Pass directly
const client = new Cognitora({
  apiKey: 'cgk_1234567890abcdef'
});

// Method 2: Environment variable
const client = new Cognitora({
  apiKey: process.env.COGNITORA_API_KEY!
});

// Method 3: With custom configuration
const client = new Cognitora({
  apiKey: 'your_api_key',
  baseURL: 'https://api.cognitora.dev',  // Production default
  timeout: 30000
});

Code Interpreter

Basic Execution with Networking Control

// Execute Python code with internet access (default)
const result = await client.codeInterpreter.execute({
  code: `
import requests
import numpy as np
import matplotlib.pyplot as plt

# Fetch data from API (requires networking)
response = requests.get('https://api.github.com/repos/microsoft/typescript')
repo_data = response.json()

print(f"Repository: {repo_data['name']}")
print(f"Stars: {repo_data['stargazers_count']}")

# Create visualization
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.title('Sine Wave')
plt.show()
`,
  language: 'python',
  networking: true  // Explicitly enable networking (default for code interpreter)
});

// Execute code without internet access for security
const secureResult = await client.codeInterpreter.execute({
  code: `
import numpy as np
# No external requests - isolated execution
data = np.random.randn(1000)
print(f"Mean: {np.mean(data)}")
`,
  language: 'python',
  networking: false  // Disable networking for secure execution
});

Session Persistence

Sessions maintain state between executions, making them perfect for:

  • Interactive data analysis workflows
  • Long-running machine learning experiments
  • Multi-step data processing pipelines
  • Collaborative coding environments
// Create a persistent session
const session = await client.codeInterpreter.createSession({
  language: 'python',
  timeout_minutes: 60,
  resources: {
    cpu_cores: 2,
    memory_mb: 2048,
    storage_gb: 10
  }
});

console.log(`Session created: ${session.data.session_id}`);

// Execute code in session (variables persist)
const result1 = await client.codeInterpreter.execute({
  code: "x = 42; y = 'Hello World'; import pandas as pd",
  session_id: session.data.session_id,
  networking: true  // Enable networking for package installs
});

const result2 = await client.codeInterpreter.execute({
  code: "print(f'x = {x}, y = {y}'); print(f'Pandas version: {pd.__version__}')",
  session_id: session.data.session_id
});

// Variables and imports are maintained across executions
console.log(result2.data.outputs[0].data); // Output: x = 42, y = Hello World

// Get session execution history
const sessionExecutions = await client.codeInterpreter.getSessionExecutions(session.data.session_id);
console.log(`Session has ${sessionExecutions.executions.length} executions`);

// Always clean up sessions when done
await client.codeInterpreter.deleteSession(session.data.session_id);

New Execution Management Features

// List all interpreter executions across all sessions
const allExecutions = await client.codeInterpreter.listAllExecutions({
  limit: 20,
  status: 'completed'
});

console.log(`Found ${allExecutions.executions.length} completed executions`);

// Get specific execution details
const executionDetails = await client.codeInterpreter.getExecution('exec_123456');
console.log(`Execution status: ${executionDetails.status}`);

// Get executions for a specific session
const sessionExecutions = await client.codeInterpreter.getSessionExecutions(
  'session_123456',
  { limit: 10 }
);

Containers Platform

The Containers Platform allows you to run containerized workloads with full execution control and networking security.

Basic Container Execution

// Run a secure container (isolated by default)
const execution = await client.containers.createContainer({
  image: 'docker.io/library/python:latest',
  command: ['python', '-c', "print('Hello from secure container!')"],
  cpu_cores: 1.0,
  memory_mb: 512,
  max_cost_credits: 5,
  networking: false  // Default: isolated for security
});

console.log(`Container ID: ${execution.id}`);
console.log(`Status: ${execution.status}`);

// Run container with internet access when needed
const networkingExecution = await client.containers.createContainer({
  image: 'docker.io/library/node:18',
  command: ['node', '-e', `
    const https = require('https');
    https.get('https://api.github.com/users/octocat', (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => console.log(JSON.parse(data).name));
    });
  `],
  cpu_cores: 1.0,
  memory_mb: 512,
  max_cost_credits: 10,
  networking: true  // Enable networking for API calls
});

Advanced Container Management

// List all container executions
const containerExecutions = await client.containers.listAllContainerExecutions({
  limit: 50,
  status: 'running'
});

console.log(`Active containers: ${containerExecutions.executions.length}`);

// Get specific container execution details
const containerExecution = await client.containers.getContainerExecution('exec_123456');
console.log(`Container execution: ${containerExecution.status}`);

// Get executions for a specific container
const containerHistory = await client.containers.getContainerExecutions('container_123456');
console.log(`Container has ${containerHistory.executions.length} executions`);

Execution Control & Cancellation

// Run a long-running task with networking control
const execution = await client.containers.createContainer({
  image: 'docker.io/library/python:latest',
  command: ['python', '-c', `
import time
import requests

for i in range(100):
    print(f'Processing step {i+1}/100')
    
    # Make API call every 10 steps (requires networking)
    if i % 10 == 0:
        try:
            response = requests.get('https://httpbin.org/delay/1')
            print(f'API call {i//10 + 1} completed')
        except Exception as e:
            print(f'Network error: {e}')
    
    time.sleep(2)
print('Processing complete!')
`],
  cpu_cores: 2.0,
  memory_mb: 1024,
  max_cost_credits: 50,
  timeout_seconds: 3600,
  networking: true  // Enable networking for API calls
});

console.log(`Started container: ${execution.id}`);

try {
  // Wait for completion with timeout
  const completed = await client.containers.waitForCompletion(
    execution.id,
    30000,  // 30 seconds timeout for demo
    2000    // Poll every 2 seconds
  );
  console.log(`Container completed: ${completed.status}`);
  
} catch (error) {
  console.log('Container taking too long, cancelling...');
  
  // Cancel the container
  const result = await client.containers.cancelContainer(execution.id);
  console.log(`Cancellation result:`, result);
  
  // Verify cancellation
  const cancelledContainer = await client.containers.getContainer(execution.id);
  console.log(`Final status: ${cancelledContainer.status}`);
}

API Reference

CodeInterpreter Class

Methods

  • execute(request: ExecuteCodeRequest): Promise<ExecuteCodeResponse> - Execute code with networking control
  • createSession(request?: CreateSessionRequest): Promise<{ data: Session }> - Create persistent session
  • listSessions(): Promise<{ data: { sessions: Session[] } }> - List active sessions
  • getSession(sessionId: string): Promise<{ data: SessionDetails }> - Get session details
  • deleteSession(sessionId: string): Promise<{ message: string }> - Delete session
  • getSessionLogs(sessionId: string, options?: SessionLogsOptions): Promise<{ data: { logs: any[]; pagination: any } }> - Get session logs
  • listAllExecutions(options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }> - NEW: List all interpreter executions
  • getExecution(executionId: string): Promise<any> - NEW: Get specific execution details
  • getSessionExecutions(sessionId: string, options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }> - NEW: List executions for specific session
  • runPython(code: string, sessionId?: string): Promise<ExecuteCodeResponse> - Execute Python code
  • runJavaScript(code: string, sessionId?: string): Promise<ExecuteCodeResponse> - Execute JavaScript code
  • runBash(command: string, sessionId?: string): Promise<ExecuteCodeResponse> - Execute bash command
  • runWithFiles(code: string, files: FileUpload[], language?, sessionId?): Promise<ExecuteCodeResponse> - Execute with files
  • createDataScienceSession(timeoutMinutes?: number): Promise<{ data: Session }> - Create data science session
  • streamExecution(request: ExecuteCodeRequest): AsyncGenerator<ExecuteCodeOutput> - Stream execution outputs

Containers Class

Methods

  • createContainer(request: ComputeExecutionRequest): Promise<Execution> - Create container with networking control
  • listContainers(options?: ListExecutionsOptions): Promise<{ executions: Execution[]; pagination: any }> - List containers
  • getContainer(containerId: string): Promise<Execution> - Get container details
  • cancelContainer(containerId: string): Promise<{ message: string }> - Cancel container
  • getContainerLogs(containerId: string): Promise<{ logs: string }> - Get container logs
  • getContainerExecutions(containerId: string): Promise<{ executions: any[] }> - Get container executions
  • listAllContainerExecutions(options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }> - NEW: List all container executions
  • getContainerExecution(executionId: string): Promise<any> - NEW: Get specific container execution details
  • estimateCost(request: CostEstimateRequest): Promise<CostEstimate> - Estimate execution cost
  • waitForCompletion(containerId: string, timeoutMs?, pollIntervalMs?): Promise<Execution> - Wait for completion
  • runAndWait(request: ComputeExecutionRequest, timeoutMs?): Promise<{ execution: Execution; logs: string }> - Create and wait

Interface Updates

// Updated interfaces with networking support
interface ExecuteCodeRequest {
  code: string;
  language?: 'python' | 'javascript' | 'bash';
  session_id?: string;
  files?: FileUpload[];
  timeout_seconds?: number;
  environment?: Record<string, string>;
  networking?: boolean;  // NEW: Control internet access
}

interface ComputeExecutionRequest {
  image: string;
  command: string[];
  cpu_cores: number;
  memory_mb: number;
  max_cost_credits: number;
  environment?: Record<string, string>;
  timeout_seconds?: number;
  storage_gb?: number;
  gpu_count?: number;
  networking?: boolean;  // NEW: Control internet access
}

Security & Networking

Default Networking Behavior

ServiceDefault NetworkingSecurity Rationale
Code Interpretertrue (enabled)Needs package installs, data fetching
Containersfalse (disabled)Security-first: isolated by default

Networking Best Practices

// For data analysis that needs external data
const dataAnalysis = await client.codeInterpreter.execute({
  code: `
import pandas as pd
import requests

# Fetch external data
response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
data = response.json()
print(f"Bitcoin price: {data['bpi']['USD']['rate']}")
`,
  networking: true  // Required for external API calls
});

// For secure computation without external access
const secureComputation = await client.containers.createContainer({
  image: 'docker.io/library/python:3.11',
  command: ['python', '-c', 'print("Secure isolated computation")'],
  cpu_cores: 1.0,
  memory_mb: 512,
  max_cost_credits: 5,
  networking: false  // Isolated execution (default)
});

// For containers that need external resources
const dataProcessing = await client.containers.createContainer({
  image: 'docker.io/library/node:18',
  command: ['npm', 'install', 'lodash', '&&', 'node', 'process.js'],
  cpu_cores: 2.0,
  memory_mb: 1024,
  max_cost_credits: 20,
  networking: true  // Enable for npm install and external APIs
});

Recent Updates

API Refactor Alignment

  • Updated endpoint paths: Code interpreter now uses /api/v1/interpreter/*
  • Container-focused architecture: All compute operations use /api/v1/compute/containers/*
  • Networking parameter: Security-focused networking control for all operations
  • New execution endpoints: Comprehensive execution management and history
  • Production-ready defaults: All clients default to https://api.cognitora.dev

New Features

  • Networking Control: Optional networking parameter with security-focused defaults
  • Execution Management: List, filter, and retrieve execution details across all services
  • Session History: Track and manage executions within persistent sessions
  • Container Execution History: Detailed tracking of container execution lifecycle

Breaking Changes from Previous Versions

  • Method Names: compute.* methods renamed to containers.*
  • Endpoint Paths: Code interpreter paths changed from /code-interpreter/ to /interpreter/
  • Default Networking: Containers now default to networking: false for security

Support

License

MIT License - see LICENSE file for details.

Keywords

cognitora

FAQs

Package last updated on 03 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.