The Node.js SDK (@ascend/sdk) is not yet published to npm. This documentation is a preview of the planned API. For production use, please use the Python SDK or the REST API.
Node.js SDK API Reference
Complete reference for all classes, methods, and types in the ASCEND Node.js SDK v2.0.
Installation
npm install @ascend/sdk
AscendClient
The main client class for interacting with the ASCEND Platform.
Constructor
import { AscendClient, FailMode } from '@ascend/sdk';
const client = new AscendClient(options: AscendClientOptions);
AscendClientOptions
interface AscendClientOptions {
/** Organization API key (required) */
apiKey: string;
/** Unique agent identifier (required) */
agentId: string;
/** Human-readable agent name (required) */
agentName: string;
/** API endpoint URL */
apiUrl?: string;
/** Deployment environment */
environment?: string;
/** Fail mode when ASCEND is unreachable */
failMode?: FailMode;
/** Request timeout in milliseconds */
timeout?: number;
/** Maximum retry attempts */
maxRetries?: number;
/** Enable debug logging */
debug?: boolean;
/** Log level */
logLevel?: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR';
/** Use JSON format for logs */
jsonLogs?: boolean;
/** Enable metrics collection */
enableMetrics?: boolean;
/** Circuit breaker options */
circuitBreakerOptions?: CircuitBreakerOptions;
/** HMAC signing secret */
signingSecret?: string;
}
Default Values
| Option | Default |
|---|---|
apiUrl | https://pilot.owkai.app |
environment | "production" |
failMode | FailMode.CLOSED |
timeout | 30000 (30 seconds) |
maxRetries | 3 |
debug | false |
enableMetrics | true |
Methods
register()
Register this agent with the ASCEND platform.
async register(options: RegisterOptions): Promise<RegisterResponse>
RegisterOptions
interface RegisterOptions {
/** Agent type: "supervised", "autonomous", "mcp_server" */
agentType: string;
/** List of capabilities */
capabilities: string[];
/** Resources this agent can access */
allowedResources?: string[];
/** Additional metadata */
metadata?: Record<string, unknown>;
}
RegisterResponse
interface RegisterResponse {
agentId: string;
status: string;
registeredAt: string;
capabilities: string[];
metadata?: Record<string, unknown>;
}
Example
const registration = await client.register({
agentType: 'automation',
capabilities: ['database.query', 'file.read', 'api.call'],
allowedResources: ['production_db', 'customer_api'],
metadata: { version: '1.0.0', owner: 'platform-team' }
});
console.log(`Registered: ${registration.agentId}`);
evaluateAction()
Evaluate an action for authorization.
async evaluateAction(options: EvaluateActionOptions): Promise<EvaluateActionResult>
EvaluateActionOptions
interface EvaluateActionOptions {
/** Action type in "category.action" format */
actionType: string;
/** Resource identifier */
resource: string;
/** Action-specific parameters */
parameters?: Record<string, unknown>;
/** Additional context for risk scoring */
context?: Record<string, unknown>;
/** Wait for approval if pending */
waitForApproval?: boolean;
/** Approval timeout in milliseconds */
approvalTimeout?: number;
/** Override risk level */
riskLevel?: string;
/** Force human approval */
requireHumanApproval?: boolean;
}
EvaluateActionResult
interface EvaluateActionResult {
decision: Decision;
actionId: string;
reason?: string;
riskScore?: number;
policyViolations: string[];
conditions: string[];
approvalRequestId?: string;
requiredApprovers: string[];
expiresAt?: string;
metadata: Record<string, unknown>;
}
Example
const decision = await client.evaluateAction({
actionType: 'financial.refund',
resource: 'stripe_api',
parameters: {
amount: 100.00,
currency: 'USD',
customerId: 'cust_123'
},
context: {
sessionId: 'sess_abc',
userRequest: 'Process refund for order #456'
}
});
if (decision.decision === Decision.ALLOWED) {
console.log(`Action approved: ${decision.actionId}`);
} else if (decision.decision === Decision.PENDING) {
console.log(`Awaiting approval: ${decision.approvalRequestId}`);
} else {
console.log(`Denied: ${decision.reason}`);
}
logActionCompleted()
Log successful action completion.
async logActionCompleted(
actionId: string,
result?: Record<string, unknown>,
durationMs?: number
): Promise<ActionLogResponse>
Example
const startTime = Date.now();
const result = await executeQuery();
const durationMs = Date.now() - startTime;
await client.logActionCompleted(
decision.actionId,
{ rowCount: result.length },
durationMs
);
logActionFailed()
Log action failure.
async logActionFailed(
actionId: string,
error: string | Error,
durationMs?: number
): Promise<ActionLogResponse>
Example
try {
await executeQuery();
} catch (error) {
await client.logActionFailed(
decision.actionId,
error as Error,
Date.now() - startTime
);
throw error;
}
checkApproval()
Check approval status.
async checkApproval(approvalRequestId: string): Promise<ApprovalStatusResponse>
ApprovalStatusResponse
interface ApprovalStatusResponse {
approvalRequestId: string;
status: 'pending' | 'approved' | 'rejected';
approvedBy?: string;
rejectedBy?: string;
rejectionReason?: string;
decidedAt?: string;
}
Example
if (decision.decision === Decision.PENDING) {
const status = await client.checkApproval(decision.approvalRequestId!);
if (status.status === 'approved') {
await executeAction();
} else if (status.status === 'rejected') {
console.log(`Rejected: ${status.rejectionReason}`);
}
}
configureWebhook()
Configure webhook for event notifications.
async configureWebhook(options: WebhookOptions): Promise<WebhookConfigResponse>
WebhookOptions
interface WebhookOptions {
/** HTTPS endpoint URL */
url: string;
/** Events to subscribe to */
events: string[];
/** Signing secret */
secret?: string;
}
Valid Events
action.approvedaction.deniedaction.pendingpolicy.violationagent.trust_changed
Example
const config = await client.configureWebhook({
url: 'https://your-app.com/webhooks/ascend',
events: ['action.approved', 'action.denied', 'policy.violation'],
secret: 'whsec_your_secret_here'
});
console.log(`Webhook ID: ${config.webhookId}`);
testConnection()
Test API connectivity.
async testConnection(): Promise<ConnectionStatus>
ConnectionStatus
interface ConnectionStatus {
status: 'connected' | 'error';
apiVersion?: string;
latency?: number;
error?: string;
}
Example
const status = await client.testConnection();
if (status.status === 'connected') {
console.log(`Connected. Latency: ${status.latency}ms`);
} else {
console.error(`Connection error: ${status.error}`);
}
getCircuitBreakerState()
Get circuit breaker status.
getCircuitBreakerState(): { state: CircuitState; failures: number }
resetCircuitBreaker()
Reset the circuit breaker.
resetCircuitBreaker(): void
getMetrics()
Get metrics snapshot.
getMetrics(): MetricsSnapshot | null
MetricsSnapshot
interface MetricsSnapshot {
totalRequests: number;
successCount: number;
errorCount: number;
successRate: number;
avgLatency: number;
p50Latency: number;
p95Latency: number;
p99Latency: number;
requestsPerMinute: number;
retryCount: number;
timeoutCount: number;
windowStart: Date;
windowEnd: Date;
}
Enums
Decision
Authorization decision values.
enum Decision {
/** Action is allowed to proceed */
ALLOWED = 'allowed',
/** Action is denied */
DENIED = 'denied',
/** Action is pending human approval */
PENDING = 'pending'
}
FailMode
Fail mode configuration.
enum FailMode {
/** Block actions when ASCEND is unreachable */
CLOSED = 'closed',
/** Allow actions when ASCEND is unreachable */
OPEN = 'open'
}
CircuitState
Circuit breaker states.
enum CircuitState {
CLOSED = 'closed',
OPEN = 'open',
HALF_OPEN = 'half_open'
}
RiskLevel
Risk assessment levels.
enum RiskLevel {
LOW = 'low',
MEDIUM = 'medium',
HIGH = 'high',
CRITICAL = 'critical'
}
Error Classes
OWKAIError
Base error class.
class OWKAIError extends Error {
readonly code: string;
readonly details: Record<string, unknown>;
toJSON(): Record<string, unknown>;
}
AuthenticationError
Raised when authentication fails.
class AuthenticationError extends OWKAIError {
// code: 'AUTH_ERROR'
}
AuthorizationError
Raised when an action is denied.
class AuthorizationError extends OWKAIError {
readonly policyViolations: string[];
readonly riskScore?: number;
// code: 'AUTHZ_DENIED'
}
TimeoutError
Raised when an operation times out.
class TimeoutError extends OWKAIError {
readonly timeoutMs: number;
// code: 'TIMEOUT'
}
RateLimitError
Raised when rate limit is exceeded.
class RateLimitError extends OWKAIError {
readonly retryAfter: number; // seconds
// code: 'RATE_LIMIT'
}
ConnectionError
Raised when connection fails.
class ConnectionError extends OWKAIError {
// code: 'CONNECTION_ERROR'
}
CircuitBreakerOpenError
Raised when circuit breaker is open.
class CircuitBreakerOpenError extends OWKAIError {
readonly recoveryTimeSeconds: number;
// code: 'CIRCUIT_OPEN'
}
ValidationError
Raised when validation fails.
class ValidationError extends OWKAIError {
readonly fieldErrors: Record<string, string>;
// code: 'VALIDATION_ERROR'
}
CircuitBreaker
Circuit breaker for resilient API calls.
CircuitBreakerOptions
interface CircuitBreakerOptions {
/** Failures before opening circuit (default: 5) */
failureThreshold?: number;
/** Seconds before recovery attempt (default: 30) */
recoveryTimeout?: number;
/** Test requests in half-open state (default: 3) */
halfOpenMaxCalls?: number;
}
Methods
class CircuitBreaker {
getState(): CircuitState;
getFailures(): number;
recordSuccess(): void;
recordFailure(): void;
allowRequest(): boolean;
reset(): void;
}
OWKAIClient (Legacy)
Legacy client for backward compatibility.
import { OWKAIClient } from '@ascend/sdk';
const client = new OWKAIClient({
apiKey: 'your-api-key',
organizationSlug: 'your-org'
});
Legacy Methods
// Submit action (legacy)
async submitAction(action: AgentAction): Promise<AuthorizationDecision>
// Get action status
async getActionStatus(actionId: string): Promise<AuthorizationDecision>
// Wait for decision
async waitForDecision(actionId: string, timeout?: number): Promise<AuthorizationDecision>
// Get action details
async getActionDetails(actionId: string): Promise<ActionDetails>
// List actions
async listActions(options?: ListOptions): Promise<ActionListResponse>
// Approve action (admin)
async approveAction(actionId: string, comments?: string): Promise<AuthorizationDecision>
// Deny action (admin)
async denyAction(actionId: string, reason: string): Promise<AuthorizationDecision>
// Batch submission
async submitActionBatch(actions: AgentAction[], options?: BatchOptions): Promise<BatchResponse>
Type Definitions
AgentAction
interface AgentAction {
agentId: string;
agentName: string;
actionType: ActionType | string;
resource: string;
resourceId?: string;
details?: Record<string, unknown>;
context?: ActionContext;
riskIndicators?: RiskIndicators;
}
RiskIndicators
interface RiskIndicators {
piiInvolved?: boolean;
financialData?: boolean;
externalTransfer?: boolean;
dataSensitivity?: 'low' | 'medium' | 'high' | 'critical';
amountThreshold?: 'normal' | 'exceeded';
complianceFlags?: string[];
}
ActionContext
interface ActionContext {
userRequest?: string;
sessionId?: string;
ipAddress?: string;
userAgent?: string;
timestamp?: string;
[key: string]: unknown;
}
BatchOptions
interface BatchOptions {
/** Process in parallel (default: true) */
parallel?: boolean;
/** Batch timeout in milliseconds */
timeout?: number;
/** Continue on errors */
continueOnError?: boolean;
/** Wait for all decisions */
waitForDecisions?: boolean;
}
BatchResponse
interface BatchResponse {
results: BatchActionResult[];
totalSubmitted: number;
successCount: number;
errorCount: number;
duration: number;
allSucceeded: boolean;
}