> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maikers.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Complete API documentation for the Maikers SDK

## Overview

This page provides comprehensive documentation for all Maikers SDK methods and interfaces. The SDK is built with TypeScript and provides full type safety for all operations.

<CardGroup cols={2}>
  <Card title="Authentication" icon="key">
    Manage API authentication and sessions
  </Card>

  <Card title="Agent Operations" icon="robot">
    Create, manage, and interact with AI agents
  </Card>

  <Card title="Type Definitions" icon="code">
    TypeScript interfaces and types
  </Card>

  <Card title="Error Handling" icon="exclamation-triangle">
    Error types and handling patterns
  </Card>
</CardGroup>

## SDK Initialization

### Constructor

```typescript theme={null}
new MaikersSDK(config?: SDKConfig)
```

Initialize a new instance of the Maikers SDK.

**Parameters:**

| Parameter | Type        | Required | Description                       |
| --------- | ----------- | -------- | --------------------------------- |
| `config`  | `SDKConfig` | No       | Configuration options for the SDK |

**SDKConfig Interface:**

```typescript theme={null}
interface SDKConfig {
  apiKey?: string; // Your Maikers API key
  baseUrl?: string; // API base URL (defaults to production)
  timeout?: number; // Request timeout in milliseconds
  retryAttempts?: number; // Number of retry attempts for failed requests
  retryDelay?: number; // Delay between retries in milliseconds
}
```

**Example:**

```typescript theme={null}
import { MaikersSDK } from "@maikers/mainframe-sdk";

// Initialize with API key
const sdk = new MaikersSDK({
  apiKey: "your-api-key",
  timeout: 30000,
  retryAttempts: 3,
});

// Initialize without config (uses environment variables)
const sdk = new MaikersSDK();
```

## Authentication Methods

### auth()

```typescript theme={null}
async auth(apiKey: string): Promise<AuthResponse>
```

Authenticate with the Maikers API using an API key.

**Parameters:**

| Parameter | Type     | Required | Description          |
| --------- | -------- | -------- | -------------------- |
| `apiKey`  | `string` | Yes      | Your Maikers API key |

**Returns:** `Promise<AuthResponse>`

**AuthResponse Interface:**

```typescript theme={null}
interface AuthResponse {
  success: boolean;
  message: string;
  user?: {
    id: string;
    email: string;
    plan: string;
  };
}
```

**Example:**

```typescript theme={null}
try {
  const response = await sdk.auth("your-api-key");
  if (response.success) {
    console.log("Authenticated successfully");
  }
} catch (error) {
  console.error("Authentication failed:", error.message);
}
```

### isAuthenticated()

```typescript theme={null}
isAuthenticated(): boolean
```

Check if the SDK is currently authenticated.

**Returns:** `boolean`

**Example:**

```typescript theme={null}
if (sdk.isAuthenticated()) {
  console.log("SDK is authenticated");
} else {
  console.log("Authentication required");
}
```

### logout()

```typescript theme={null}
logout(): void
```

Clear the current authentication session.

**Example:**

```typescript theme={null}
sdk.logout();
console.log("Logged out successfully");
```

## Agent Operations

### agent.create()

```typescript theme={null}
async agent.create(config: AgentConfig): Promise<Agent>
```

Create a new AI agent with the specified configuration.

**Parameters:**

| Parameter | Type          | Required | Description                |
| --------- | ------------- | -------- | -------------------------- |
| `config`  | `AgentConfig` | Yes      | Agent configuration object |

**AgentConfig Interface:**

```typescript theme={null}
interface AgentConfig {
  id: string; // Unique identifier for the agent
  name: string; // Display name for the agent
  description?: string; // Description of the agent's purpose
  riskLevel: "low" | "medium" | "high"; // Risk tolerance level
  jobTypes: string[]; // Array of job types the agent can perform
  skills: string[]; // Array of skills the agent possesses
  personaId?: string; // Persona identifier for the agent
  settings?: AgentSettings; // Additional agent settings
}
```

**AgentSettings Interface:**

```typescript theme={null}
interface AgentSettings {
  maxCreditsPerTask?: number; // Maximum credits to use per task
  autoExecute?: boolean; // Whether to auto-execute tasks
  notifications?: boolean; // Enable/disable notifications
  timezone?: string; // Agent's timezone
}
```

**Returns:** `Promise<Agent>`

**Agent Interface:**

```typescript theme={null}
interface Agent {
  id: string;
  name: string;
  description: string;
  riskLevel: string;
  jobTypes: string[];
  skills: string[];
  status: "active" | "inactive" | "error";
  createdAt: string;
  updatedAt: string;
  credits: number;
  settings: AgentSettings;
}
```

**Example:**

```typescript theme={null}
const agent = await sdk.agent.create({
  id: "trading-bot-1",
  name: "Advanced Trading Bot",
  description: "AI agent for automated cryptocurrency trading",
  riskLevel: "medium",
  jobTypes: ["trading", "analysis"],
  skills: ["sniper", "analyst", "strategist"],
  personaId: "professional-trader",
  settings: {
    maxCreditsPerTask: 10,
    autoExecute: true,
    notifications: true,
  },
});

console.log("Agent created:", agent.id);
```

### agent.get()

```typescript theme={null}
async agent.get(agentId: string): Promise<Agent>
```

Retrieve information about a specific agent.

**Parameters:**

| Parameter | Type     | Required | Description                        |
| --------- | -------- | -------- | ---------------------------------- |
| `agentId` | `string` | Yes      | The unique identifier of the agent |

**Returns:** `Promise<Agent>`

**Example:**

```typescript theme={null}
try {
  const agent = await sdk.agent.get("trading-bot-1");
  console.log("Agent details:", agent);
} catch (error) {
  console.error("Agent not found:", error.message);
}
```

### agent.list()

```typescript theme={null}
async agent.list(options?: ListOptions): Promise<Agent[]>
```

List all agents associated with your account.

**Parameters:**

| Parameter | Type          | Required | Description                      |
| --------- | ------------- | -------- | -------------------------------- |
| `options` | `ListOptions` | No       | Filtering and pagination options |

**ListOptions Interface:**

```typescript theme={null}
interface ListOptions {
  limit?: number; // Maximum number of agents to return
  offset?: number; // Number of agents to skip
  status?: string; // Filter by agent status
  skills?: string[]; // Filter by agent skills
  sortBy?: string; // Sort field
  sortOrder?: "asc" | "desc"; // Sort order
}
```

**Returns:** `Promise<Agent[]>`

**Example:**

```typescript theme={null}
// List all agents
const allAgents = await sdk.agent.list();

// List active trading agents
const tradingAgents = await sdk.agent.list({
  status: "active",
  skills: ["sniper", "analyst"],
  limit: 10,
});

console.log("Found", tradingAgents.length, "trading agents");
```

### agent.update()

```typescript theme={null}
async agent.update(agentId: string, updates: Partial<AgentConfig>): Promise<Agent>
```

Update an existing agent's configuration.

**Parameters:**

| Parameter | Type                   | Required | Description                        |
| --------- | ---------------------- | -------- | ---------------------------------- |
| `agentId` | `string`               | Yes      | The unique identifier of the agent |
| `updates` | `Partial<AgentConfig>` | Yes      | Fields to update                   |

**Returns:** `Promise<Agent>`

**Example:**

```typescript theme={null}
const updatedAgent = await sdk.agent.update("trading-bot-1", {
  name: "Advanced Trading Bot v2",
  riskLevel: "high",
  settings: {
    maxCreditsPerTask: 15,
    autoExecute: false,
  },
});

console.log("Agent updated:", updatedAgent.name);
```

### agent.updateSettings()

```typescript theme={null}
async agent.updateSettings(agentId: string, settings: AgentSettings): Promise<Agent>
```

Update specific settings for an agent.

**Parameters:**

| Parameter  | Type            | Required | Description                        |
| ---------- | --------------- | -------- | ---------------------------------- |
| `agentId`  | `string`        | Yes      | The unique identifier of the agent |
| `settings` | `AgentSettings` | Yes      | New settings to apply              |

**Returns:** `Promise<Agent>`

**Example:**

```typescript theme={null}
await sdk.agent.updateSettings("trading-bot-1", {
  persona: "aggressive trader",
  risks: ["medium", "high"],
  maxCreditsPerTask: 20,
});
```

### agent.delete()

```typescript theme={null}
async agent.delete(agentId: string): Promise<void>
```

Delete an agent permanently.

**Parameters:**

| Parameter | Type     | Required | Description                        |
| --------- | -------- | -------- | ---------------------------------- |
| `agentId` | `string` | Yes      | The unique identifier of the agent |

**Returns:** `Promise<void>`

**Example:**

```typescript theme={null}
try {
  await sdk.agent.delete("trading-bot-1");
  console.log("Agent deleted successfully");
} catch (error) {
  console.error("Failed to delete agent:", error.message);
}
```

## Agent Interaction

### agent.query()

```typescript theme={null}
async agent.query(agentId: string, query: QueryRequest): Promise<QueryResponse>
```

Send a query to an agent and receive a response.

**Parameters:**

| Parameter | Type           | Required | Description                        |
| --------- | -------------- | -------- | ---------------------------------- |
| `agentId` | `string`       | Yes      | The unique identifier of the agent |
| `query`   | `QueryRequest` | Yes      | The query to send to the agent     |

**QueryRequest Interface:**

```typescript theme={null}
interface QueryRequest {
  message: string; // The message/question to send
  context?: any; // Additional context for the query
  maxCredits?: number; // Maximum credits to use for this query
  timeout?: number; // Query timeout in milliseconds
  stream?: boolean; // Whether to stream the response
}
```

**Returns:** `Promise<QueryResponse>`

**QueryResponse Interface:**

```typescript theme={null}
interface QueryResponse {
  id: string; // Unique response ID
  agentId: string; // ID of the responding agent
  data: string; // The agent's response
  creditsUsed: number; // Credits consumed for this query
  timestamp: string; // Response timestamp
  responseTime: number; // Response time in milliseconds
  metadata?: {
    // Additional response metadata
    confidence?: number;
    sources?: string[];
    reasoning?: string;
  };
}
```

**Example:**

```typescript theme={null}
const response = await sdk.agent.query("trading-bot-1", {
  message:
    "Analyze the current market conditions for Bitcoin and provide trading recommendations",
  maxCredits: 5,
  timeout: 30000,
});

console.log("Agent response:", response.data);
console.log("Credits used:", response.creditsUsed);
console.log("Response time:", response.responseTime, "ms");
```

### agent.chat()

```typescript theme={null}
async agent.chat(agentId: string, options?: ChatOptions): Promise<ChatSession>
```

Start an interactive chat session with an agent.

**Parameters:**

| Parameter | Type          | Required | Description                        |
| --------- | ------------- | -------- | ---------------------------------- |
| `agentId` | `string`      | Yes      | The unique identifier of the agent |
| `options` | `ChatOptions` | No       | Chat session options               |

**ChatOptions Interface:**

```typescript theme={null}
interface ChatOptions {
  sessionId?: string; // Existing session ID to resume
  maxMessages?: number; // Maximum messages in session
  autoSave?: boolean; // Auto-save chat history
  context?: any; // Initial context for the chat
}
```

**Returns:** `Promise<ChatSession>`

**ChatSession Interface:**

```typescript theme={null}
interface ChatSession {
  id: string; // Session ID
  agentId: string; // Agent ID
  messages: ChatMessage[]; // Chat history
  status: "active" | "ended"; // Session status
  createdAt: string; // Session creation time

  // Methods
  sendMessage(message: string): Promise<ChatMessage>;
  getHistory(): ChatMessage[];
  end(): Promise<void>;
}
```

**ChatMessage Interface:**

```typescript theme={null}
interface ChatMessage {
  id: string;
  role: "user" | "agent";
  content: string;
  timestamp: string;
  creditsUsed?: number;
}
```

**Example:**

```typescript theme={null}
const chatSession = await sdk.agent.chat("trading-bot-1", {
  maxMessages: 50,
  autoSave: true,
});

// Send a message
const response = await chatSession.sendMessage(
  "What are your thoughts on DeFi?",
);
console.log("Agent:", response.content);

// Get chat history
const history = chatSession.getHistory();
console.log("Chat history:", history.length, "messages");

// End the session
await chatSession.end();
```

## Error Handling

### Error Types

The SDK throws specific error types for different scenarios:

```typescript theme={null}
// Base error class
class MaikersError extends Error {
  code: string;
  statusCode?: number;
  details?: any;
}

// Authentication errors
class AuthenticationError extends MaikersError {
  code = "AUTHENTICATION_FAILED";
}

// Agent not found errors
class AgentNotFoundError extends MaikersError {
  code = "AGENT_NOT_FOUND";
}

// Rate limit errors
class RateLimitError extends MaikersError {
  code = "RATE_LIMIT_EXCEEDED";
  retryAfter?: number;
}

// Network errors
class NetworkError extends MaikersError {
  code = "NETWORK_ERROR";
}

// Validation errors
class ValidationError extends MaikersError {
  code = "VALIDATION_ERROR";
  field?: string;
}
```

### Error Handling Examples

```typescript theme={null}
import {
  MaikersSDK,
  AuthenticationError,
  AgentNotFoundError,
  RateLimitError,
} from "@maikers/mainframe-sdk";

try {
  const response = await sdk.agent.query("agent-id", {
    message: "Hello",
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Please check your API key");
  } else if (error instanceof AgentNotFoundError) {
    console.error("Agent does not exist");
  } else if (error instanceof RateLimitError) {
    console.error("Rate limit exceeded, retry after:", error.retryAfter);
  } else {
    console.error("Unexpected error:", error.message);
  }
}
```

## Utility Methods

### getCredits()

```typescript theme={null}
async getCredits(): Promise<CreditsInfo>
```

Get information about your current credit balance and usage.

**Returns:** `Promise<CreditsInfo>`

**CreditsInfo Interface:**

```typescript theme={null}
interface CreditsInfo {
  balance: number; // Current credit balance
  used: number; // Credits used this period
  limit: number; // Credit limit for current plan
  resetDate: string; // When credits reset
  plan: string; // Current subscription plan
}
```

**Example:**

```typescript theme={null}
const credits = await sdk.getCredits();
console.log("Credit balance:", credits.balance);
console.log("Credits used:", credits.used);
console.log("Plan:", credits.plan);
```

### getUsage()

```typescript theme={null}
async getUsage(period?: 'day' | 'week' | 'month'): Promise<UsageStats>
```

Get usage statistics for your account.

**Parameters:**

| Parameter | Type                         | Required | Description                              |
| --------- | ---------------------------- | -------- | ---------------------------------------- |
| `period`  | `'day' \| 'week' \| 'month'` | No       | Time period for stats (default: 'month') |

**Returns:** `Promise<UsageStats>`

**UsageStats Interface:**

```typescript theme={null}
interface UsageStats {
  period: string;
  totalQueries: number;
  totalCreditsUsed: number;
  agentCount: number;
  averageResponseTime: number;
  topAgents: Array<{
    agentId: string;
    name: string;
    queries: number;
    creditsUsed: number;
  }>;
}
```

**Example:**

```typescript theme={null}
const usage = await sdk.getUsage("week");
console.log("Weekly stats:", usage);
console.log("Total queries:", usage.totalQueries);
console.log("Top agent:", usage.topAgents[0]?.name);
```

## Type Definitions

### Complete Type Reference

```typescript theme={null}
// Main SDK class
export class MaikersSDK {
  constructor(config?: SDKConfig);
  auth(apiKey: string): Promise<AuthResponse>;
  isAuthenticated(): boolean;
  logout(): void;
  getCredits(): Promise<CreditsInfo>;
  getUsage(period?: "day" | "week" | "month"): Promise<UsageStats>;

  agent: {
    create(config: AgentConfig): Promise<Agent>;
    get(agentId: string): Promise<Agent>;
    list(options?: ListOptions): Promise<Agent[]>;
    update(agentId: string, updates: Partial<AgentConfig>): Promise<Agent>;
    updateSettings(agentId: string, settings: AgentSettings): Promise<Agent>;
    delete(agentId: string): Promise<void>;
    query(agentId: string, query: QueryRequest): Promise<QueryResponse>;
    chat(agentId: string, options?: ChatOptions): Promise<ChatSession>;
  };
}

// Export all interfaces
export {
  SDKConfig,
  AgentConfig,
  AgentSettings,
  Agent,
  QueryRequest,
  QueryResponse,
  ChatOptions,
  ChatSession,
  ChatMessage,
  AuthResponse,
  CreditsInfo,
  UsageStats,
  ListOptions,
};

// Export error classes
export {
  MaikersError,
  AuthenticationError,
  AgentNotFoundError,
  RateLimitError,
  NetworkError,
  ValidationError,
};
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/sdk/quickstart">
    Get started with the SDK in minutes
  </Card>

  <Card title="Examples" icon="lightbulb" href="/sdk/examples">
    Explore practical examples and use cases
  </Card>

  <Card title="CLI Tool" icon="terminal" href="/sdk/cli">
    Learn about the command-line interface
  </Card>

  <Card title="GitHub" icon="github" href="https://github.com/maikershq/maikers-mainframe-sdk">
    View source code and contribute
  </Card>
</CardGroup>
