@cadraos/sdk
v0.1.11-test
Published
Official SDK for CadraOS platform - programmatic access to agents, skills, tools, and artifacts
Downloads
1,183
Maintainers
Readme
@cadraos/sdk
Official SDK for the CadraOS platform - programmatic access to agents, skills, tools, and artifacts.
Note: For React chat components, use the new @cadraos/react package. The
@cadraos/sdk/chatsubpath is deprecated.
Deprecation Notice
The @cadraos/sdk/chat subpath is deprecated and will be removed in a future version.
If you're using React chat components, please migrate to @cadraos/react:
// Before (deprecated)
import { AgentChat, ChatConfigProvider } from '@cadraos/sdk/chat';
import '@cadraos/sdk/chat/styles.css';
// After (recommended)
import '@cadraos/react/styles.css';
import { CadraCopilot } from '@cadraos/react';
function App() {
return (
<CadraCopilot
apiKey="cdr_live_xxx"
orgId={123}
agentId="agent-uuid"
/>
);
}For full migration instructions, see the migration guide.
Installation
npm install @cadraos/sdk
# or
pnpm add @cadraos/sdk
# or
yarn add @cadraos/sdkQuick Start
import { CadraClient } from '@cadraos/sdk';
// Initialize the client
const client = new CadraClient({
apiKey: process.env.CADRA_API_KEY!, // e.g., cdr_live_xxx
orgId: Number(process.env.CADRA_ORG_ID),
});
// List available agents
const { data: agents } = await client.agents.list();
console.log('Available agents:', agents.map(a => a.name));
// Execute an agent
const execution = await client.agents.executeSync(agents[0].uuid, {
task: 'Summarize the latest news about AI',
});
console.log('Result:', execution.output);Note:
AISaaSClientis deprecated but still works as an alias forCadraClient.
Authentication
The SDK supports three authentication methods:
API Key (recommended for server-side)
const client = new AISaaSClient({
apiKey: 'sk_...',
orgId: 123,
});OAuth Token
const client = new AISaaSClient({
token: 'eyJ...',
orgId: 123,
});Token Provider (for automatic refresh)
const client = new AISaaSClient({
tokenProvider: async () => myAuth.getAccessToken(),
orgId: 123,
});API Reference
Agents
// List agents
const { data: agents, pagination } = await client.agents.list({
limit: 10,
status: 'active',
});
// Get agent details
const agent = await client.agents.get('agent-uuid');
// Execute (async - returns immediately)
const { executionId, status } = await client.agents.execute('agent-uuid', {
task: 'Your task here',
context: { key: 'value' },
});
// Execute (sync - waits for completion)
const execution = await client.agents.executeSync('agent-uuid', {
task: 'Your task here',
});
// Stream execution (real-time events)
const stream = await client.agents.stream('agent-uuid', {
task: 'Research a topic',
});
stream.on('log', (log) => console.log(log.title));
stream.on('toolCall', ({ toolName }) => console.log(`Calling: ${toolName}`));
stream.on('complete', ({ execution }) => console.log(execution.output));
const result = await stream.wait();
// Get execution result
const execution = await client.agents.getExecution('execution-uuid');
// Update agent
const updated = await client.agents.update('agent-uuid', {
name: 'New Name',
description: 'New description',
});
// Cancel execution
await client.agents.cancelExecution('execution-uuid');Skills
// List skills
const { data: skills } = await client.skills.list({
category: 'writing',
tags: ['seo', 'blog'],
});
// Get skill with prompt template
const skill = await client.skills.get('skill-uuid');
console.log(skill.promptTemplate);
// Get skill tools
const tools = await client.skills.getTools('skill-uuid');
// Execute skill
const result = await client.skills.execute('skill-uuid', {
variables: {
topic: 'AI in healthcare',
tone: 'professional',
},
});
// Update skill
await client.skills.update('skill-uuid', {
name: 'Updated Name',
tags: ['new-tag'],
});
// Update prompt template
await client.skills.updatePrompt('skill-uuid', 'New prompt template...');Tools
// List tools
const { data: tools } = await client.tools.list({
category: 'data',
isEnabled: true,
});
// Get tool with schema
const tool = await client.tools.get('tool-uuid');
console.log(tool.inputSchema);
// Execute tool
const result = await client.tools.execute('tool-uuid', {
query: 'weather in London',
limit: 5,
});
// Validate input
const validation = await client.tools.validateInput('tool-uuid', {
query: 'test',
});
if (!validation.valid) {
console.log(validation.errors);
}
// Update tool
await client.tools.update('tool-uuid', {
name: 'Updated Name',
});
// Update config
await client.tools.updateConfig('tool-uuid', {
isEnabled: false,
});Artifacts
// List artifacts for an execution
const { data: artifacts } = await client.artifacts.list('execution-uuid', {
type: 'file',
});
// Get artifact metadata
const artifact = await client.artifacts.get('artifact-uuid');
// Download artifact
const content = await client.artifacts.download('artifact-uuid');
// Node.js: Buffer | Browser: Blob
// Download as stream
const stream = await client.artifacts.downloadStream('artifact-uuid');
// Get signed URL
const { url, expiresAt } = await client.artifacts.getSignedUrl('artifact-uuid', {
expiresIn: 3600, // 1 hour
});
// Upload artifact
const artifact = await client.artifacts.upload('execution-uuid', {
name: 'report.pdf',
content: fileBuffer,
mimeType: 'application/pdf',
});
// Delete artifact
await client.artifacts.delete('artifact-uuid');Sessions
// Create session
const session = await client.sessions.create({
agentUuid: 'agent-uuid',
systemMessage: 'You are a helpful assistant.',
});
// List sessions
const { data: sessions } = await client.sessions.list({
agentUuid: 'agent-uuid',
});
// Get session
const session = await client.sessions.get('session-id');
// Send message (async)
const { executionId } = await client.sessions.sendMessage('session-id', {
message: 'What is the capital of France?',
});
// Send message (sync)
const execution = await client.sessions.sendMessageSync('session-id', {
message: 'Tell me more about that',
});
// Stream message
const stream = await client.sessions.stream('session-id', {
message: 'Explain in detail',
});
const result = await stream.wait();
// Get history
const history = await client.sessions.getHistory('session-id');
history.messages.forEach(msg => {
console.log(`${msg.role}: ${msg.content}`);
});
// Delete session
await client.sessions.delete('session-id');Streaming
The SDK supports real-time streaming for agent executions:
const stream = await client.agents.stream('agent-uuid', {
task: 'Research climate change and provide a summary',
});
// Register event handlers
stream.on('log', (log) => {
console.log(`[${log.type}] ${log.title}`);
if (log.content) console.log(log.content);
});
stream.on('toolCall', ({ toolName, inputs }) => {
console.log(`Calling tool: ${toolName}`, inputs);
});
stream.on('toolResult', ({ toolName, result, durationMs }) => {
console.log(`Tool ${toolName} completed in ${durationMs}ms`);
});
stream.on('complete', ({ execution }) => {
console.log('Final output:', execution.output);
});
stream.on('error', ({ error, errorCode }) => {
console.error(`Error [${errorCode}]: ${error}`);
});
stream.on('connectionChange', ({ connected, usingFallback }) => {
if (usingFallback) {
console.log('Switched to polling fallback');
}
});
// Wait for completion
const execution = await stream.wait();
// Or cancel
stream.cancel();Error Handling
The SDK provides typed error classes for different error scenarios:
import {
AISaaSError,
AuthenticationError,
AuthorizationError,
NotFoundError,
ValidationError,
RateLimitError,
ServerError,
TimeoutError,
NetworkError,
} from '@cadraos/sdk';
try {
await client.agents.get('invalid-uuid');
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Agent not found');
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof ValidationError) {
error.errors.forEach(e => {
console.log(`${e.field}: ${e.message}`);
});
} else if (error instanceof AISaaSError) {
console.log(`Error [${error.code}]: ${error.message}`);
console.log('Request ID:', error.requestId);
}
}Configuration Options
const client = new AISaaSClient({
// Required
apiKey: 'sk_...', // or token/tokenProvider
orgId: 123,
// Optional
baseUrl: 'https://api.aisaas.com/v1', // Custom API URL
timeout: 30000, // Request timeout (ms)
maxRetries: 3, // Retry attempts
headers: { // Custom headers
'X-Custom-Header': 'value',
},
});TypeScript
The SDK is written in TypeScript and provides full type definitions:
import type {
Agent,
AgentExecution,
Skill,
Tool,
Artifact,
Session,
StreamController,
} from '@cadraos/sdk';Browser Support
The SDK works in modern browsers for non-streaming operations. Streaming (SSE) is only supported in Node.js in v1.
// Works in browser
const agents = await client.agents.list();
const execution = await client.agents.executeSync(uuid, { task: '...' });
// Node.js only (v1)
const stream = await client.agents.stream(uuid, { task: '...' });Requirements
- Node.js >= 18.0.0
- Modern browsers (Chrome, Firefox, Safari, Edge)
License
Apache-2.0
