safe-bash
Run shell scripts and command-line tools in your application against an explicit filesystem, without launching a host shell. The root and contract posixPath exports, including contracts/node and contracts/node-path, share the portable safe-fs helpers in every runtime, with / as the working directory for resolve and relative.
All command plugins and their factories are available from the root entrypoint in Node, browsers, and Cloudflare Workers.
Import ffmpegCommands from @poe-platform/safe-bash and register
it with shell.use(ffmpegCommands()) for in-memory media conversion and probing. Optional tesseractCommands() and ocrmypdfCommands() from /commands/tesseract and /commands/ocrmypdf add Rust OCR and searchable PDFs in Node.js when the private @poe-platform/tesseract workspace is built and linked locally. See the OCR guide.
Pass cloudflareWorkerLimits() explicitly to bound media work in Workers.
Quickstart
Install in a Node.js 22+ ESM application:
npm install @poe-platform/safe-bash
import { Shell, agentCommands, createMemoryFileSystem } from "@poe-platform/safe-bash";
const fs = createMemoryFileSystem();
const encoder = new TextEncoder();
await fs.mkdir("/work");
await fs.writeFile("/work/names.txt", encoder.encode("Ada\nGrace\nAda\n"));
await fs.writeFile("/work/run.sh", encoder.encode(`#!/bin/sh
set -eu
sort names.txt | uniq > names.sorted.txt
printf 'Hello, %s!\\n' "$1"
cat names.sorted.txt
`));
const shell = new Shell({ fs, cwd: "/work" }).use(agentCommands());
try {
const result = await shell.exec("sh run.sh reader");
if (result.exitCode !== 0) throw new Error(result.stderr);
process.stdout.write(result.stdout);
} finally {
await shell.dispose();
}
Output: Hello, reader!\nAda\nGrace\n. The script, input, and generated
names.sorted.txt stay in memory. Results contain exitCode, stdout, stderr,
stdoutBytes, and stderrBytes; use the byte fields for binary output.
For large output, use await shell.exec(source, { captureOutput: false, stdout, stderr }).
Each sink implements async write(bytes); writes are awaited for backpressure.
This mode creates no stdout/stderr captures or decoded output copies. Results and
hooks retain exit/state metadata but have empty output fields. An omitted sink
discards its stream. The CLI and timeout worker use this mode; the same SDK option
works in Workers and session.exec(). Buffered results remain the default.
Sinks must consume bytes before their write resolves, or copy bytes they retain.
This bounds shell output transport, not arbitrary programs: command substitution,
variables, arrays, arguments, process substitution and individual commands may
retain data. See streaming boundaries.
Each exec() starts fresh shell variables, functions, and working-directory state;
filesystem changes persist in the supplied fs. With the memory filesystem,
relative file access follows working-directory and ancestor renames; pwd -P
reports the moved path while logical PWD stays unchanged until cd.
The invocation-local umask
starts at 0022, accepts octal or symbolic modes, and is inherited by child shells.
Use shell.createSession() to retain shell state, including aliases and set --
arguments, across session.exec() calls. With backgroundJobs: true, session
turns return while background commands run; later turns can use jobs, wait,
kill, and disown. Calls in one session execute in submission order. Live jobs
belong to that session, not its serializable state snapshot. Redirect background
output to files or supply stdout/stderr sinks to receive output after a turn
returns. await session.dispose() cancels remaining work and awaits cleanup;
shell.dispose() also disposes its sessions. Disowning removes a job from
jobs/wait, while disown -h retains it with the nohup mark. Both remain owned
for resource cleanup. Ordinary shell.exec() still drains its children before
returning.
Within a script, exec keeps file redirections open or replaces the current shell
command, including -c to clear its environment and -a to set its argument zero.
read -u FD -t SECONDS reads an open descriptor with a timeout; mapfile -u FD
and readarray -u FD collect its remaining records. readExtension and
mapfileExtension are also available as public factories.
mapfile and readarray reject protected shell arrays before consuming input.
Use caller [depth] to inspect function/source call sites, and
printf '%(%Y-%m-%d)T\n' 1700000000 to format timestamps (-1 means now,
-2 means shell start). Time formatting uses the virtual TZ, defaulting to UTC.
LC_ALL, then LC_TIME, then LANG selects C or US-English (en_US) formats
for %x, %X, and %c; %D and %T retain their fixed numeric formats.
Creation modes use the filesystem's capabilities; advisory modes do not enforce
physical permissions, and the host process mask remains unchanged.
Core, shell, and command imports use Web-standard bytes without installing
globalThis.Buffer. Workers do not need nodejs_compat for this. The legacy
portable-buffer.js bootstrap remains importable but no longer installs a global.
The root uses the portable shell and Fetch transport in every runtime. Import
Shell from @poe-platform/safe-bash/node to opt into Node worker-backed
timeout --kill-after, real filesystem adapters, and Node runtime hosts.
For Node-specific HTTP controls, import createNodeHttpTransport from
@poe-platform/safe-bash/commands/network/node and pass it as transport.
Bash [[ value =~ pattern ]] and BASH_REMATCH also work in browsers and
Workers, using the same ERE engine with cooperative cancellation and shared
resource accounting.
AES ZIP encryption and decryption also work in browsers and Workers. The
@poe-platform/safe-bash/trap entry selects the portable signal catalog there.
For an application that selects its commands, import Shell and CommandRegistry
from @poe-platform/safe-bash/shell, then compose plugins with shell.use():
import { Shell } from "@poe-platform/safe-bash/shell";
import { pdfinfoCommands } from "@poe-platform/safe-bash/commands/pdfinfo";
const shell = new Shell({ fs }).use(pdfinfoCommands());
Python and LLM plugins have independent commands/python and commands/llm
entrypoints. Use pythonExecutorCommands({ createExecutor }) from
commands/python/executor (or
createPythonExecutorCommands for command definitions) when supplying an
interpreter: these exports exclude the default artifact renderer and its PDF
engines. pythonCommands() retains the default version probes and document
rendering; its existing options overload remains compatible. Select spreadsheet
formats through ssconvert/commands with
ssconvert/formats/csv and ssconvert/formats/xlsx; the compatibility
commands/ssconvert entry retains its full format set. The aggregate root/core
exports and the explicit @poe-platform/safe-bash/full aggregate remain available
with the existing agentCommands() defaults;
keep existing explicit plugins and their limits when migrating an application.
For a lightweight registry, import baseAgentCommands and
createBoundedRegexProvider from @poe-platform/safe-bash/registry with the same
family limits and regex options. It preserves the base shell inventory without
the default registry’s GH/Git integration; add ghCommands explicitly where needed.
The registry subpath supports ESM splitting without visiting the full aggregate.
Configure the included dd command through bytes.dd on agentCommands() or
baseAgentCommands(), or through dd on byteCommands(). These options accept
the command's block, buffer, transfer and read-operation limits.
Its exports do not select the optional
op, node or safejs plugins; add those only through their command entrypoints.
Only registered commands are available; adding search commands does not enable unrelated tools.
agentCommands() includes convenience tools such as bc, fd, sponge, less, and more by default. Pass muscleMemory: false to omit that family; individual command plugins remain available. Use moreCommands() to register only more; lessCommands() and pagerCommands() retain both pagers. Pager input limits are disabled by default; set maxInputBytes to opt in.
Removing a registered command changes availability, while shared family code may
remain bundled. Splitting dynamic
imports changes initialization timing: every uploaded static chunk and Wasm asset
still counts toward a Worker's uncompressed size.
Supported features and commands
The root and core exports provide spreadsheet, PDF, media, office, and Git
commands using static metadata, loading their implementations on first execution.
agentCommands() includes the portable command suite, including YAML, CSV, HTML,
PDF, media, office, Mermaid, and virtual op commands. Git remains an explicit
plugin, as do network and external runtime capabilities. For a shell without
agentCommands(), select individual commands or families:
import { optionalCommands } from "@poe-platform/safe-bash";
shell.use(optionalCommands({ commands: ["pdftotext", "ffprobe"] }));
// Alternatively: optionalCommands({ families: ["pdfinfo", "ssconvert"] })
// Full profile: agentCommands() plus optionalCommands({ profile: "full" })
The full optional profile fills missing commands and preserves existing dedicated
registrations, including configured default commands. Pass replace: true to
replace existing registrations explicitly.
Existing root factories such as ffmpegCommands() and createPdftotextCommand()
also defer loading. The advanced command subpaths retain their eager SDK and
synchronous APIs. Selected ssconvert format factories remain supported through
configuration.ssconvert.formats; no format adapter is replaced.
Concurrent first calls share one code-load promise per family. Failed loader
calls retry on the next invocation. Host module caches can retain evaluation
errors; correcting a broken bundled module can require restarting the host. Cancellation stops that caller's wait and prevents late
dispatch; it does not cancel another caller's shared code import. Factories and
execution contexts are invocation-local, and Git shares compiled Wasm code but
creates separate mutable instances. Existing filesystem, streams, host bindings,
limits and cleanup remain with the original command context. Configuration
validation in deferred factories occurs at first execution.
Static dynamic-import chunks and Wasm assets still count toward Cloudflare's
total uncompressed upload size. Deferring evaluation reduces startup work;
splitting files alone does not remove deployment bytes. Hosts can parse or
compile statically declared assets before execution; the loader defers JavaScript
evaluation and mutable engine initialization. The maintained
tests/integration/lazy-loading.test.mjs qualifies source and installed profiles
in workerd and reports cold runtime/setup, first use, repeat use and cleanup
measurements. Python uses an injected asynchronous executor in this loader
regression; LLM uses a synthetic provider, without external model calls.
All private command plugins are available from @poe-platform/safe-bash/core in portable browser and workerd environments. Each command exposes its plugin, create<Name>Commands, create<Name>Command, <Name>CommandsOptions, and <Name>Limits; factories construct commands without registering them. Standalone sed, awk, find, diff, patch, tar, zip, unzip, gzip, curl, and wget imports use @poe-platform/safe-bash/commands/<name>. Standalone network factories deny requests unless an authorize callback permits them.
Chain .use(plugin).register(command, { replace: true }) to replace a plugin command. Registration waits for pending plugin setup in call order; setup and queued registration errors surface through exec(). Replacements for true, false, and pwd also apply to shell calls; builtin <name> explicitly runs the shell builtin.
Shell syntax