1772117990
2026-02-26 13:16:00
TypeScript で記述された、インメモリ仮想ファイル システムを備えたシミュレートされた bash 環境。
安全なサンドボックス化された bash 環境を必要とする AI エージェント向けに設計されています。
オプションのネットワークアクセスをサポート curl デフォルトで安全な URL フィルタリングを使用します。
注記: これはベータ版ソフトウェアです。ご自身の責任で使用し、フィードバックをお寄せください。
- シェルは、提供されたファイル システムにのみアクセスできます。
- 実行は無限ループや再帰から保護されます。ただし、Bash は入力からの DOS に対して完全に堅牢ではありません。これに対して堅牢である必要がある場合は、OS レベルでプロセス分離を使用してください。
- バイナリや WASM さえも本質的にサポートされていません (使用 ヴァーセルサンドボックス 完全な VM が必要な場合は、同様の製品を使用します)。
- デフォルトではネットワークアクセスはありません。
- ネットワーク アクセスを有効にすることはできますが、リクエストは URL プレフィックス許可リストおよび HTTP メソッド許可リストと照合してチェックされます。見る ネットワークアクセス 詳細については
import { Bash } from "just-bash";
const env = new Bash();
await env.exec('echo "Hello" > greeting.txt');
const result = await env.exec("cat greeting.txt");
console.log(result.stdout); // "Hellon"
console.log(result.exitCode); // 0
console.log(result.env); // Final environment after execution
それぞれ exec() は分離されています。環境変数、関数、CWD は呼び出しをまたいで持続しません (ファイルシステムは持続します)。
const env = new Bash({
files: { "/data/file.txt": "content" }, // Initial files
env: { MY_VAR: "value" }, // Initial environment
cwd: "/app", // Starting directory (default: /home/user)
executionLimits: { maxCallDepth: 50 }, // See "Execution Protection"
});
// Per-exec overrides
await env.exec("echo $TEMP", { env: { TEMP: "value" }, cwd: "/tmp" });
ファイル値は関数 (同期または非同期) にすることができます。この関数は最初の読み取り時に呼び出され、結果がキャッシュされます。ファイルが読み取られる前に書き込まれた場合、関数は呼び出されません。
const env = new Bash({
files: {
"/data/config.json": () => JSON.stringify({ key: "value" }),
"/data/remote.txt": async () => (await fetch("https://example.com")).text(),
"/data/static.txt": "always loaded",
},
});
これは、必要のない大規模なコンテンツや計算コストのかかるコンテンツに役立ちます。
以下を使用して、独自の TypeScript コマンドで just-bash を拡張します。 defineCommand:
import { Bash, defineCommand } from "just-bash";
const hello = defineCommand("hello", async (args, ctx) => {
const name = args[0] || "world";
return { stdout: `Hello, ${name}!n`, stderr: "", exitCode: 0 };
});
const upper = defineCommand("upper", async (args, ctx) => {
return { stdout: ctx.stdin.toUpperCase(), stderr: "", exitCode: 0 };
});
const bash = new Bash({ customCommands: [hello, upper] });
await bash.exec("hello Alice"); // "Hello, Alice!n"
await bash.exec("echo 'test' | upper"); // "TESTn"
カスタムコマンドは完全に受信します CommandContext にアクセスできる fs、 cwd、 env、 stdin、 そして exec サブコマンドを実行するためのものです。
4 つのファイルシステム実装が利用可能です。
インメモリFs (デフォルト) – 純粋なインメモリ ファイル システム、ディスク アクセスなし:
import { Bash } from "just-bash";
const env = new Bash(); // Uses InMemoryFs by default
オーバーレイFs – 実ディレクトリへのコピーオンライト。読み取りはディスクから行われ、書き込みはメモリに残ります。
import { Bash } from "just-bash";
import { OverlayFs } from "just-bash/fs/overlay-fs";
const overlay = new OverlayFs({ root: "/path/to/project" });
const env = new Bash({ fs: overlay, cwd: overlay.getMountPoint() });
await env.exec("cat package.json"); // reads from disk
await env.exec('echo "modified" > package.json'); // stays in memory
読み取り書き込みFs – 実ディレクトリへの直接読み取り/書き込みアクセス。エージェントがディスクに書き込むことができるようにする場合は、これを使用します。
import { Bash } from "just-bash";
import { ReadWriteFs } from "just-bash/fs/read-write-fs";
const rwfs = new ReadWriteFs({ root: "/path/to/sandbox" });
const env = new Bash({ fs: rwfs });
await env.exec('echo "hello" > file.txt'); // writes to real filesystem
マウント可能なFs – 複数のファイルシステムを異なるパスにマウントします。読み取り専用ファイルシステムと読み取り/書き込みファイルシステムを統合した名前空間に統合します。
import { Bash, MountableFs, InMemoryFs } from "just-bash";
import { OverlayFs } from "just-bash/fs/overlay-fs";
import { ReadWriteFs } from "just-bash/fs/read-write-fs";
const fs = new MountableFs({ base: new InMemoryFs() });
// Mount read-only knowledge base
fs.mount("/mnt/knowledge", new OverlayFs({ root: "/path/to/knowledge", readOnly: true }));
// Mount read-write workspace
fs.mount("/home/agent", new ReadWriteFs({ root: "/path/to/workspace" }));
const bash = new Bash({ fs, cwd: "/home/agent" });
await bash.exec("ls /mnt/knowledge"); // reads from knowledge base
await bash.exec("cp /mnt/knowledge/doc.txt ./"); // cross-mount copy
await bash.exec('echo "notes" > notes.txt'); // writes to workspace
コンストラクターでマウントを構成することもできます。
import { MountableFs, InMemoryFs } from "just-bash";
import { OverlayFs } from "just-bash/fs/overlay-fs";
import { ReadWriteFs } from "just-bash/fs/read-write-fs";
const fs = new MountableFs({
base: new InMemoryFs(),
mounts: [
{ mountPoint: "/data", filesystem: new OverlayFs({ root: "/shared/data" }) },
{ mountPoint: "/workspace", filesystem: new ReadWriteFs({ root: "/tmp/work" }) },
],
});
AI エージェントの場合は、次を使用します。 bash-tool これは just-bash 用に最適化されており、すぐに使用できる機能を提供します。 AI SDK 道具:
import { createBashTool } from "bash-tool";
import { generateText } from "ai";
const bashTool = createBashTool({
files: { "/data/users.json": '[{"name": "Alice"}, {"name": "Bob"}]' },
});
const result = await generateText({
model: "anthropic/claude-sonnet-4",
tools: { bash: bashTool },
prompt: "Count the users in /data/users.json",
});
を参照してください。 bash ツールのドキュメント 詳細と例については、こちらをご覧ください。
Bash が提供するのは、 Sandbox API互換のクラス @vercel/sandbox実装を簡単に交換できるようになります。 Bash から始めて、完全な VM の能力が必要な場合 (ノード、Python、またはカスタム バイナリを実行する場合など)、実際のサンドボックスに切り替えることができます。
import { Sandbox } from "just-bash";
// Create a sandbox instance
const sandbox = await Sandbox.create({ cwd: "/app" });
// Write files to the virtual filesystem
await sandbox.writeFiles({
"/app/script.sh": 'echo "Hello World"',
"/app/data.json": '{"key": "value"}',
});
// Run commands and get results
const cmd = await sandbox.runCommand("bash /app/script.sh");
const output = await cmd.stdout(); // "Hello Worldn"
const exitCode = (await cmd.wait()).exitCode; // 0
// Read files back
const content = await sandbox.readFile("/app/data.json");
// Create directories
await sandbox.mkDir("/app/logs", { recursive: true });
// Clean up (no-op for Bash, but API-compatible)
await sandbox.stop();
グローバルにインストールした後 (npm install -g just-bash)、を使用します。 just-bash の安全な代替としてのコマンド bash AI エージェントの場合:
# Execute inline script
just-bash -c 'ls -la && cat package.json | head -5'
# Execute with specific project root
just-bash -c 'grep -r "TODO" src/' --root /path/to/project
# Pipe script from stdin
echo 'find . -name "*.ts" | wc -l' | just-bash
# Execute a script file
just-bash ./scripts/deploy.sh
# Get JSON output for programmatic use
just-bash -c 'echo hello' --json
# Output: {"stdout":"hellon","stderr":"","exitCode":0}
CLI は OverlayFS を使用します。読み取りは実際のファイルシステムから行われますが、書き込みはすべてメモリ内に留まり、実行後に破棄されます。プロジェクトのルートは次の場所にマウントされます。 /home/user/project。
オプション:
-c– 引数からスクリプトを実行--root– ルートディレクトリ(デフォルト:カレントディレクトリ)--cwd– サンドボックス内の作業ディレクトリ-e, --errexit– 最初のエラーで終了--json– JSONとして出力
インタラクティブ シェルでは、デフォルトで完全なインターネット アクセスが有効になっており、以下を使用できます。 curl 任意の URL からデータを取得します。使用 --no-network これを無効にするには:
cat、 cp、 file、 ln、 ls、 mkdir、 mv、 readlink、 rm、 rmdir、 split、 stat、 touch、 tree
awk、 base64、 column、 comm、 cut、 diff、 expand、 fold、 grep (+ egrep、 fgrep)、 head、 join、 md5sum、 nl、 od、 paste、 printf、 rev、 rg、 sed、 sha1sum、 sha256sum、 sort、 strings、 tac、 tail、 tr、 unexpand、 uniq、 wc、 xargs
jq (JSON)、 python3/python (Pyodide 経由の Python、オプトインが必要)、 sqlite3 (SQLite)、 xan (CSV)、 yq (YAML/XML/TOML/CSV)
gzip (+ gunzip、 zcat)、 tar
basename、 cd、 dirname、 du、 echo、 env、 export、 find、 hostname、 printenv、 pwd、 tee
alias、 bash、 chmod、 clear、 date、 expr、 false、 help、 history、 seq、 sh、 sleep、 time、 timeout、 true、 unalias、 which、 whoami
curl、 html-to-markdown
すべてのコマンドのサポート --help 使用方法については。
- パイプ:
cmd1 | cmd2 - リダイレクト:
>、>>、2>、2>&1、 - Command chaining:
&&、||、; - 変数:
$VAR、${VAR}、${VAR:-default} - 位置パラメータ:
$1、$2、$@、$# - グロブパターン:
*、?、[...] - If ステートメント:
if COND; then CMD; elif COND; then CMD; else CMD; fi - 機能:
function name { ... }またはname() { ... } - ローカル変数:
local VAR=value - ループ:
for、while、until - シンボリックリンク:
ln -s target link - ハードリンク:
ln target link
オプションを指定せずに作成すると、Bash は Unix のようなディレクトリ構造を提供します。
/home/user– デフォルトの作業ディレクトリ (および$HOME)/bin– すべての組み込みコマンドのスタブが含まれています/usr/bin– 追加のバイナリ ディレクトリ/tmp– 一時ファイルのディレクトリ
コマンドはパスによって呼び出すことができます (例: /bin/ls)または名前で。
ネットワーク アクセス (および curl コマンド) は、セキュリティのためにデフォルトで無効になっています。有効にするには、 network オプション:
// Allow specific URLs with GET/HEAD only (safest)
const env = new Bash({
network: {
allowedUrlPrefixes: [
"https://api.github.com/repos/myorg/",
"https://api.example.com",
],
},
});
// Allow specific URLs with additional methods
const env = new Bash({
network: {
allowedUrlPrefixes: ["https://api.example.com"],
allowedMethods: ["GET", "HEAD", "POST"], // Default: ["GET", "HEAD"]
},
});
// Allow all URLs and methods (use with caution)
const env = new Bash({
network: { dangerouslyAllowFullInternetAccess: true },
});
注記: の curl コマンドはネットワークが設定されている場合にのみ存在します。ネットワーク設定がなければ、 curl 「コマンドが見つかりません」を返します。
Pyodide による Python サポートは、追加のセキュリティ面のためオプトインです。明示的に有効にしますが、次のリスクに注意してください。
const env = new Bash({
python: true,
});
// Execute Python code
await env.exec('python3 -c "print(1 + 2)"');
// Run Python scripts
await env.exec('python3 script.py');
注記: の python3 そして python コマンドは次の場合にのみ存在します。 python: true 設定されています。 Python はブラウザ環境では使用できません。
の sqlite3 このコマンドは、完全にサンドボックス化されており、実際のファイルシステムにアクセスできない sql.js (WASM ベースの SQLite) を使用します。
const env = new Bash();
// Query in-memory database
await env.exec('sqlite3 :memory: "SELECT 1 + 1"');
// Query file-based database
await env.exec('sqlite3 data.db "SELECT * FROM users"');
注記: SQLiteはブラウザ環境では利用できません。クエリは、暴走クエリによって実行がブロックされるのを防ぐために、構成可能なタイムアウト (デフォルト: 5 秒) を使用してワーカー スレッドで実行されます。
許可リストでは次のことが強制されます。
- 原点マッチング: URL は正確なオリジン (スキーム + ホスト + ポート) と一致する必要があります。
- パスプレフィックス: 指定されたプレフィックスで始まるパスのみが許可されます
- HTTPメソッドの制限: デフォルトでは GET と HEAD のみ (構成
allowedMethodsさらに詳しく) - リダイレクト保護: 許可されていない URL へのリダイレクトはブロックされます
# Fetch and process data
curl -s https://api.example.com/data | grep pattern
# Download and convert HTML to Markdown
curl -s https://example.com | html-to-markdown
# POST JSON data
curl -X POST -H "Content-Type: application/json"
-d '{"key":"value"}' https://api.example.com/endpoint
Bash は、構成可能な制限によって無限ループと深い再帰から保護します。
const env = new Bash({
executionLimits: {
maxCallDepth: 100, // Max function recursion depth
maxCommandCount: 10000, // Max total commands executed
maxLoopIterations: 10000, // Max iterations per loop
maxAwkIterations: 10000, // Max iterations in awk programs
maxSedIterations: 10000, // Max iterations in sed scripts
},
});
すべての制限には適切なデフォルト値があります。エラー メッセージには、制限を増やすためのヒントが含まれています。スクリプトが意図的にそれを超えている場合は、自由に増やしてください。
bash スクリプトを AST に解析し、変換プラグインを実行し、実行可能な bash にシリアル化します。実行前のスクリプトの計測 (コマンドごとの stdout/stderr のキャプチャなど) やスクリプトの分析 (コマンド名の抽出など) に役立ちます。
import { Bash, BashTransformPipeline, TeePlugin, CommandCollectorPlugin } from "just-bash";
// Standalone pipeline — output can be run by any shell
const pipeline = new BashTransformPipeline()
.use(new TeePlugin({ outputDir: "/tmp/logs" }))
.use(new CommandCollectorPlugin());
const result = pipeline.transform("echo hello | grep hello");
result.script; // transformed bash string
result.metadata.commands; // ["echo", "grep", "tee"]
// Integrated API — exec() auto-applies transforms and returns metadata
const bash = new Bash();
bash.registerTransformPlugin(new CommandCollectorPlugin());
const execResult = await bash.exec("echo hello | grep hello");
execResult.metadata?.commands; // ["echo", "grep"]
見る src/transform/README.md 完全な API、組み込みプラグイン、カスタム プラグインの作成方法については、こちらをご覧ください。
pnpm test # Run tests in watch mode
pnpm test:run # Run tests once
pnpm typecheck # Type check without emitting
pnpm build # Build TypeScript
pnpm shell # Run interactive shell
AI エージェントの場合は、次の使用をお勧めします。 bash-tool これは just-bash 用に最適化されており、追加のガイダンスを提供します。 AGENTS.md:
cat node_modules/bash-tool/dist/AGENTS.md
アパッチ-2.0
#GitHub #vercellabsjustbash #エージェント用の #Bash