
Security News
npm Adopts OIDC for Trusted Publishing in CI/CD Workflows
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
@cognitora/sdk
Advanced tools
Official JavaScript/TypeScript SDK for Cognitora - Operating System for Autonomous AI Agents
The official JavaScript/TypeScript SDK for Cognitora - Operating System for Autonomous AI Agents.
# npm
npm install @cognitora/sdk
# yarn
yarn add @cognitora/sdk
# pnpm
pnpm add @cognitora/sdk
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}`);
});
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
});
// 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
});
Sessions maintain state between executions, making them perfect for:
// 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);
// 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 }
);
The Containers Platform allows you to run containerized workloads with full execution control and networking security.
// 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
});
// 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`);
// 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}`);
}
execute(request: ExecuteCodeRequest): Promise<ExecuteCodeResponse>
- Execute code with networking controlcreateSession(request?: CreateSessionRequest): Promise<{ data: Session }>
- Create persistent sessionlistSessions(): Promise<{ data: { sessions: Session[] } }>
- List active sessionsgetSession(sessionId: string): Promise<{ data: SessionDetails }>
- Get session detailsdeleteSession(sessionId: string): Promise<{ message: string }>
- Delete sessiongetSessionLogs(sessionId: string, options?: SessionLogsOptions): Promise<{ data: { logs: any[]; pagination: any } }>
- Get session logslistAllExecutions(options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }>
- NEW: List all interpreter executionsgetExecution(executionId: string): Promise<any>
- NEW: Get specific execution detailsgetSessionExecutions(sessionId: string, options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }>
- NEW: List executions for specific sessionrunPython(code: string, sessionId?: string): Promise<ExecuteCodeResponse>
- Execute Python coderunJavaScript(code: string, sessionId?: string): Promise<ExecuteCodeResponse>
- Execute JavaScript coderunBash(command: string, sessionId?: string): Promise<ExecuteCodeResponse>
- Execute bash commandrunWithFiles(code: string, files: FileUpload[], language?, sessionId?): Promise<ExecuteCodeResponse>
- Execute with filescreateDataScienceSession(timeoutMinutes?: number): Promise<{ data: Session }>
- Create data science sessionstreamExecution(request: ExecuteCodeRequest): AsyncGenerator<ExecuteCodeOutput>
- Stream execution outputscreateContainer(request: ComputeExecutionRequest): Promise<Execution>
- Create container with networking controllistContainers(options?: ListExecutionsOptions): Promise<{ executions: Execution[]; pagination: any }>
- List containersgetContainer(containerId: string): Promise<Execution>
- Get container detailscancelContainer(containerId: string): Promise<{ message: string }>
- Cancel containergetContainerLogs(containerId: string): Promise<{ logs: string }>
- Get container logsgetContainerExecutions(containerId: string): Promise<{ executions: any[] }>
- Get container executionslistAllContainerExecutions(options?: ListExecutionsOptions): Promise<{ executions: any[]; pagination: any }>
- NEW: List all container executionsgetContainerExecution(executionId: string): Promise<any>
- NEW: Get specific container execution detailsestimateCost(request: CostEstimateRequest): Promise<CostEstimate>
- Estimate execution costwaitForCompletion(containerId: string, timeoutMs?, pollIntervalMs?): Promise<Execution>
- Wait for completionrunAndWait(request: ComputeExecutionRequest, timeoutMs?): Promise<{ execution: Execution; logs: string }>
- Create and wait// 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
}
Service | Default Networking | Security Rationale |
---|---|---|
Code Interpreter | true (enabled) | Needs package installs, data fetching |
Containers | false (disabled) | Security-first: isolated by default |
// 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
});
/api/v1/interpreter/*
/api/v1/compute/containers/*
https://api.cognitora.dev
networking
parameter with security-focused defaultscompute.*
methods renamed to containers.*
/code-interpreter/
to /interpreter/
networking: false
for securityMIT License - see LICENSE file for details.
FAQs
Official JavaScript/TypeScript SDK for Cognitora - Operating System for Autonomous AI Agents
The npm package @cognitora/sdk receives a total of 160 weekly downloads. As such, @cognitora/sdk popularity was classified as not popular.
We found that @cognitora/sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.
Research
/Security News
A RubyGems malware campaign used 60 malicious packages posing as automation tools to steal credentials from social media and marketing tool users.
Security News
The CNA Scorecard ranks CVE issuers by data completeness, revealing major gaps in patch info and software identifiers across thousands of vulnerabilities.