SERVER SDK
The Server SDK (@aether-stack-dev/developer-sdk) runs on your backend for session management, user management, billing, webhooks, and more.
INITIALIZATION
import { AStackSDK } from '@aether-stack-dev/developer-sdk';const sdk = new AStackSDK({apiKey: process.env.ASTACK_API_KEY, // RequiredapiSecret: process.env.ASTACK_API_SECRET, // RequiredsessionTtl: 3600, // Session TTL in seconds (default: 3600)maxConcurrentSessions: 100, // Max concurrent sessions (default: 100)enableBilling: true, // Enable billing tracking (default: true)enableAuditLogging: false, // Enable audit logs (default: false)});
SESSIONS
// Create a sessionconst { session, token } = await sdk.createSession('user_123', {connection_type: 'websocket',quality: 'high', // 'standard' | 'high' | 'premium'features: ['vision'],metadata: { source: 'web' },});// Generate a client tokenconst sessionToken = await sdk.generateSessionToken(session.id);// Validate a tokenconst { sessionId, isValid } = await sdk.validateSessionToken(sessionToken);// Refresh a tokenconst newToken = await sdk.refreshSessionToken(sessionToken);// Get session detailsconst session = await sdk.getSession(sessionId);// List user sessionsconst sessions = await sdk.listUserSessions('user_123', 10, 0);// Terminate a sessionawait sdk.terminateSession(sessionId, {quality_score: 4.5,error_count: 0,});
SESSION STATUS
PENDINGSession created, waiting for connection
ACTIVEUser connected, conversation in progress
COMPLETEDSession ended successfully
FAILEDSession ended due to error
EXPIREDSession TTL exceeded
USERS
// CRUD operationsconst user = await sdk.createUser({id: 'user_123',email: 'user@example.com',name: 'Jane Doe',plan: 'growth',initial_credits: 1000,});const user = await sdk.getUserById('user_123');const updated = await sdk.updateUser('user_123', { plan: 'enterprise' });await sdk.deleteUser('user_123');
API KEY MANAGEMENT
// Create an API key for a userconst { apiKey, key } = await sdk.createApiKey('user_123', {key_name: 'Production',permissions: {session_create: true,session_manage: true,usage_read: true,},rate_limit_per_minute: 60,rate_limit_per_hour: 1000,expires_at: new Date('2026-12-31'),});// List and revoke keysconst keys = await sdk.listApiKeys('user_123');await sdk.revokeApiKey('user_123', apiKey.id);
BILLING
// Usage trackingconst usage = await sdk.getUserUsage('user_123', {start: new Date('2026-01-01'),end: new Date('2026-02-01'),});// Cost estimationconst estimate = await sdk.estimateSessionCost({quality: 'premium',features: ['vision'],duration: 300,});// Billing infoconst billing = await sdk.getBillingInfo('user_123');// Invoice generationconst invoice = await sdk.generateInvoice('user_123', {start: new Date('2026-01-01'),end: new Date('2026-02-01'),});// Usage alertsconst alertId = await sdk.setUsageAlert('user_123','credit_threshold',100,(alert) => console.log('Low credits:', alert.message));// Usage projectionconst projection = await sdk.calculateUsageProjection('user_123', 30);
WORKERS
// Worker statusconst worker = await sdk.getWorkerStatus('worker_id');// List active workersconst { workers, total } = await sdk.listActiveWorkers({region: 'us-east-1',status: 'active',limit: 10,});// Worker metricsconst metrics = await sdk.getWorkerMetrics('worker_id', {start: '2026-01-01T00:00:00Z',end: '2026-02-01T00:00:00Z',});// Capacity overviewconst capacity = await sdk.getCapacityMetrics();// Request scalingconst response = await sdk.requestWorkerScale({action: 'scale_up',delta_workers: 2,region: 'us-east-1',reason: 'Traffic spike',});
ADMIN
SCOPED API KEYS
const key = await sdk.createApiKeyWithScopes({key_name: 'Read-only Dashboard',scopes: ['sessions:read', 'billing:read', 'workers:read'],});// Available scopes:// sessions:read, sessions:write, users:read, users:write,// billing:read, billing:write, workers:read, workers:write, admin:all
AUDIT LOGS & PERFORMANCE
// Audit logs (requires enableAuditLogging: true)const { logs, total } = await sdk.getAuditLogs({action: 'session.create',start_date: '2026-01-01',limit: 50,});// Performance metricsconst metrics = await sdk.getPerformanceMetrics({aggregation: 'day',start_date: '2026-01-01',});// Returns: avg_response_time, p95, p99, error_rate, requests_per_second
WEBHOOKS
import { WebhookManager, createWebhookHandler, setupWebhooks }from '@aether-stack-dev/developer-sdk';// Option 1: WebhookManager classconst webhooks = new WebhookManager(sdk, process.env.WEBHOOK_SECRET);webhooks.setHandlers({onSessionStarted: (session) => { /* ... */ },onSessionEnded: (session, metrics) => { /* ... */ },onSessionError: (session, error) => { /* ... */ },onUserCreated: (user) => { /* ... */ },onUsageRecorded: (usage) => { /* ... */ },onInvoiceCreated: (invoice) => { /* ... */ },});app.post('/webhooks/astack', webhooks.middleware());// Option 2: Helper functionapp.post('/webhooks/astack', createWebhookHandler(sdk, webhookSecret, {onSessionEnded: (session) => { /* ... */ },}));// Option 3: Auto-setupsetupWebhooks(app, sdk, {webhookSecret: process.env.WEBHOOK_SECRET,endpoint: '/webhooks/astack',handlers: { onSessionEnded: (session) => { /* ... */ } },});
WEBHOOK EVENTS
session.startedNew session created and activesession.endedSession completed or terminatedsession.errorSession encountered an erroruser.createdNew user registereduser.updatedUser profile updatedusage.recordedUsage record loggedinvoice.createdNew invoice generatedMIDDLEWARE
EXPRESS
import {authMiddleware, rateLimitMiddleware, corsMiddleware, errorHandler} from '@aether-stack-dev/developer-sdk';// Authentication — validates API key or JWTapp.use('/api', authMiddleware(sdk, {apiKeyHeader: 'x-api-key',requirePermissions: ['session_create'],}));// Rate limitingapp.use(rateLimitMiddleware({windowMs: 60_000,max: 100,}));// CORSapp.use(corsMiddleware(['https://app.example.com']));// Error handler (last)app.use(errorHandler());// After auth, access req.astack.customerId, req.astack.apiKey
FASTIFY PLUGIN
import { astackFastifyPlugin } from '@aether-stack-dev/developer-sdk';await fastify.register(astackFastifyPlugin, {apiKey: process.env.ASTACK_API_KEY,apiSecret: process.env.ASTACK_API_SECRET,enableAuth: true,enableRateLimit: true,rateLimitOptions: { max: 100, timeWindow: 60_000 },});// Auto-registers routes:// GET /api/astack/health// POST /api/astack/sessions// GET /api/astack/sessions/:sessionId// DELETE /api/astack/sessions/:sessionId// GET /api/astack/users/:userId// Access SDK: fastify.astack// Access auth: request.astack.customerId
ERROR CODES
INVALID_API_KEYAPI key is invalid or missingINVALID_SESSION_TOKENSession token is invalidSESSION_NOT_FOUNDSession does not existSESSION_LIMIT_EXCEEDEDMax concurrent sessions reachedINSUFFICIENT_CREDITSAccount has no remaining creditsCUSTOMER_NOT_FOUNDCustomer record not foundCUSTOMER_INACTIVECustomer account is deactivatedAPI_KEY_EXPIREDAPI key has expiredRATE_LIMIT_EXCEEDEDToo many requestsPERMISSION_DENIEDMissing required scopeWEBHOOK_VERIFICATION_FAILEDWebhook signature mismatchWEBSOCKET_CONNECTION_FAILEDWebSocket connection failed