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

# Instances

> Create and manage VM instances

## Overview

Instances are VMs running the in10nt agent server. They provide isolated environments for executing AI coding tasks.

## Create Instance

### Static method (zero-config)

```typescript theme={null}
import { Instance } from '@in10nt/sdk';

const instance = await Instance.create({
  name: 'my-agent',
  description: 'My coding agent',
  agentType: 'opencode',              // 'opencode' or 'moltbot'
  containerTemplateId: 'tmpl_12345',   // Optional: custom template
  vmSize: 'shared-cpu-4x',            // Optional: VM size
  region: 'iad',                       // Optional: region
  env: { API_KEY: 'secret' }           // Optional: env vars
});
```

### Via client

```typescript theme={null}
import { In10ntClient } from '@in10nt/sdk';

const client = new In10ntClient();
const instance = await client.instances.create({
  name: 'my-agent',
  description: 'My coding agent'
});
```

### Agent Types

| Type       | Description              | Min Size              |
| ---------- | ------------------------ | --------------------- |
| `opencode` | Default agent (OpenCode) | `shared-cpu-1x`       |
| `moltbot`  | Moltbot/Clawdbot agent   | `shared-cpu-8x` (2GB) |

<Note>
  Moltbot requires at least 2GB RAM and automatically upgrades to `shared-cpu-8x` if needed
</Note>

### Parameters

| Parameter             | Type     | Description                                               |
| --------------------- | -------- | --------------------------------------------------------- |
| `name`                | `string` | **Required** - Instance name                              |
| `description`         | `string` | **Required** - Description                                |
| `agentType`           | `string` | Agent type: `opencode` or `moltbot` (default: `opencode`) |
| `containerTemplateId` | `string` | Container template ID                                     |
| `vmSize`              | `string` | VM size (default: `shared-cpu-4x`)                        |
| `region`              | `string` | Region code (default: `iad`)                              |
| `env`                 | `object` | Environment variables                                     |

### Response

```typescript theme={null}
{
  instanceId: "inst_abc123",
  name: "my-agent",
  status: "healthy",
  agentUrl: "http://machine-id.vm.app.internal:3000",
  createdAt: "2025-01-06T..."
}
```

## Connect to Existing Instance

```typescript theme={null}
const instance = await Instance.connect('inst_abc123');

// Or via client
const instance = await client.instances.get('inst_abc123');
const instance = await client.instances.getByName('my-agent');
```

## Integrations

Connect your agent to external services:

```typescript theme={null}
const instance = await client.instances.create({
  name: 'discord-bot',
  description: 'Discord bot agent',
  agentType: 'moltbot',  // Required for Discord
  integrations: ['Discord', 'GitHub'],
  integrationEnv: {
    DISCORD_BOT_TOKEN: 'xxx',
    DISCORD_GUILD_ID: 'xxx',
    DISCORD_CHANNEL_ID: 'xxx',
    GITHUB_TOKEN: 'xxx'
  }
});
```

### Supported Integrations

| Integration | Required Env Vars                                               |
| ----------- | --------------------------------------------------------------- |
| `Discord`   | `DISCORD_BOT_TOKEN`, `DISCORD_GUILD_ID`, `DISCORD_CHANNEL_ID`   |
| `Slack`     | `SLACK_BOT_TOKEN`                                               |
| `GitHub`    | `GITHUB_TOKEN`                                                  |
| `Notion`    | `NOTION_API_TOKEN`                                              |
| `Telegram`  | `TELEGRAM_BOT_TOKEN`                                            |
| `Jira`      | `JIRA_BASE_URL`, `JIRA_EMAIL`, `JIRA_API_TOKEN`                 |
| `Voice`     | `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, `TWILIO_FROM_NUMBER` |

<Note>
  Voice integration supports both Twilio (required) and ElevenLabs (optional). Add `ELEVENLABS_API_KEY`, `ELEVENLABS_VOICE_ID` for text-to-speech.
</Note>

<Warning>
  Discord integration only works with `agentType: 'moltbot'`
</Warning>

### Update Integrations

```typescript theme={null}
await instance.integrations.set({
  integrations: ['GitHub', 'Notion'],
  integrationEnv: { GITHUB_TOKEN: 'new_token' }
});

// Read current integrations
const config = await instance.integrations.get();
```

## List Instances

```typescript theme={null}
// Static
const instances = await Instance.list();

// Via client
const instances = await client.instances.list();

instances.forEach(instance => {
  console.log(`${instance.name}: ${instance.status}`);
});
```

## Get Instance

Retrieve a specific instance by ID:

```typescript theme={null}
const instance = await Instance.connect('inst_abc123');
// or
const instance = await client.instances.get('inst_abc123');
```

Or by name:

```typescript theme={null}
const instance = await client.instances.getByName('my-agent');
```

## Run Task

Execute a coding task on an instance (works for both OpenCode and Moltbot):

```typescript theme={null}
const result = await instance.run(
  'Build a REST API with user CRUD operations',
  {
    model: 'anthropic/claude-sonnet-4.5',  // Optional
    timeout: 300_000,                       // Optional
    maxTokens: 8000,                        // Optional
    system: 'Custom system prompt'          // Optional
  }
);

console.log(result.response);
console.log(`Tokens used: ${result.tokensUsed}`);
console.log(`Duration: ${result.duration_ms}ms`);
```

<Note>
  The same `.run()` method works for both OpenCode and Moltbot instances. Moltbot instances automatically use optimized internal routing.
</Note>

### Complete Example with All Options

```typescript theme={null}
const result = await instance.run(
  'Build a REST API with authentication',
  {
    model: 'anthropic/claude-sonnet-4.5',
    timeout: 300_000,
    pollInterval: 5_000,
    maxPollTime: 120_000,
    healthCheckRetries: 20,
    healthCheckDelay: 3_000,
    waitForHealth: true,
    maxTokens: 8000,
    system: 'You are a senior backend engineer',
    background: false
  }
);
```

### Options

| Option               | Type      | Default                       | Description                       |
| -------------------- | --------- | ----------------------------- | --------------------------------- |
| `model`              | `string`  | `anthropic/claude-sonnet-4.5` | LLM model                         |
| `provider`           | `string`  | `openrouter`                  | Model provider                    |
| `maxTokens`          | `number`  | -                             | Max response tokens               |
| `system`             | `string`  | -                             | Custom system prompt              |
| `timeout`            | `number`  | `480000`                      | Timeout in ms                     |
| `pollInterval`       | `number`  | `2000`                        | Poll interval in ms               |
| `maxPollTime`        | `number`  | `600000`                      | Max poll time in ms               |
| `healthCheckRetries` | `number`  | `40`                          | Health check retry count          |
| `healthCheckDelay`   | `number`  | `5000`                        | Delay between health checks in ms |
| `waitForHealth`      | `boolean` | `true`                        | Wait for health before running    |
| `background`         | `boolean` | `false`                       | Return taskId immediately         |
| `tools`              | `array`   | -                             | Custom tools for the agent        |
| `autoTools`          | `boolean` | `true`                        | Enable automatic tool usage       |

## Background Mode

Run a task in the background and poll later:

```typescript theme={null}
const { taskId } = await instance.run('Build a web app', { background: true });

// ... do other work ...

// Poll when ready
const result = await instance.tasks.poll(taskId!);
console.log(result.response);
```

## Tasks Namespace

### List Tasks

```typescript theme={null}
const tasks = await instance.tasks.list();
```

### Get Task Status

```typescript theme={null}
const status = await instance.tasks.getStatus(taskId);
// Returns: { status: 'processing' | 'completed' | 'failed', ... }
```

### Poll Task

```typescript theme={null}
const result = await instance.tasks.poll(taskId, {
  pollInterval: 2000,    // Check every 2s
  maxPollTime: 600000    // Timeout after 10min
});
```

## Conversation Context

Instance maintains conversation history automatically. You can send multiple prompts:

```typescript theme={null}
const instance = await Instance.create({
  name: 'web-builder',
  description: 'Web project'
});

// First prompt
await instance.run('Create a simple REST API with user CRUD');

// Follow-up prompts (context maintained)
await instance.run('Add JWT authentication');
await instance.run('Add rate limiting middleware');
await instance.run('Write integration tests');
```

## Instance Management

### Health Check

Check if instance is ready:

```typescript theme={null}
const health = await instance.health();
console.log(health.status); // "healthy"
```

### Execute Command

Run a command directly on the instance:

```typescript theme={null}
const output = await instance.execute('ls -la /workspace');
```

### Refresh Status

Update instance data:

```typescript theme={null}
await instance.refresh();
console.log(`Current status: ${instance.status}`);
```

### Stop Instance

```typescript theme={null}
await instance.stop();
```

### Restart Instance

```typescript theme={null}
await instance.restart();
```

### Destroy Instance

```typescript theme={null}
await instance.destroy();
```

<Warning>
  Destroy is permanent. Use `stop()` if you plan to restart later.
</Warning>

## Files Namespace

### Get Changes

Get files modified by the agent:

```typescript theme={null}
const changes = await instance.files.getChanges();
console.log('Modified files:', changes.files);
```

### Filesystem Tree

```typescript theme={null}
const tree = await instance.files.tree();
```

## Ports Namespace

Access dev servers running in your instance:

```typescript theme={null}
// List active ports
const ports = await instance.ports.list();

// Get proxy URL for a port
const url = instance.ports.getProxyUrl(5173);
// or shorthand
const url = instance.getProxyUrl(5173);

// Register ports manually
await instance.ports.open([5173, 3000, 8080]);
```

## Tools Namespace

```typescript theme={null}
// List available tools
const tools = await instance.tools.list();

// Get MCP config
const mcp = await instance.tools.getMcpConfig();
```

## Integrations Namespace

```typescript theme={null}
// Get current integrations
const config = await instance.integrations.get();

// Set / update integrations
await instance.integrations.set({
  integrations: ['GitHub'],
  integrationEnv: { GITHUB_TOKEN: 'xxx' }
});
```

## Snapshots

Save and restore workspace state:

```typescript theme={null}
// Create snapshot
const { snapshotId } = await instance.snapshot();

// Restore from snapshot (via create with snapshotId)
const restored = await Instance.create({
  name: 'restored',
  description: 'Restored workspace'
});
```

## Save & Clone Instance

Clone from saved templates (workspace snapshots):

```typescript theme={null}
// Snapshot an instance
await instance.snapshot();

// List saved templates
const saved = await client.savedTemplates.list();

// Clone from saved template
const clone = await client.instances.createFromSavedTemplate({
  templateName: 'my-template',
  newInstanceName: 'new-instance'
});

// Delete a saved template
await client.savedTemplates.delete('old-template');
```

## Stream Logs

```typescript theme={null}
// Node.js: install 'eventsource' package first
const stopStreaming = await instance.streamLogs((log) => {
  console.log(`[${log.type}] ${log.message}`);
});

await instance.run('Build a web app');
stopStreaming();
```

## Quick Examples

### Basic Usage

```typescript theme={null}
const instance = await Instance.create({
  name: 'my-agent',
  description: 'Quick task'
});

await instance.run('Create a REST API');
await instance.destroy();
```

### Multi-Step Session

```typescript theme={null}
const instance = await Instance.create({
  name: 'session',
  description: 'Multi-step project'
});

await instance.run('Initialize project');
await instance.run('Add authentication');
await instance.run('Write tests');

const changes = await instance.files.getChanges();
await instance.destroy();
```

### Discord Bot (Moltbot)

```typescript theme={null}
const bot = await client.instances.create({
  name: 'discord-bot',
  description: 'My Discord bot',
  agentType: 'moltbot',
  integrations: ['Discord'],
  integrationEnv: {
    DISCORD_BOT_TOKEN: process.env.DISCORD_TOKEN,
    DISCORD_GUILD_ID: '123456',
    DISCORD_CHANNEL_ID: '789012'
  }
});

// Bot automatically responds to Discord messages
// You can also run tasks directly via HTTP:
await bot.run('Add a /help command that lists all available features');
```

### Voice Agent (Twilio + ElevenLabs)

```typescript theme={null}
const voiceAgent = await client.instances.create({
  name: 'voice-assistant',
  description: 'Voice-enabled AI agent',
  integrations: ['Voice'],
  integrationEnv: {
    TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID,
    TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN,
    TWILIO_FROM_NUMBER: '+1234567890',
    ELEVENLABS_API_KEY: process.env.ELEVENLABS_KEY,
    ELEVENLABS_VOICE_ID: 'voice_id_here'
  }
});
```

### Moltbot with Custom Options

```typescript theme={null}
const moltbot = await client.instances.create({
  name: 'custom-moltbot',
  description: 'Moltbot with custom settings',
  agentType: 'moltbot'
});

// Run task with custom options (same API as OpenCode)
const result = await moltbot.run(
  'Analyze this codebase and suggest improvements',
  {
    model: 'anthropic/claude-sonnet-4.5',
    maxTokens: 16000,
    timeout: 900000  // 15 minutes for complex tasks
  }
);
```

***

## HTTP API Reference

Base URL: `https://in10t-api-v2.fly.dev`
Auth: `Authorization: Bearer YOUR_API_KEY` or `X-API-Key: YOUR_API_KEY`

### Create Instance

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-agent",
    "description": "My coding agent",
    "agentType": "opencode",
    "region": "iad",
    "vmSize": "shared-cpu-4x"
  }'
```

### List Instances

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances
```

### Get Instance

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances/{instanceId}
```

### Run Task (OpenCode & Moltbot)

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/run \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Build a REST API with user CRUD",
    "model": "anthropic/claude-sonnet-4.5",
    "timeout": 480000,
    "max_tokens": 8000
  }'
```

| Body Param   | Type    | Required | Description                                      |
| ------------ | ------- | -------- | ------------------------------------------------ |
| `prompt`     | string  | Yes      | Task prompt                                      |
| `model`      | string  | No       | LLM model (default: anthropic/claude-sonnet-4.5) |
| `provider`   | string  | No       | Model provider (default: openrouter)             |
| `timeout`    | number  | No       | Timeout in ms (default: 480000)                  |
| `max_tokens` | number  | No       | Max response tokens                              |
| `system`     | string  | No       | Custom system prompt                             |
| `async`      | boolean | No       | Run asynchronously                               |

### Stop Instance

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/stop \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Destroy Instance

```bash theme={null}
curl -X DELETE https://in10t-api-v2.fly.dev/instances/{instanceId} \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Restart Instance

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/restart \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Get Health

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances/{instanceId}/health
```

### Get Changes

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://in10t-api-v2.fly.dev/instances/{instanceId}/changes"
```

### Execute Command

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/execute \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "ls -la /workspace"}'
```

### Create Snapshot

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/snapshot \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### List Ports

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances/{instanceId}/ports
```

### Open Ports

```bash theme={null}
curl -X POST https://in10t-api-v2.fly.dev/instances/{instanceId}/open-ports \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"ports": [5173, 3000]}'
```

### List Tasks

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances/{instanceId}/tasks
```

### Get Task Status

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://in10t-api-v2.fly.dev/instances/{instanceId}/tasks/{taskId}
```
