TypeScript SDK Reference

The official TypeScript SDK for Agent OTP. Full type safety, async/await support, and comprehensive error handling.

Installation

npm install @orrisai/agent-otp-sdk

AgentOTPClient

The main client class for interacting with the Agent OTP API.

Constructor

import { AgentOTPClient } from '@orrisai/agent-otp-sdk';

const client = new AgentOTPClient(options: AgentOTPClientOptions);

Options

PropertyTypeRequiredDescription
apiKeystringYesYour Agent OTP API key
baseUrlstringNoAPI base URL (for self-hosted)
timeoutnumberNoDefault request timeout in ms (30000)
retriesnumberNoNumber of retry attempts (3)

requestPermission()

Request a new permission for a sensitive operation.

const permission = await client.requestPermission(
  request: PermissionRequest
): Promise<PermissionResponse>;

PermissionRequest

interface PermissionRequest {
  // The action being requested (e.g., 'email.send', 'file.read')
  action: string;

  // The specific resource being accessed (optional)
  resource?: string;

  // Scope constraints for the permission
  scope: Record<string, unknown>;

  // Additional context about the request
  context?: Record<string, unknown>;

  // Time-to-live in seconds (default: 300, max: 3600)
  ttl?: number;

  // Whether to block until the request is approved/denied
  waitForApproval?: boolean;

  // Timeout for waiting (in ms, default: 60000)
  timeout?: number;

  // Callback when approval is pending
  onPendingApproval?: (info: PendingApprovalInfo) => void;
}

PermissionResponse

interface PermissionResponse {
  // Unique permission ID
  id: string;

  // Status: 'approved', 'denied', 'pending', 'expired'
  status: PermissionStatus;

  // The one-time token (only present when approved)
  token?: string;

  // Granted scope (may be more restrictive than requested)
  scope?: Record<string, unknown>;

  // Expiration timestamp
  expiresAt: string;

  // Reason for denial (if denied)
  reason?: string;

  // URL for manual approval (if pending)
  approvalUrl?: string;
}

Example

const permission = await client.requestPermission({
  action: 'email.send',
  resource: 'email:client@example.com',
  scope: {
    max_emails: 1,
    subject_pattern: '^Invoice.*',
  },
  context: {
    reason: 'Sending monthly invoice',
    triggeredBy: 'scheduled_task',
  },
  ttl: 300,
  waitForApproval: true,
  timeout: 60000,
  onPendingApproval: (info) => {
    console.log(`Approval needed: ${info.approvalUrl}`);
  },
});

if (permission.status === 'approved') {
  console.log('Token:', permission.token);
}

verifyToken()

Verify that a token is still valid without consuming it.

const result = await client.verifyToken(
  permissionId: string,
  token: string
): Promise<TokenVerification>;

interface TokenVerification {
  valid: boolean;
  scope?: Record<string, unknown>;
  usesRemaining?: number;
  expiresAt?: string;
}

useToken()

Mark a token as used after performing the operation.

const result = await client.useToken(
  permissionId: string,
  token: string,
  details?: Record<string, unknown>
): Promise<TokenUsageResult>;

interface TokenUsageResult {
  success: boolean;
  usesRemaining: number;
}

revokeToken()

Revoke a token before it expires or is used.

await client.revokeToken(
  permissionId: string,
  token: string
): Promise<void>;

Error Handling

The SDK throws typed errors for different failure scenarios:

import {
  AgentOTPError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  NetworkError,
} from '@orrisai/agent-otp-sdk';

try {
  const permission = await client.requestPermission({...});
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Invalid or expired API key
    console.error('Auth failed:', error.message);
  } else if (error instanceof ValidationError) {
    // Invalid request parameters
    console.error('Validation failed:', error.details);
  } else if (error instanceof RateLimitError) {
    // Rate limit exceeded
    console.error('Rate limited, retry after:', error.retryAfter);
  } else if (error instanceof NetworkError) {
    // Network connectivity issue
    console.error('Network error:', error.message);
  } else if (error instanceof AgentOTPError) {
    // Other API error
    console.error('API error:', error.code, error.message);
  }
}

Types

All types are exported from the package for use in your application:

import type {
  AgentOTPClientOptions,
  PermissionRequest,
  PermissionResponse,
  PermissionStatus,
  TokenVerification,
  TokenUsageResult,
  PendingApprovalInfo,
  Policy,
  PolicyCondition,
  Agent,
} from '@orrisai/agent-otp-sdk';

Best Practices

  • Store API keys securely - Use environment variables, never commit API keys to source control
  • Use descriptive context - Provide clear reasons for permission requests to help with approval decisions
  • Handle all statuses - Always handle approved, denied, pending, and expired statuses
  • Set appropriate timeouts - Balance between giving humans time to approve and not blocking too long
  • Use tokens immediately - Tokens are ephemeral; use them right after receiving approval

See Also