TABLE OF CONTENTS

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, // Required
apiSecret: process.env.ASTACK_API_SECRET, // Required
sessionTtl: 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 session
const { session, token } = await sdk.createSession('user_123', {
connection_type: 'websocket',
quality: 'high', // 'standard' | 'high' | 'premium'
features: ['vision'],
metadata: { source: 'web' },
});
// Generate a client token
const sessionToken = await sdk.generateSessionToken(session.id);
// Validate a token
const { sessionId, isValid } = await sdk.validateSessionToken(sessionToken);
// Refresh a token
const newToken = await sdk.refreshSessionToken(sessionToken);
// Get session details
const session = await sdk.getSession(sessionId);
// List user sessions
const sessions = await sdk.listUserSessions('user_123', 10, 0);
// Terminate a session
await 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 operations
const 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 user
const { 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 keys
const keys = await sdk.listApiKeys('user_123');
await sdk.revokeApiKey('user_123', apiKey.id);

BILLING

// Usage tracking
const usage = await sdk.getUserUsage('user_123', {
start: new Date('2026-01-01'),
end: new Date('2026-02-01'),
});
// Cost estimation
const estimate = await sdk.estimateSessionCost({
quality: 'premium',
features: ['vision'],
duration: 300,
});
// Billing info
const billing = await sdk.getBillingInfo('user_123');
// Invoice generation
const invoice = await sdk.generateInvoice('user_123', {
start: new Date('2026-01-01'),
end: new Date('2026-02-01'),
});
// Usage alerts
const alertId = await sdk.setUsageAlert(
'user_123',
'credit_threshold',
100,
(alert) => console.log('Low credits:', alert.message)
);
// Usage projection
const projection = await sdk.calculateUsageProjection('user_123', 30);

WORKERS

// Worker status
const worker = await sdk.getWorkerStatus('worker_id');
// List active workers
const { workers, total } = await sdk.listActiveWorkers({
region: 'us-east-1',
status: 'active',
limit: 10,
});
// Worker metrics
const metrics = await sdk.getWorkerMetrics('worker_id', {
start: '2026-01-01T00:00:00Z',
end: '2026-02-01T00:00:00Z',
});
// Capacity overview
const capacity = await sdk.getCapacityMetrics();
// Request scaling
const 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 metrics
const 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 class
const 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 function
app.post('/webhooks/astack', createWebhookHandler(sdk, webhookSecret, {
onSessionEnded: (session) => { /* ... */ },
}));
// Option 3: Auto-setup
setupWebhooks(app, sdk, {
webhookSecret: process.env.WEBHOOK_SECRET,
endpoint: '/webhooks/astack',
handlers: { onSessionEnded: (session) => { /* ... */ } },
});

WEBHOOK EVENTS

session.startedNew session created and active
session.endedSession completed or terminated
session.errorSession encountered an error
user.createdNew user registered
user.updatedUser profile updated
usage.recordedUsage record logged
invoice.createdNew invoice generated

MIDDLEWARE

EXPRESS

import {
authMiddleware, rateLimitMiddleware, corsMiddleware, errorHandler
} from '@aether-stack-dev/developer-sdk';
// Authentication — validates API key or JWT
app.use('/api', authMiddleware(sdk, {
apiKeyHeader: 'x-api-key',
requirePermissions: ['session_create'],
}));
// Rate limiting
app.use(rateLimitMiddleware({
windowMs: 60_000,
max: 100,
}));
// CORS
app.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 missing
INVALID_SESSION_TOKENSession token is invalid
SESSION_NOT_FOUNDSession does not exist
SESSION_LIMIT_EXCEEDEDMax concurrent sessions reached
INSUFFICIENT_CREDITSAccount has no remaining credits
CUSTOMER_NOT_FOUNDCustomer record not found
CUSTOMER_INACTIVECustomer account is deactivated
API_KEY_EXPIREDAPI key has expired
RATE_LIMIT_EXCEEDEDToo many requests
PERMISSION_DENIEDMissing required scope
WEBHOOK_VERIFICATION_FAILEDWebhook signature mismatch
WEBSOCKET_CONNECTION_FAILEDWebSocket connection failed