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

# TypeScript SDK

> Type-safe client library for buntime.sh

## Overview

The buntime.sh TypeScript SDK provides a type-safe, modern interface for interacting with the buntime.sh API. Built with TypeScript, fully async/await compatible, and designed for both Node.js and Bun runtimes.

## Why Use the SDK?

<CardGroup cols={2}>
  <Card title="Type Safety" icon="shield-check">
    Full TypeScript support with autocomplete and type checking
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Structured error types with helpful messages
  </Card>

  <Card title="Automatic Retries" icon="rotate">
    Built-in retry logic for transient failures
  </Card>

  <Card title="Streaming Support" icon="signal-stream">
    Stream execution output in real-time
  </Card>
</CardGroup>

## Installation

<CodeGroup>
  ```bash bun theme={null}
  bun add buntime.sh
  ```

  ```bash npm theme={null}
  npm install buntime.sh
  ```

  ```bash pnpm theme={null}
  pnpm add buntime.sh
  ```

  ```bash yarn theme={null}
  yarn add buntime.sh
  ```
</CodeGroup>

## Quick Start

```typescript theme={null}
import { Buntime } from 'buntime.sh';

// Initialize the client
const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY
});

// Create a session
const session = await client.sessions.create();

// Execute code
const result = await client.execute({
  sessionId: session.id,
  code: `
    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce((a, b) => a + b, 0);
    console.log('Sum:', sum);
  `
});

console.log(result.stdout); // "Sum: 15"
```

## Client Configuration

### Basic Configuration

```typescript theme={null}
const client = new Buntime({
  apiKey: 'your_api_key_here'
});
```

### Advanced Configuration

```typescript theme={null}
const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY,
  baseUrl: 'https://api.buntime.sh', // Custom API URL
  timeout: 60000, // Request timeout in ms (default: 30000)
  maxRetries: 3, // Max retry attempts (default: 2)
  retryDelay: 1000, // Initial retry delay in ms (default: 1000)
  onRetry: (error, attempt) => {
    console.log(`Retry attempt ${attempt}:`, error.message);
  }
});
```

## Core Concepts

### Sessions

Sessions are isolated execution environments. Create a session once and reuse it across multiple executions:

```typescript theme={null}
// Create a session
const session = await client.sessions.create({
  ttl: 3600, // 1 hour
  metadata: {
    userId: 'user_123',
    purpose: 'data-processing'
  }
});

// Use the session multiple times
await client.execute({
  sessionId: session.id,
  code: 'console.log("First execution");'
});

await client.execute({
  sessionId: session.id,
  code: 'console.log("Second execution");'
});

// Clean up when done
await client.sessions.delete({ sessionId: session.id });
```

### Execution

Execute code or commands in a session:

```typescript theme={null}
// Execute inline code
const result = await client.execute({
  sessionId: session.id,
  code: 'console.log("Hello, World!");'
});

// Execute a command
const result = await client.execute({
  sessionId: session.id,
  command: 'bun run index.ts'
});

// Execute with files
const result = await client.execute({
  sessionId: session.id,
  files: [
    { path: 'utils.ts', content: 'export const add = (a, b) => a + b;' },
    { path: 'main.ts', content: 'import { add } from "./utils"; console.log(add(2, 3));' }
  ],
  command: 'bun run main.ts'
});
```

### Files

Manage files in a session:

```typescript theme={null}
// Write a file
await client.files.write({
  sessionId: session.id,
  path: 'data.json',
  content: JSON.stringify({ key: 'value' })
});

// Read a file
const content = await client.files.read({
  sessionId: session.id,
  path: 'data.json'
});

// List files
const files = await client.files.list({
  sessionId: session.id
});
```

## Error Handling

The SDK throws typed errors that you can catch and handle:

```typescript theme={null}
import { Buntime, BuntimeError } from 'buntime.sh';

const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY });

try {
  const result = await client.execute({
    sessionId: 'invalid_session',
    code: 'console.log("test");'
  });
} catch (error) {
  if (error instanceof BuntimeError) {
    console.error('Buntime error:', error.code);
    console.error('Message:', error.message);
    console.error('Status:', error.status);
    console.error('Details:', error.details);
    
    // Handle specific error types
    switch (error.code) {
      case 'session_not_found':
        console.log('Session expired or deleted');
        break;
      case 'rate_limit_exceeded':
        console.log('Rate limited. Retry after:', error.retryAfter);
        break;
      case 'execution_timeout':
        console.log('Code took too long to execute');
        break;
      default:
        console.log('Unknown error');
    }
  } else {
    // Network error or other unexpected error
    console.error('Unexpected error:', error);
  }
}
```

## Complete Example

Here's a full example showing common SDK patterns:

```typescript theme={null}
import { Buntime } from 'buntime.sh';

async function processData() {
  const client = new Buntime({
    apiKey: process.env.BUNTIME_API_KEY
  });

  try {
    // Create a session for this workflow
    console.log('Creating session...');
    const session = await client.sessions.create({
      ttl: 3600,
      metadata: {
        workflow: 'data-processing',
        timestamp: new Date().toISOString()
      }
    });
    console.log('Session created:', session.id);

    // Write data files
    console.log('Writing files...');
    await client.files.write({
      sessionId: session.id,
      path: 'data.csv',
      content: 'name,age\nAlice,30\nBob,25\nCharlie,35'
    });

    // Write processing script
    await client.files.write({
      sessionId: session.id,
      path: 'process.ts',
      content: `
        const csv = await Bun.file('data.csv').text();
        const lines = csv.trim().split('\\n');
        const headers = lines[0].split(',');
        
        const data = lines.slice(1).map(line => {
          const values = line.split(',');
          return {
            name: values[0],
            age: parseInt(values[1])
          };
        });
        
        const avgAge = data.reduce((sum, person) => sum + person.age, 0) / data.length;
        console.log('Average age:', avgAge);
        
        const sorted = data.sort((a, b) => b.age - a.age);
        console.log('Oldest:', sorted[0].name);
      `
    });

    // Execute the script
    console.log('Processing data...');
    const result = await client.execute({
      sessionId: session.id,
      command: 'bun run process.ts',
      timeout: 60
    });

    console.log('Output:', result.stdout);
    console.log('Execution time:', result.executionTime, 'ms');
    console.log('Memory used:', (result.memoryUsed / 1024 / 1024).toFixed(2), 'MB');

    // List all files created
    const files = await client.files.list({ sessionId: session.id });
    console.log('Files in session:', files.map(f => f.path));

    // Clean up
    await client.sessions.delete({ sessionId: session.id });
    console.log('Session deleted');

  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

processData();
```

## TypeScript Types

The SDK exports all types for your convenience:

```typescript theme={null}
import type {
  Session,
  ExecuteRequest,
  ExecuteResponse,
  File,
  FileListResponse,
  BuntimeError,
  BuntimeConfig,
  ResourceLimits,
  SessionMetadata
} from 'buntime.sh';

// Use types in your code
const config: BuntimeConfig = {
  apiKey: process.env.BUNTIME_API_KEY!,
  timeout: 30000
};

const executeParams: ExecuteRequest = {
  sessionId: 'ses_123',
  code: 'console.log("hello");'
};
```

## Best Practices

<AccordionGroup>
  <Accordion icon="key" title="Use environment variables for API keys">
    Never hardcode your API key. Use environment variables or a secrets manager.

    ```typescript theme={null}
    const client = new Buntime({
      apiKey: process.env.BUNTIME_API_KEY
    });
    ```
  </Accordion>

  <Accordion icon="recycle" title="Reuse sessions">
    Create a session once and reuse it for multiple operations rather than creating a new session for each execution.

    ```typescript theme={null}
    const session = await client.sessions.create();

    // Good: Multiple executions in same session
    await client.execute({ sessionId: session.id, code: '...' });
    await client.execute({ sessionId: session.id, code: '...' });
    ```
  </Accordion>

  <Accordion icon="broom" title="Clean up sessions">
    Always delete sessions when you're done to free resources.

    ```typescript theme={null}
    try {
      const session = await client.sessions.create();
      // ... use session
    } finally {
      await client.sessions.delete({ sessionId: session.id });
    }
    ```
  </Accordion>

  <Accordion icon="shield" title="Handle errors properly">
    Use try-catch blocks and check for specific error types.

    ```typescript theme={null}
    try {
      await client.execute({ ... });
    } catch (error) {
      if (error instanceof BuntimeError) {
        // Handle buntime-specific errors
      }
    }
    ```
  </Accordion>

  <Accordion icon="gauge" title="Monitor resource usage">
    Check execution metrics to optimize performance.

    ```typescript theme={null}
    const result = await client.execute({ ... });
    console.log('Execution time:', result.executionTime);
    console.log('Memory used:', result.memoryUsed);
    ```
  </Accordion>
</AccordionGroup>

## Framework Integration

### Express

```typescript theme={null}
import express from 'express';
import { Buntime } from 'buntime.sh';

const app = express();
const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY });

app.post('/execute', async (req, res) => {
  try {
    const { sessionId, code } = req.body;
    const result = await client.execute({ sessionId, code });
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

### Next.js API Route

```typescript theme={null}
import { Buntime } from 'buntime.sh';
import type { NextApiRequest, NextApiResponse } from 'next';

const client = new Buntime({ apiKey: process.env.BUNTIME_API_KEY! });

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { sessionId, code } = req.body;
    const result = await client.execute({ sessionId, code });
    return res.status(200).json(result);
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="SDK Reference" icon="book" href="/sdk/client">
    Explore all SDK methods and options
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    View the underlying REST API
  </Card>

  <Card title="Examples" icon="brackets-curly" href="https://github.com/buntimesh/examples">
    Browse code examples
  </Card>

  <Card title="AI Integration" icon="brain" href="/guides/ai-integration">
    Integrate with AI agents
  </Card>
</CardGroup>

<Note>
  **Questions?** Join our [Discord community](https://discord.gg/buntime) or check out the [GitHub repository](https://github.com/buntimesh/buntime).
</Note>
