Skip to content

Advanced Mastra AI coding agent with secure E2B sandbox execution, comprehensive file management, and multi-language support for Python, JavaScript, and TypeScript development workflows

Notifications You must be signed in to change notification settings

astickleyid/template-coding-agent

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

E2B Code Execution Agent

An advanced Mastra template that provides a coding agent capable of planning, writing, executing, and iterating on code in secure, isolated E2B sandboxes with comprehensive file management and development workflow capabilities.

Overview

This template demonstrates how to build an AI coding assistant that can work with real development environments. The agent can create sandboxes, manage files and directories, execute code in multiple languages, and monitor development workflows - all within secure, isolated E2B environments.

Features

  • Secure Code Execution: Run Python, JavaScript, and TypeScript code in isolated E2B sandboxes
  • Complete File Management: Create, read, write, delete files and directories with batch operations
  • Multi-Language Support: Execute code in Python, JavaScript, and TypeScript environments
  • Live Development Monitoring: Watch directory changes and monitor development workflows
  • Command Execution: Run shell commands, install packages, and manage dependencies
  • Memory System: Persistent conversation memory with semantic recall and working memory
  • Personalization Layer: Configure agent identity, preferences, and a catalog of repeatable workflows
  • Desktop Launcher: Electron-based desktop application for starting/stopping the agent without the terminal
  • Development Workflows: Professional development patterns with build automation

Prerequisites

  • Node.js 20 or higher
  • E2B API key (sign up at e2b.dev)
  • OpenAI API key

Setup

  1. Clone and install dependencies:

    git clone https://github.com/mastra-ai/template-coding-agent.git
    cd template-coding-agent
    npm install
    # or: pnpm install
  2. Set up environment variables:

    cp .env.example .env
    # Edit .env and add your API keys
    E2B_API_KEY="your-e2b-api-key-here"
    OPENAI_API_KEY="your-openai-api-key-here"
  3. Check your environment:

    npm run doctor

    The doctor script highlights missing dependencies or API keys before you launch the agent.

  4. Start the agent (pick one):

    • CLI: npm run dev for hot-reload development or npm run start for production mode.
    • Desktop App: npm run desktop to open the Electron launcher. Provide your API keys once and start/stop the agent with buttons. Output streaming and status updates are surfaced in the UI.
  5. Package a desktop build (optional):

    npm run desktop:package

    This produces a platform-specific build in the dist/ directory using electron-builder.

Architecture

Core Components

Coding Agent (src/mastra/agents/coding-agent.ts)

The main agent with comprehensive development capabilities:

  • Sandbox Management: Creates and manages isolated execution environments
  • Code Execution: Runs code with real-time output capture
  • File Operations: Complete CRUD operations for files and directories
  • Development Monitoring: Watches for changes and monitors workflows
  • Memory Integration: Maintains conversation context and project history
  • Personal Profile: Dynamically incorporates preferences defined in personal-config.ts

E2B Tools (src/mastra/tools/e2b.ts)

Complete toolkit for sandbox interaction:

Sandbox Management:

  • createSandbox - Initialize new isolated environments
  • Connection management with timeout handling

Code Execution:

  • runCode - Execute Python, JavaScript, TypeScript code
  • Real-time output capture and error handling
  • Environment variable and timeout configuration

File Operations:

  • writeFile - Create individual files
  • writeFiles - Batch create multiple files for project setup
  • readFile - Read file contents for analysis and validation
  • listFiles - Explore directory structures
  • deleteFile - Clean up files and directories
  • createDirectory - Set up project structures

File Information & Monitoring:

  • getFileInfo - Get detailed file metadata
  • checkFileExists - Validate file existence for conditional logic
  • getFileSize - Monitor file sizes and track changes
  • watchDirectory - Live monitoring of file system changes

Development Workflow:

  • runCommand - Execute shell commands, build scripts, package management
  • runCustomCommand - Trigger user-defined workflows stored in personal-config.ts

Memory System

The agent includes a configured memory system:

  • Thread Management: Automatic conversation title generation
  • Semantic Recall: Search through previous interactions
  • Working Memory: Maintains context across interactions
  • Vector Storage: Semantic search capabilities with LibSQLVector

Configuration

Environment Variables

E2B_API_KEY=your_e2b_api_key_here
OPENAI_API_KEY=your_openai_api_key_here

Personalization & Custom Commands

Fine-tune the assistant without editing core agent code by updating src/mastra/agents/personal-config.ts.

export const personalAgentConfig = {
  name: 'My Personal Coding Companion',
  tagline: 'A persistent AI partner tailored to your workflows.',
  mission: 'Describe the long-term goals for the agent.',
  preferences: {
    languages: ['TypeScript', 'Python'],
    technologies: ['Node.js', 'React'],
    developmentStyle: ['Prefer TDD', 'Document architectural decisions'],
  },
  memoryStrategy: {
    longTermSummary: 'What should be remembered across sessions.',
    workingMemoryGuidelines: ['Snapshot progress at the end of each session.'],
  },
  customCommands: [
    {
      id: 'start-dev',
      label: 'Start Dev Server',
      description: 'Launch the development server inside the sandbox.',
      command: 'pnpm run dev',
    },
  ],
};

Key capabilities provided by the configuration file:

  • Agent identity — control tone, mission, and project focus.
  • Preference sets — inform the agent about favored languages, tools, and delivery style.
  • Memory strategy — guide how long-term and short-term context should be stored.
  • Custom commands — register reusable shell commands that can be triggered with the runCustomCommand tool using a commandId.

Feel free to extend the configuration with additional custom commands or memory options; the agent automatically reads the updated details on startup.

Desktop Launcher

The Electron desktop app wraps the same Mastra agent so you can run it without the terminal:

  1. Install dependencies and run npm run doctor to verify prerequisites.
  2. Launch the desktop shell with npm run desktop.
  3. Enter your API keys once—the app stores them locally using the operating system's application storage.
  4. Start or stop the agent with a single click. Live logs and status updates stream into the UI so you can monitor the session in real time.
  5. Package a distributable build with npm run desktop:package when you are ready to share it across machines.

The launcher proxies your chosen mode (mastra dev for development or mastra start for production) and forwards environment variables so the agent runs exactly as it does via the CLI.

Common Issues

"E2B_API_KEY is not set"

  • Make sure you've set the environment variable
  • Check that your API key is valid and has sufficient credits
  • Verify your E2B account is properly configured

"Sandbox creation failed"

  • Check your E2B API key and account status
  • Ensure you haven't exceeded sandbox limits
  • Verify network connectivity to E2B services

"Code execution timeout"

  • Increase timeout values for long-running operations
  • Break down complex operations into smaller steps
  • Monitor resource usage and optimize code

"File operation errors"

  • Validate file paths and permissions
  • Check sandbox file system limits
  • Ensure directories exist before file operations

"Agent stopping with tool-call reason"

  • Increase maxSteps in the agent configuration

Development

Project Structure

src/mastra/
      agents/
        coding-agent.ts              # Main coding agent with development capabilities
        personal-config.ts           # User-editable persona, memory, and command catalog
      tools/
        e2b.ts                      # Complete E2B sandbox interaction toolkit
        custom-commands.ts          # Tool for invoking reusable workflows
      index.ts                        # Mastra configuration with storage and logging

License

This project is part of the Mastra ecosystem and follows the same licensing terms.

About

Advanced Mastra AI coding agent with secure E2B sandbox execution, comprehensive file management, and multi-language support for Python, JavaScript, and TypeScript development workflows

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 72.5%
  • JavaScript 18.5%
  • CSS 5.1%
  • HTML 3.9%