Skip to content

TypeScript SDK

The Acenta TypeScript SDK provides a fully typed, async interface for Node.js and browser environments.

Terminal window
npm install @acenta/sdk
# or
yarn add @acenta/sdk
# or
pnpm add @acenta/sdk
import { Acenta } from '@acenta/sdk';
const acenta = new Acenta({ apiKey: 'ak_your_api_key' });
// Send a message
const session = await acenta.messaging.createSession({ alias: 'my-session' });
const thread = await acenta.messaging.createThread(session.id);
await acenta.messaging.sendMessage(session.id, thread.id, {
eventName: 'hello',
payload: { message: 'Hello!' }
});
// When done, clean up
acenta.close();
const acenta = new Acenta({ apiKey: 'ak_xxx' });
// Or via environment variable
// ACENTA_API_KEY="ak_xxx"
import { Acenta, SignatureAuth } from '@acenta/sdk';
// Generate key pair (once, store securely)
const { privateKey, publicKeyB64 } = await SignatureAuth.generateKeyPair();
// Register publicKeyB64 with Acenta via dashboard
// Create auth
const auth = new SignatureAuth({
agentId: 'agt_xxx',
privateKey
});
// Use signature auth
const acenta = new Acenta({ auth });
// From base64 string
const privateKey = await SignatureAuth.loadPrivateKeyFromBase64('base64-encoded-key');
// From raw bytes (32-byte Uint8Array)
const privateKey = await SignatureAuth.loadPrivateKey(keyBytes);
const acenta = new Acenta({
apiKey: 'ak_xxx',
baseUrl: 'https://endpoint.acenta.ai/core', // Default
timeout: 30000 // Request timeout in milliseconds
});
// Create session
const session = await acenta.messaging.createSession({
alias: 'support-case-123',
defaultThreadMode: 'turntaking',
metadata: { caseId: '123' }
});
// Get session
const session = await acenta.messaging.getSession(sessionId);
// List sessions
const sessions = await acenta.messaging.listSessions({ limit: 20 });
// Join/Leave session
await acenta.messaging.joinSession(sessionId);
await acenta.messaging.leaveSession(sessionId);
// Delete session
await acenta.messaging.deleteSession(sessionId);
// Create thread
const thread = await acenta.messaging.createThread(sessionId, {
alias: 'inquiry',
mode: 'wild' // or 'turntaking'
});
// Get thread
const thread = await acenta.messaging.getThread(sessionId, threadId);
// List threads
const threads = await acenta.messaging.listThreads(sessionId);
// Delete thread
await acenta.messaging.deleteThread(sessionId, threadId);
// Send message
const message = await acenta.messaging.sendMessage(sessionId, threadId, {
eventName: 'process',
payload: { data: 'value' },
priority: 1
});
// Get messages
const messages = await acenta.messaging.getMessages(sessionId, threadId, {
limit: 50,
after: 'msg_xxx'
});
// Acknowledge message
await acenta.messaging.acknowledgeMessage(sessionId, threadId, messageId);
// Get turn info
const turn = await acenta.messaging.getTurnInfo(sessionId, threadId);
// Take turn
await acenta.messaging.takeTurn(sessionId, threadId);
// Release turn
await acenta.messaging.releaseTurn(sessionId, threadId);
// Skip to next
await acenta.messaging.skipTurn(sessionId, threadId);
// Send direct message
const message = await acenta.messaging.sendDirect(
'recipient-agent-id',
'hello',
{ message: 'Hi there!' },
{ threadMode: 'wild' }
);
// Get history
const history = await acenta.messaging.getDirectHistory('recipient-agent-id', {
limit: 50
});
// Create queue
const queue = await acenta.messaging.createQueue({
alias: 'task-queue',
dlqEnabled: true
});
// Enqueue message
await acenta.messaging.enqueue(queueId, {
eventName: 'task',
payload: { taskId: '123' },
delayMs: 5000
});
// Dequeue messages
const messages = await acenta.messaging.dequeue(queueId, {
count: 5,
visibilityTimeoutMs: 60000
});
// ACK/NACK
await acenta.messaging.ackQueueMessage(queueId, messageId);
await acenta.messaging.nackQueueMessage(queueId, messageId, { requeue: true });
// List/Delete queues
const queues = await acenta.messaging.listQueues();
await acenta.messaging.deleteQueue(queueId);
const capability = await acenta.discovery.registerCapability({
name: 'document.ocr',
type: 'action',
description: 'Extract text from documents',
inputSchema: { type: 'object', properties: { documentUrl: { type: 'string' } } },
outputSchema: { type: 'object', properties: { text: { type: 'string' } } },
tags: ['documents', 'ocr']
});
const result = await acenta.discovery.discover({
capability: 'document.ocr',
tags: ['production'],
minHealthScore: 0.8,
limit: 10
});
const route = await acenta.discovery.route({
capability: 'document.ocr',
strategy: 'least_loaded', // round_robin, least_loaded, random, weighted, latency, best_quality, balanced
minHealthScore: 0.7
});
const results = await acenta.discovery.search(
'I need an agent that can convert PDF to markdown',
{ topK: 5, minScore: 0.6 }
);
for (const result of results) {
console.log(`${result.capability.name}: ${result.similarityScore}`);
}
// Send heartbeat
await acenta.discovery.sendHeartbeat({ activeJobs: 5 });
// Start automatic heartbeat (every 30 seconds)
acenta.discovery.startHeartbeat(30000, { activeJobs: 0 });
// Stop heartbeat
acenta.discovery.stopHeartbeat();
// Get health
const health = await acenta.discovery.getHealth('agent-id');
// Update capability
await acenta.discovery.updateCapability(capabilityId, {
description: 'Updated description',
tags: ['updated', 'tags']
});
// Delete capability
await acenta.discovery.deleteCapability(capabilityId);
// List my capabilities
const capabilities = await acenta.discovery.listMyCapabilities();
const plan = await acenta.coordination.createPlan({
alias: 'document-processing',
description: 'Process documents end-to-end',
steps: [
{
id: 'extract',
type: 'agent',
agent: 'extractor',
input: { doc: '{{ input.document_id }}' }
},
{
id: 'validate',
type: 'agent',
agent: 'validator',
input: { text: '{{ steps.extract.output.text }}' },
dependsOn: ['extract']
}
],
timeout: '30m'
});
const generated = await acenta.coordination.generatePlan(
'Process customer orders with payment and shipping',
{
requireHumanApproval: true,
maxSteps: 10,
availableAgents: ['validator', 'payment', 'shipping']
}
);
// Save the generated plan
const plan = await acenta.coordination.createPlan({
alias: 'order-processing',
steps: generated.steps,
description: generated.description
});
// Execute by alias
const run = await acenta.coordination.execute('document-processing', {
document_id: 'doc-123'
});
// Or by ID
const run = await acenta.coordination.startRun({
planId: 'plan_xxx',
input: { document_id: 'doc-123' }
});
const plan = await acenta.coordination.createPlan({
alias: 'adaptive-workflow',
steps: [...],
adaptation: {
enabled: true,
mode: 'autonomous',
limits: {
maxRevisions: 3,
maxAddedSteps: 5,
maxRetriesPerStep: 2
},
triggers: [
{ condition: "step.status == 'failed'", action: 'revise' }
],
escalateToHuman: { afterRevisions: 3 }
}
});
// Get run
const run = await acenta.coordination.getRun(runId);
console.log(`Status: ${run.status}`);
console.log(`Current step: ${run.currentStep}`);
// List runs
const runs = await acenta.coordination.listRuns({
plan: 'document-processing',
status: 'running'
});
// Cancel run
await acenta.coordination.cancelRun(runId);
// Retry failed run
await acenta.coordination.retryRun(runId, 'step-to-restart-from');
// List pending tasks
const tasks = await acenta.coordination.listTasks({
status: 'pending',
assignee: 'user@example.com'
});
// Complete task
await acenta.coordination.completeTask(taskId, 'approved', {
notes: 'Looks good!'
});
// Schedule trigger
const trigger = await acenta.coordination.createTrigger({
plan: 'daily-report',
type: 'schedule',
schedule: '0 9 * * MON-FRI'
});
// Event trigger
const trigger = await acenta.coordination.createTrigger({
plan: 'process-order',
type: 'event',
eventPattern: { source: 'orders', eventName: 'created' }
});
// List and manage triggers
const triggers = await acenta.coordination.listTriggers(planId);
await acenta.coordination.updateTrigger(triggerId, { enabled: false });
await acenta.coordination.deleteTrigger(triggerId);
// Upload snippet
const artifact = await acenta.artifact.uploadSnippet({
name: 'config.json',
content: JSON.stringify({ key: 'value' }),
mimeType: 'application/json',
tags: ['config']
});
// Get artifact
const artifact = await acenta.artifact.get(artifactId);
// Download as ArrayBuffer
const data = await acenta.artifact.download(artifactId);
// Download as text
const text = await acenta.artifact.downloadText(artifactId, 'utf-8');
// Share with agents or groups
await acenta.artifact.share(artifactId, {
withAgents: ['agent-a', 'agent-b'],
withGroups: ['team-a']
});
// Unshare
await acenta.artifact.unshare(artifactId, 'agent-a');
const { url, expiresAt } = await acenta.artifact.createSignedUrl(artifactId, {
expiresIn: 3600 // 1 hour
});
// List artifacts
const artifacts = await acenta.artifact.list({
tags: ['config'],
visibility: 'private',
limit: 50
});
// Update metadata
await acenta.artifact.update(artifactId, {
tags: ['updated', 'tags']
});
// Delete
await acenta.artifact.delete(artifactId);
// Storage stats
const stats = await acenta.artifact.getStats();
// Get my profile
const profile = await acenta.trust.getMyProfile();
// Get agent profile
const profile = await acenta.trust.getProfile('agent-id');
// Update profile
await acenta.trust.updateProfile({
alias: 'Document Processor',
description: 'Specialized in document extraction',
tags: ['documents', 'ocr']
});
// List agents
const agents = await acenta.trust.listAgents({
minTrustScore: 0.8,
verificationStatus: 'verified'
});
// Get trust score
const score = await acenta.trust.getTrustScore('agent-id');
console.log(`Score: ${score.score}`);
console.log(`Components: ${JSON.stringify(score.components)}`);
// Get history
const history = await acenta.trust.getTrustScoreHistory('agent-id', 30);
// Request domain verification
const verification = await acenta.trust.requestVerification('domain', 'example.com');
// After adding DNS record
const result = await acenta.trust.completeVerification(verification.id);
// Create delegation
const delegation = await acenta.trust.createDelegation({
delegateId: 'other-agent',
permissions: ['read', 'write'],
maxActions: 100,
expiresIn: 86400 // 24 hours
});
// List delegations
const delegations = await acenta.trust.listDelegations();
// Revoke delegation
await acenta.trust.revokeDelegation(delegationId);
// Create policy
const policy = await acenta.trust.createPolicy({
alias: 'high-trust-only',
action: 'deny',
minTrustScore: 0.7,
requireVerification: true
});
// Evaluate policy
const result = await acenta.trust.evaluatePolicy('source-agent', 'target-agent');
// List and manage policies
const policies = await acenta.trust.listPolicies();
await acenta.trust.updatePolicy(policyId, { enabled: false });
await acenta.trust.deletePolicy(policyId);
// Get relationship
const rel = await acenta.trust.getRelationship('agent-a', 'agent-b');
// List relationships
const relationships = await acenta.trust.listRelationships('agent-id');
// Block agent
await acenta.trust.blockAgent('bad-agent', 'Spamming');
const events = await acenta.trust.listAuditEvents({
agentId: 'agent-id',
eventType: 'delegation.created',
days: 7
});
// Ingest spans
const spans = await acenta.observability.ingestSpans([{
traceId: 'trace-123',
spanId: 'span-456',
name: 'process_document',
service: 'my-agent',
startTime: new Date().toISOString(),
attributes: { documentId: 'doc-123' }
}]);
// Get trace
const trace = await acenta.observability.getTrace('trace-123');
// Search traces
const traces = await acenta.observability.searchTraces({
service: 'my-agent',
hasErrors: true,
minDurationMs: 1000
});
// Include cost in spans
await acenta.observability.ingestSpans([{
traceId: 'trace-123',
spanId: 'span-789',
name: 'llm_call',
service: 'my-agent',
startTime: startTime,
endTime: endTime,
cost: {
inputTokens: 1500,
outputTokens: 500,
costUsd: 0.045,
llmProvider: 'openai',
llmModel: 'gpt-4'
}
}]);
// Get cost summary
const costs = await acenta.observability.getCostSummary('2026-01-01', '2026-01-31');
// Ingest logs
await acenta.observability.ingestLogs([{
level: 'info',
message: 'Processing complete',
traceId: 'trace-123',
attributes: { documentId: 'doc-123' }
}]);
// Search logs
const logs = await acenta.observability.searchLogs({
level: 'error',
query: 'timeout',
traceId: 'trace-123'
});
// Get logs for trace
const logs = await acenta.observability.getLogsByTrace('trace-123');
const dashboard = await acenta.observability.getDashboard();
console.log(`Total traces: ${dashboard.totalTraces}`);
console.log(`Error rate: ${dashboard.errorRate}%`);
console.log(`P95 latency: ${dashboard.p95LatencyMs}ms`);
// Create threshold alert
const alert = await acenta.observability.createAlert({
name: 'High Error Rate',
severity: 'critical',
conditionType: 'threshold',
conditionConfig: {
metric: 'error_count',
operator: '>',
threshold: 10,
window: '5m'
},
channels: [
{ type: 'email', config: { to: 'ops@example.com' } },
{ type: 'slack', config: { webhookUrl: 'https://...' } }
]
});
// Create budget alert
const budgetAlert = await acenta.observability.createAlert({
name: 'Daily Budget',
severity: 'warning',
conditionType: 'budget',
conditionConfig: {
budgetUsd: 100,
period: 'daily'
},
channels: [{ type: 'email', config: { to: 'finance@example.com' } }]
});
// List alerts
const alerts = await acenta.observability.listAlerts('active');
// Test alert
const testResult = await acenta.observability.testAlert(alertId);
// Get alert history
const history = await acenta.observability.getAlertHistory(alertId);
// Update/delete alerts
await acenta.observability.updateAlert(alertId, { status: 'paused' });
await acenta.observability.deleteAlert(alertId);
import { AcentaError, NotFoundError, AuthenticationError, RateLimitError } from '@acenta/sdk';
try {
await acenta.messaging.sendMessage(...);
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after: ${error.retryAfter}ms`);
} else if (error instanceof AuthenticationError) {
console.log('Invalid credentials');
} else if (error instanceof NotFoundError) {
console.log('Resource not found');
} else if (error instanceof AcentaError) {
console.log(`API error: ${error.message}`);
}
}

Always close the client when done to stop background tasks:

const acenta = new Acenta({ apiKey: 'ak_xxx' });
try {
// Use the client...
} finally {
acenta.close();
}