> ## 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.

# Execute Code

> Execute code or commands in a session

## Overview

Executes JavaScript/TypeScript code or shell commands in an existing session. The session's filesystem and running processes persist between executions, enabling iterative development.

## Request

<ParamField header="Authorization" type="string" required>
  Bearer token with your API key
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`
</ParamField>

### Request Body

<ParamField body="sessionId" type="string" required>
  ID of the session to execute code in
</ParamField>

<ParamField body="code" type="string" optional>
  JavaScript/TypeScript code to execute. Either `code` or `command` must be provided.
</ParamField>

<ParamField body="command" type="string" optional>
  Shell command to run (e.g., `bun run index.ts`). Either `code` or `command` must be provided.
</ParamField>

<ParamField body="files" type="array" optional>
  Array of files to write before execution

  <Expandable title="file object">
    <ParamField body="path" type="string" required>
      File path relative to `/workspace`
    </ParamField>

    <ParamField body="content" type="string" required>
      File content (max 10MB per file)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="env" type="object" optional>
  Environment variables to set for this execution (max 100 variables)
</ParamField>

<ParamField body="timeout" type="integer" optional>
  Execution timeout in seconds. Default: 30, Max: 300 (5 minutes)
</ParamField>

<ParamField body="workingDir" type="string" optional>
  Working directory for execution. Default: `/workspace`
</ParamField>

<ParamField body="stream" type="boolean" optional>
  Stream output as Server-Sent Events. Default: false
</ParamField>

## Response

<ResponseField name="stdout" type="string" required>
  Standard output from the execution
</ResponseField>

<ResponseField name="stderr" type="string" required>
  Standard error output
</ResponseField>

<ResponseField name="exitCode" type="integer" required>
  Process exit code (0 = success)
</ResponseField>

<ResponseField name="executionTime" type="integer" required>
  Execution time in milliseconds
</ResponseField>

<ResponseField name="memoryUsed" type="integer" required>
  Peak memory usage in bytes
</ResponseField>

<ResponseField name="cpuTime" type="integer" required>
  CPU time used in milliseconds
</ResponseField>

<ResponseField name="timedOut" type="boolean" required>
  Whether the execution was terminated due to timeout
</ResponseField>

<ResponseField name="filesWritten" type="array" optional>
  Paths of files written during execution
</ResponseField>

## Examples

### Execute Inline Code

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.buntime.sh/execute \
    -H "Authorization: Bearer $BUNTIME_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "sessionId": "ses_abc123",
      "code": "const result = [1, 2, 3, 4, 5].reduce((a, b) => a + b, 0); console.log(\"Sum:\", result);"
    }'
  ```

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

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

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

  console.log(result.stdout); // "Sum: 15"
  console.log(result.exitCode); // 0
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "stdout": "Sum: 15\n",
    "stderr": "",
    "exitCode": 0,
    "executionTime": 45,
    "memoryUsed": 12582912,
    "cpuTime": 42,
    "timedOut": false,
    "filesWritten": []
  }
  ```
</ResponseExample>

### Execute with Multiple Files

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.buntime.sh/execute \
    -H "Authorization: Bearer $BUNTIME_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "sessionId": "ses_abc123",
      "files": [
        {
          "path": "utils.ts",
          "content": "export const add = (a: number, b: number) => a + b;"
        },
        {
          "path": "index.ts",
          "content": "import { add } from \"./utils\";\nconsole.log(\"Result:\", add(5, 3));"
        }
      ],
      "command": "bun run index.ts"
    }'
  ```

  ```typescript TypeScript SDK theme={null}
  const result = await client.execute({
    sessionId: 'ses_abc123',
    files: [
      {
        path: 'utils.ts',
        content: 'export const add = (a: number, b: number) => a + b;'
      },
      {
        path: 'index.ts',
        content: 'import { add } from "./utils";\nconsole.log("Result:", add(5, 3));'
      }
    ],
    command: 'bun run index.ts'
  });
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "stdout": "Result: 8\n",
    "stderr": "",
    "exitCode": 0,
    "executionTime": 123,
    "memoryUsed": 18874368,
    "cpuTime": 115,
    "timedOut": false,
    "filesWritten": ["utils.ts", "index.ts"]
  }
  ```
</ResponseExample>

### Execute with Environment Variables

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.buntime.sh/execute \
    -H "Authorization: Bearer $BUNTIME_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "sessionId": "ses_abc123",
      "code": "console.log(\"API Key:\", process.env.API_KEY);",
      "env": {
        "API_KEY": "secret_key_123",
        "DEBUG": "true"
      }
    }'
  ```

  ```typescript TypeScript SDK theme={null}
  const result = await client.execute({
    sessionId: 'ses_abc123',
    code: 'console.log("API Key:", process.env.API_KEY);',
    env: {
      API_KEY: 'secret_key_123',
      DEBUG: 'true'
    }
  });
  ```
</RequestExample>

### Execute Shell Command

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.buntime.sh/execute \
    -H "Authorization: Bearer $BUNTIME_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "sessionId": "ses_abc123",
      "command": "bun install && bun test"
    }'
  ```

  ```typescript TypeScript SDK theme={null}
  const result = await client.execute({
    sessionId: 'ses_abc123',
    command: 'bun install && bun test'
  });
  ```
</RequestExample>

### Long-Running with Timeout

<RequestExample>
  ```typescript TypeScript SDK theme={null}
  const result = await client.execute({
    sessionId: 'ses_abc123',
    code: `
      // Process large dataset
      const data = Array.from({ length: 1000000 }, (_, i) => i);
      const sum = data.reduce((a, b) => a + b, 0);
      console.log("Sum:", sum);
    `,
    timeout: 120 // 2 minutes
  });
  ```
</RequestExample>

## Error Responses

<ResponseExample>
  ```json 404 Session Not Found theme={null}
  {
    "error": {
      "code": "session_not_found",
      "message": "Session not found or expired",
      "details": {
        "sessionId": "ses_invalid"
      }
    }
  }
  ```

  ```json 400 Bad Request theme={null}
  {
    "error": {
      "code": "invalid_request",
      "message": "Either 'code' or 'command' must be provided"
    }
  }
  ```

  ```json 408 Timeout theme={null}
  {
    "error": {
      "code": "execution_timeout",
      "message": "Execution exceeded timeout of 30 seconds",
      "stdout": "Partial output...",
      "stderr": ""
    }
  }
  ```

  ```json 413 File Too Large theme={null}
  {
    "error": {
      "code": "file_too_large",
      "message": "File exceeds maximum size of 10MB",
      "details": {
        "path": "data.json",
        "size": 15728640
      }
    }
  }
  ```

  ```json 507 Disk Full theme={null}
  {
    "error": {
      "code": "disk_full",
      "message": "Session disk limit exceeded",
      "details": {
        "used": 1073741824,
        "limit": 1073741824
      }
    }
  }
  ```
</ResponseExample>

## Execution Modes

### Inline Code

Pass code directly in the request body. Best for short scripts or single-file executions.

```typescript theme={null}
await client.execute({
  sessionId: 'ses_abc123',
  code: 'console.log("Hello!");'
});
```

### Command Execution

Run shell commands like `bun run`, `bun test`, or `bun install`.

```typescript theme={null}
await client.execute({
  sessionId: 'ses_abc123',
  command: 'bun run index.ts'
});
```

### Multi-file Projects

Write multiple files atomically before execution.

```typescript theme={null}
await client.execute({
  sessionId: 'ses_abc123',
  files: [
    { path: 'file1.ts', content: '...' },
    { path: 'file2.ts', content: '...' }
  ],
  command: 'bun run file1.ts'
});
```

## Streaming Output

For long-running executions, enable streaming to receive output as it's generated:

```typescript theme={null}
const stream = await client.execute({
  sessionId: 'ses_abc123',
  command: 'bun test',
  stream: true
});

for await (const chunk of stream) {
  if (chunk.type === 'stdout') {
    console.log(chunk.data);
  } else if (chunk.type === 'stderr') {
    console.error(chunk.data);
  } else if (chunk.type === 'exit') {
    console.log('Exit code:', chunk.code);
  }
}
```

## Package Installation

Bun automatically installs packages on import:

```typescript theme={null}
await client.execute({
  sessionId: 'ses_abc123',
  code: `
    import { z } from "zod"; // Auto-installed
    const schema = z.string();
    console.log(schema.parse("hello"));
  `
});
```

For explicit installation:

```typescript theme={null}
await client.execute({
  sessionId: 'ses_abc123',
  command: 'bun add lodash react'
});
```

## Process Management

Processes from previous executions stay alive:

```typescript theme={null}
// Start a server
await client.execute({
  sessionId: 'ses_abc123',
  code: 'Bun.serve({ port: 8080, fetch: () => new Response("OK") });'
});

// Server keeps running in background
// Access at: https://ses-abc123.buntime.sh
```

Kill background processes:

```typescript theme={null}
await client.execution.kill({
  sessionId: 'ses_abc123',
  pid: 1234 // Optional: specific process
});
```

## Best Practices

<AccordionGroup>
  <Accordion icon="clock" title="Set appropriate timeouts">
    Use shorter timeouts (10-30s) for quick scripts, longer (2-5min) for complex operations like installs or tests.
  </Accordion>

  <Accordion icon="file" title="Batch file writes">
    Write all files in a single execute call rather than making multiple file write requests.
  </Accordion>

  <Accordion icon="key" title="Use environment variables for secrets">
    Pass secrets via `env` parameter instead of hardcoding in code. Env vars are encrypted in transit and at rest.
  </Accordion>

  <Accordion icon="memory" title="Monitor resource usage">
    Check `memoryUsed` and `cpuTime` in responses to optimize your code and avoid hitting limits.
  </Accordion>

  <Accordion icon="bug" title="Handle errors gracefully">
    Check `exitCode` and parse `stderr` to detect and handle errors properly.
  </Accordion>
</AccordionGroup>

## Limits

| Resource             | Free Tier | Paid Tier   | Enterprise |
| -------------------- | --------- | ----------- | ---------- |
| Execution timeout    | 30s       | 300s (5min) | Custom     |
| Memory per execution | 1GB       | 4GB         | Custom     |
| File size            | 10MB      | 50MB        | Custom     |
| Files per request    | 100       | 1000        | Custom     |
| Env variables        | 100       | 500         | Custom     |

## Related Endpoints

<CardGroup cols={3}>
  <Card title="Write Files" icon="file-pen" href="/api-reference/files/write">
    Write files separately
  </Card>

  <Card title="Kill Process" icon="stop" href="/api-reference/execution/kill">
    Stop running processes
  </Card>

  <Card title="List Files" icon="folder" href="/api-reference/files/list">
    See all files in session
  </Card>
</CardGroup>
