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

# Prime Agent

> Run Prime Agent in a secure E2B sandbox with full filesystem, terminal, and git access.

[Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent) is Prime Intellect's open-source coding and research agent for general and long-running work, built around a persistent IPython kernel and recursive subagents. E2B provides a pre-built `prime` template with Prime Agent already installed.

## CLI

Create a sandbox with the [E2B CLI](/docs/cli).

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
e2b sbx create prime
```

Once inside the sandbox, start Prime Agent.

```bash theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
prime-agent
```

On first launch, run `/login` to pick a subscription (Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot) or an API-key provider.

## Run headless

Use `-p` to print the response and exit. Prime Agent has no approval prompts or auto-approve flag — it runs model-generated Python and project commands with the permissions of the user it runs as, which is why upstream recommends running it inside a sandbox. The sandbox isolates the agent from your host machine, but sandboxes can reach the open internet by default — restrict outbound traffic with [network rules](/docs/network/internet-access). Prime Agent authenticates with standard provider environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`, `OPENROUTER_API_KEY`), or `PRIME_API_KEY` for Prime Inference. Pick a model with `--provider <name>` and `--model <pattern>`.

<Note>
  Running tool calls without approval is contained by the sandbox: the agent cannot touch your host machine, local files, or credentials. It can still make outbound network requests — internet access is enabled by default. To limit where an unattended agent can connect, configure [outbound network rules](/docs/network/internet-access) (`allowInternetAccess`, plus allow/deny lists by CIDR or hostname). Hostname rules apply to HTTP(S) traffic only; use CIDR rules for other protocols.
</Note>

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import { Sandbox } from 'e2b'

  const sandbox = await Sandbox.create('prime', {
    envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
  })

  const result = await sandbox.commands.run(
    `prime-agent -p "Create a hello world HTTP server in Go"`
  )

  console.log(result.stdout)
  await sandbox.kill()
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import os
  from e2b import Sandbox

  sandbox = Sandbox.create("prime", envs={
      "ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"],
  })

  result = sandbox.commands.run(
      'prime-agent -p "Create a hello world HTTP server in Go"',
  )

  print(result.stdout)
  sandbox.kill()
  ```
</CodeGroup>

### Example: work on a cloned repository

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import { Sandbox } from 'e2b'

  const sandbox = await Sandbox.create('prime', {
    envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
    timeoutMs: 600_000,
  })

  await sandbox.git.clone('https://github.com/your-org/your-repo.git', {
    path: '/home/user/repo',
    username: 'x-access-token',
    password: process.env.GITHUB_TOKEN,
    depth: 1,
  })

  const result = await sandbox.commands.run(
    `cd /home/user/repo && prime-agent -p "Add error handling to all API endpoints"`,
    { onStdout: (data) => process.stdout.write(data) }
  )

  const diff = await sandbox.commands.run('cd /home/user/repo && git diff')
  console.log(diff.stdout)

  await sandbox.kill()
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import os
  from e2b import Sandbox

  sandbox = Sandbox.create("prime", envs={
      "ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"],
  }, timeout=600)

  sandbox.git.clone("https://github.com/your-org/your-repo.git",
      path="/home/user/repo",
      username="x-access-token",
      password=os.environ["GITHUB_TOKEN"],
      depth=1,
  )

  result = sandbox.commands.run(
      'cd /home/user/repo && prime-agent -p "Add error handling to all API endpoints"',
      on_stdout=lambda data: print(data, end=""),
  )

  diff = sandbox.commands.run("cd /home/user/repo && git diff")
  print(diff.stdout)

  sandbox.kill()
  ```
</CodeGroup>

## Streaming JSON

Use `--mode json` to get a real-time JSONL event stream. The first line is a session header, followed by events as they occur — `agent_start`, `turn_start`, `message_start`/`message_update`/`message_end`, `tool_execution_start`/`tool_execution_end`, `turn_end`, and `agent_end`. For bidirectional integrations, `--mode rpc` exposes the same session over stdin/stdout.

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import { Sandbox } from 'e2b'

  const sandbox = await Sandbox.create('prime', {
    envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
  })

  const result = await sandbox.commands.run(
    `cd /home/user/repo && prime-agent --mode json "Find and fix all TODO comments"`,
    {
      onStdout: (data) => {
        for (const line of data.split('\n').filter(Boolean)) {
          const event = JSON.parse(line)
          if (event.type === 'tool_execution_start') {
            console.log(`[tool] ${event.toolName}`)
          } else if (event.type === 'message_end') {
            console.log(`[message] ${event.message.role}`)
          } else if (event.type === 'agent_end') {
            console.log(`[done] ${event.messages.length} messages`)
          }
        }
      },
    }
  )

  await sandbox.kill()
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import os
  import json
  from e2b import Sandbox

  sandbox = Sandbox.create("prime", envs={
      "ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"],
  })

  def handle_event(data):
      for line in data.strip().split("\n"):
          if line:
              event = json.loads(line)
              if event["type"] == "tool_execution_start":
                  print(f"[tool] {event['toolName']}")
              elif event["type"] == "message_end":
                  print(f"[message] {event['message']['role']}")
              elif event["type"] == "agent_end":
                  print(f"[done] {len(event['messages'])} messages")

  result = sandbox.commands.run(
      'cd /home/user/repo && prime-agent --mode json "Find and fix all TODO comments"',
      on_stdout=handle_event,
  )

  sandbox.kill()
  ```
</CodeGroup>

## Session management

Prime Agent saves sessions to disk and runs them behind a background daemon, so work survives across commands in a long-lived sandbox. Use `-c` to continue the most recent session, `-r <path|id>` to resume a specific one, and `prime-agent agents` / `prime-agent attach <agent>` to list and reattach to agents still running in the sandbox.

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import { Sandbox } from 'e2b'

  const sandbox = await Sandbox.create('prime', {
    envs: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
    timeoutMs: 600_000,
  })

  // Start a new session
  const initial = await sandbox.commands.run(
    `cd /home/user/repo && prime-agent -p "Analyze the codebase and create a refactoring plan"`,
    { onStdout: (data) => process.stdout.write(data) }
  )

  // Continue the most recent session with a follow-up task
  const followUp = await sandbox.commands.run(
    `cd /home/user/repo && prime-agent -c -p "Now implement step 1 of the plan"`,
    { onStdout: (data) => process.stdout.write(data) }
  )

  const diff = await sandbox.commands.run('cd /home/user/repo && git diff')
  console.log(diff.stdout)

  await sandbox.kill()
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  import os
  from e2b import Sandbox

  sandbox = Sandbox.create("prime", envs={
      "ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"],
  }, timeout=600)

  # Start a new session
  initial = sandbox.commands.run(
      'cd /home/user/repo && prime-agent -p "Analyze the codebase and create a refactoring plan"',
      on_stdout=lambda data: print(data, end=""),
  )

  # Continue the most recent session with a follow-up task
  follow_up = sandbox.commands.run(
      'cd /home/user/repo && prime-agent -c -p "Now implement step 1 of the plan"',
      on_stdout=lambda data: print(data, end=""),
  )

  diff = sandbox.commands.run("cd /home/user/repo && git diff")
  print(diff.stdout)

  sandbox.kill()
  ```
</CodeGroup>

## Build a custom template

If you need to customize the environment (e.g. pre-install dependencies, add config files), build your own template on top of the pre-built `prime` template.

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  // template.ts
  import { Template } from 'e2b'

  export const template = Template()
    .fromTemplate('prime')
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  # template.py
  from e2b import Template

  template = (
      Template()
      .from_template("prime")
  )
  ```
</CodeGroup>

<CodeGroup>
  ```typescript JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  // build.ts
  import { Template, defaultBuildLogger } from 'e2b'
  import { template as primeTemplate } from './template'

  await Template.build(primeTemplate, 'my-prime', {
    cpuCount: 2,
    memoryMB: 2048,
    onBuildLogs: defaultBuildLogger(),
  })
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  # build.py
  from e2b import Template, default_build_logger
  from template import template as prime_template

  Template.build(prime_template, "my-prime",
      cpu_count=2,
      memory_mb=2048,
      on_build_logs=default_build_logger(),
  )
  ```
</CodeGroup>

Run the build script to create the template.

<CodeGroup>
  ```bash JavaScript & TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  npx tsx build.ts
  ```

  ```bash Python theme={"theme":{"light":"github-light","dark":"github-dark-default"}}
  python build.py
  ```
</CodeGroup>

## Related guides

<CardGroup cols={3}>
  <Card title="Sandbox persistence" icon="clock" href="/docs/sandbox/persistence">
    Auto-pause, resume, and manage sandbox lifecycle
  </Card>

  <Card title="Git integration" icon="code-branch" href="/docs/sandbox/git-integration">
    Clone repos, manage branches, and push changes
  </Card>

  <Card title="SSH access" icon="terminal" href="/docs/sandbox/ssh-access">
    Connect to the sandbox via SSH for interactive sessions
  </Card>
</CardGroup>
