Documentation
¶
Overview ¶
Package gbash provides the primary embedding API for the gbash sandbox.
The root package is the intended entry point for most callers. It exposes the runtime, session, execution request/result types, and the opinionated configuration helpers that cover the common embedding cases:
- create an isolated in-memory sandbox with New
- mount a real host directory into the sandbox with WithWorkspace
- enable allowlisted HTTP access for curl with WithHTTPAccess or WithNetwork
- customize the registry, policy, or filesystem with explicit options when you need lower-level control
Most embedders should only import the root package. Advanced integrations may also import the supported extension packages:
- commands for custom command authorship and registry customization
- fs for custom filesystem backends and factories
- network for sandbox HTTP client customization
- policy for sandbox policy implementations
- trace for structured execution event consumption when callers opt in to tracing on the runtime
Packages under internal/ and other undocumented subpackages are not public API.
Index ¶
- Constants
- func DefaultRegistry() *commands.Registry
- type Config
- type ExecutionRequest
- type ExecutionResult
- type FileSystemConfig
- func CustomFileSystem(factory gbfs.Factory, workingDir string) FileSystemConfig
- func HostDirectoryFileSystem(root string, opts HostDirectoryOptions) FileSystemConfig
- func InMemoryFileSystem() FileSystemConfig
- func MountableFileSystem(opts MountableFileSystemOptions) FileSystemConfig
- func ReadWriteDirectoryFileSystem(root string, opts ReadWriteDirectoryOptions) FileSystemConfig
- func SeededInMemoryFileSystem(files gbfs.InitialFiles) FileSystemConfig
- type HostDirectoryOptions
- type InteractiveRequest
- type InteractiveResult
- type LogCallback
- type LogEvent
- type LogKind
- type Method
- type MountableFileSystemOptions
- type NetworkConfig
- type Option
- func WithBaseEnv(env map[string]string) Option
- func WithConfig(cfg *Config) Option
- func WithFileSystem(cfg FileSystemConfig) Option
- func WithHTTPAccess(prefixes ...string) Option
- func WithLogger(callback LogCallback) Option
- func WithNetwork(cfg *NetworkConfig) Option
- func WithNetworkClient(client network.Client) Option
- func WithPolicy(p policy.Policy) Option
- func WithRegistry(registry commands.CommandRegistry) Option
- func WithTracing(cfg TraceConfig) Option
- func WithWorkingDir(dir string) Option
- func WithWorkspace(dir string) Option
- type ReadWriteDirectoryOptions
- type Runtime
- type Session
- type TraceConfig
- type TraceMode
Constants ¶
const ( // MethodGet allows HTTP GET requests. MethodGet = network.MethodGet // MethodHead allows HTTP HEAD requests. MethodHead = network.MethodHead // MethodPost allows HTTP POST requests. MethodPost = network.MethodPost // MethodPut allows HTTP PUT requests. MethodPut = network.MethodPut // MethodDelete allows HTTP DELETE requests. MethodDelete = network.MethodDelete // MethodPatch allows HTTP PATCH requests. MethodPatch = network.MethodPatch // MethodOptions allows HTTP OPTIONS requests. MethodOptions = network.MethodOptions )
const ( // DefaultWorkspaceMountPoint is the default sandbox mount point used by // [WithWorkspace] and [HostDirectoryFileSystem]. DefaultWorkspaceMountPoint = gbfs.DefaultHostVirtualRoot // DefaultHostFileReadBytes is the default per-file read cap used when a host // directory is mounted into the sandbox. DefaultHostFileReadBytes = gbfs.DefaultHostMaxFileReadBytes )
const ( // TraceOff disables structured execution events. TraceOff = internalruntime.TraceOff // TraceRedacted enables structured events with argv redaction for // secret-bearing values. This is the recommended mode for agent workloads. TraceRedacted = internalruntime.TraceRedacted // TraceRaw enables full structured events without argv redaction. // // This mode is unsafe for shared logs or centralized telemetry unless the // embedder controls retention and sink access tightly. TraceRaw = internalruntime.TraceRaw )
const ( // LogExecStart fires before the shell engine begins execution. LogExecStart = internalruntime.LogExecStart // LogStdout carries the final captured stdout for one execution. LogStdout = internalruntime.LogStdout // LogStderr carries the final captured stderr for one execution. LogStderr = internalruntime.LogStderr // LogExecFinish fires when execution completes normally, including shell // exit statuses and timeout/cancel control outcomes. LogExecFinish = internalruntime.LogExecFinish // LogExecError fires when gbash returns an unexpected runtime error rather // than a normal shell exit status. LogExecError = internalruntime.LogExecError )
Variables ¶
This section is empty.
Functions ¶
func DefaultRegistry ¶
DefaultRegistry returns a registry populated with gbash's built-in commands.
Callers can register additional custom commands onto the returned registry before passing it to WithRegistry.
Types ¶
type Config ¶
type Config struct {
// FileSystem controls how each session gets its sandbox filesystem and what
// working directory new sessions start in.
FileSystem FileSystemConfig
// Registry contains the commands that can be executed inside the sandbox.
// When nil, the default built-in registry is used.
Registry commands.CommandRegistry
// Policy governs path access, command limits, and other sandbox checks.
// When nil, the default static policy is used.
Policy policy.Policy
// BaseEnv provides the base environment visible to each execution before any
// per-request environment overrides are applied.
BaseEnv map[string]string
// Network configures the built-in HTTP client used by the curl command. When
// nil and NetworkClient is also nil, curl is not registered in the sandbox.
Network *NetworkConfig
// NetworkClient replaces the built-in HTTP client. This is the advanced
// escape hatch for tests and custom transports.
NetworkClient network.Client
// Tracing controls structured execution events. Tracing is off by default.
// When enabled, [ExecutionResult.Events] is populated for non-interactive
// executions and OnEvent receives events for both non-interactive and
// interactive runs.
Tracing TraceConfig
// Logger receives top-level execution lifecycle events. Logging is off by
// default.
Logger LogCallback
}
Config describes the complete gbash runtime configuration.
The zero value is useful: it creates the default in-memory sandbox rooted at /home/agent with the default command registry and the default static policy.
Most callers should prefer New with a small number of option helpers such as WithWorkspace, WithHTTPAccess, WithRegistry, or WithBaseEnv. This struct is provided for callers that want to construct a configuration value explicitly before handing it to WithConfig.
type ExecutionRequest ¶
type ExecutionRequest struct {
Name string
Interpreter string
PassthroughArgs []string
ScriptPath string
Script string
Args []string
StartupOptions []string
Env map[string]string
WorkDir string
Timeout time.Duration
ReplaceEnv bool
Interactive bool
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
ExecutionRequest describes a single shell execution.
Callers usually populate [ExecutionRequest.Script] and optionally provide stdin, environment overrides, or a working directory override.
type ExecutionResult ¶
type ExecutionResult struct {
ExitCode int
ShellExited bool
Stdout string
Stderr string
ControlStderr string
FinalEnv map[string]string
StartedAt time.Time
FinishedAt time.Time
Duration time.Duration
// Events contains structured execution events when tracing is enabled on the
// runtime. It is empty by default.
Events []trace.Event
StdoutTruncated bool
StderrTruncated bool
}
ExecutionResult captures the output, exit status, timing, and optional trace events produced by a shell execution.
type FileSystemConfig ¶
type FileSystemConfig struct {
// Factory builds the filesystem instance for a new session.
Factory gbfs.Factory
// WorkingDir is the directory new sessions start in.
WorkingDir string
}
FileSystemConfig describes how gbash provisions a session filesystem.
Callers rarely need to populate this struct directly. Prefer the helper constructors InMemoryFileSystem, SeededInMemoryFileSystem, HostDirectoryFileSystem, MountableFileSystem, ReadWriteDirectoryFileSystem, and CustomFileSystem, and then apply the result with WithFileSystem.
func CustomFileSystem ¶
func CustomFileSystem(factory gbfs.Factory, workingDir string) FileSystemConfig
CustomFileSystem wires an arbitrary filesystem factory into the runtime.
This is the low-level escape hatch for callers that want to seed a custom filesystem backend or provide their own persistence model.
func HostDirectoryFileSystem ¶
func HostDirectoryFileSystem(root string, opts HostDirectoryOptions) FileSystemConfig
HostDirectoryFileSystem mounts a real host directory into the sandbox under a writable in-memory overlay.
The mounted host tree is read-only. All writes, deletes, and command stubs live in the in-memory upper layer, so shell activity never mutates the host directory directly.
func InMemoryFileSystem ¶
func InMemoryFileSystem() FileSystemConfig
InMemoryFileSystem returns the default mutable sandbox filesystem configuration.
This is the same filesystem layout gbash uses when New is called without a filesystem option.
func MountableFileSystem ¶
func MountableFileSystem(opts MountableFileSystemOptions) FileSystemConfig
MountableFileSystem returns a multi-mount filesystem configuration.
func ReadWriteDirectoryFileSystem ¶
func ReadWriteDirectoryFileSystem(root string, opts ReadWriteDirectoryOptions) FileSystemConfig
ReadWriteDirectoryFileSystem mounts a real host directory as the mutable sandbox root.
This is the closest gbash equivalent to just-bash's ReadWriteFs: sandbox paths are rooted at "/", sessions start at "/", and writes persist directly to the host directory.
func SeededInMemoryFileSystem ¶
func SeededInMemoryFileSystem(files gbfs.InitialFiles) FileSystemConfig
SeededInMemoryFileSystem returns an in-memory filesystem configuration preloaded with the provided files.
type HostDirectoryOptions ¶
type HostDirectoryOptions struct {
// MountPoint is the sandbox path where the host directory should appear.
// When empty, [DefaultWorkspaceMountPoint] is used.
MountPoint string
// MaxFileReadBytes limits the size of individual regular files that may be
// read from the host directory. When zero or negative, the default host read
// cap is used.
MaxFileReadBytes int64
}
HostDirectoryOptions controls how a real host directory is mounted into the sandbox.
The mounted directory is always read-only from the host's perspective. gbash layers an in-memory writable upper filesystem on top so the shell can create, overwrite, and delete files without mutating the host tree.
type InteractiveRequest ¶
type InteractiveRequest struct {
Name string
Args []string
StartupOptions []string
Env map[string]string
WorkDir string
ReplaceEnv bool
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
InteractiveRequest describes an interactive shell session.
type InteractiveResult ¶
type InteractiveResult struct {
ExitCode int
}
InteractiveResult captures the final exit status from an interactive shell session.
type LogCallback ¶
type LogCallback = internalruntime.LogCallback
LogCallback receives top-level execution lifecycle logs.
Callbacks run synchronously on the execution path. Panics are recovered and ignored so observability hooks do not fail shell execution.
type LogEvent ¶
type LogEvent = internalruntime.LogEvent
LogEvent describes one top-level execution lifecycle log callback.
type LogKind ¶
type LogKind = internalruntime.LogKind
LogKind identifies a high-level execution lifecycle log event.
type MountableFileSystemOptions ¶
type MountableFileSystemOptions struct {
// Base provisions the base filesystem used for unmounted paths. When nil, a
// fresh in-memory filesystem is used.
Base gbfs.Factory
// Mounts configures the mounted filesystems visible inside the sandbox.
Mounts []gbfs.MountConfig
// WorkingDir is the directory new sessions start in. When empty,
// /home/agent is used.
WorkingDir string
}
MountableFileSystemOptions configures a multi-mount sandbox filesystem.
type NetworkConfig ¶
type NetworkConfig struct {
// AllowedURLPrefixes is the URL allowlist for sandbox HTTP access.
AllowedURLPrefixes []string
// AllowedMethods restricts which HTTP methods may be used. When empty, GET
// and HEAD are allowed.
AllowedMethods []Method
// MaxRedirects limits how many redirects a request may follow.
MaxRedirects int
// Timeout is the default request timeout.
Timeout time.Duration
// MaxResponseBytes caps the response body size.
MaxResponseBytes int64
// DenyPrivateRanges blocks requests to private, loopback, link-local, and
// similar address ranges.
DenyPrivateRanges bool
}
NetworkConfig controls the built-in HTTP client that powers curl inside the sandbox.
All fields are optional except that some form of URL allowlist is required at runtime. Empty AllowedMethods defaults to GET and HEAD. Zero-valued limits use the network package defaults.
type Option ¶
Option mutates a Config before New constructs the runtime.
Options are applied in order, so later options can intentionally override earlier ones.
func WithBaseEnv ¶
WithBaseEnv replaces the base environment inherited by each execution.
func WithConfig ¶
WithConfig overlays non-zero fields from cfg onto the runtime configuration.
This is useful when configuration is assembled ahead of time and then applied as one option to New.
func WithFileSystem ¶
func WithFileSystem(cfg FileSystemConfig) Option
WithFileSystem replaces the session filesystem configuration.
func WithHTTPAccess ¶
WithHTTPAccess enables curl with a URL allowlist and the default HTTP policy.
This is the simplest way to turn on network access. Requests are restricted to the provided URL prefixes, and all other HTTP settings use the defaults from the network package.
func WithLogger ¶
func WithLogger(callback LogCallback) Option
WithLogger installs a top-level execution lifecycle log callback.
func WithNetwork ¶
func WithNetwork(cfg *NetworkConfig) Option
WithNetwork replaces the built-in HTTP client configuration used by curl.
Use this option when you want to customize methods, limits, timeouts, or private-range denial behavior while still relying on the standard gbash HTTP client implementation.
func WithNetworkClient ¶
WithNetworkClient injects a fully custom HTTP client for curl.
This is the advanced escape hatch for tests and unusual embedding scenarios where the built-in allowlist-based client is not sufficient.
func WithPolicy ¶
WithPolicy replaces the sandbox policy implementation.
func WithRegistry ¶
func WithRegistry(registry commands.CommandRegistry) Option
WithRegistry replaces the command registry visible inside the sandbox.
func WithTracing ¶
func WithTracing(cfg TraceConfig) Option
WithTracing replaces the runtime tracing configuration.
func WithWorkingDir ¶
WithWorkingDir overrides the initial working directory for new sessions.
This option composes with both the default in-memory sandbox and any explicit filesystem option such as WithWorkspace or WithFileSystem.
func WithWorkspace ¶
WithWorkspace mounts dir into the sandbox under a writable in-memory overlay and starts new sessions in that mounted directory.
This is the intended happy-path option for embedding gbash against a real codebase or workspace on disk.
type ReadWriteDirectoryOptions ¶
type ReadWriteDirectoryOptions struct {
// MaxFileReadBytes limits the size of individual regular files that may be
// read from the host directory. When zero or negative, the default host read
// cap is used.
MaxFileReadBytes int64
}
ReadWriteDirectoryOptions controls how a real host directory is mounted as a mutable sandbox root.
Unlike HostDirectoryOptions, this mode writes directly back to the host directory instead of using an in-memory overlay. It is intended for opt-in compatibility harnesses and advanced embedding scenarios.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime executes bash-like scripts inside the configured sandbox.
Use New to construct a runtime, Runtime.Run for one-shot execution, and Runtime.NewSession when you want multiple executions to share the same sandbox filesystem state.
func New ¶
New constructs a runtime from the provided options.
When called with no options, New returns the default sandbox runtime:
- an isolated in-memory filesystem rooted at /home/agent
- the built-in command registry
- the default in-tree shell core
- the default static policy and resource limits
- no network access
Use WithWorkspace to mount a real host directory, WithHTTPAccess or WithNetwork to enable curl, and WithRegistry, WithPolicy, or WithFileSystem when you need lower-level control.
func (*Runtime) NewSession ¶
NewSession creates a new persistent session backed by the runtime's configured filesystem factory and sandbox policy.
Each session gets its own filesystem state. Repeated calls create isolated sessions, while repeated calls to Session.Exec on the same session share the same sandbox filesystem.
func (*Runtime) Run ¶
func (r *Runtime) Run(ctx context.Context, req *ExecutionRequest) (*ExecutionResult, error)
Run executes a script in a fresh session and returns the result.
Use Runtime.NewSession when you want filesystem state to persist across multiple executions.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a persistent sandbox that can execute multiple scripts against the same filesystem state.
Sessions are created by calling Runtime.NewSession.
func (*Session) Exec ¶
func (s *Session) Exec(ctx context.Context, req *ExecutionRequest) (*ExecutionResult, error)
Exec runs a script inside the existing session.
Session executions share filesystem state with each other, but shell-local state such as the working directory and environment only persists when the caller explicitly threads it through later requests.
func (*Session) FileSystem ¶
func (s *Session) FileSystem() gbfs.FileSystem
FileSystem returns the live sandbox filesystem for the session.
Most callers do not need this method. It exists as an advanced escape hatch for tests, bootstrapping, and integrations that need direct filesystem access. Callers should treat the result as the gbfs.FileSystem interface and should not rely on concrete backend types.
func (*Session) Interact ¶
func (s *Session) Interact(ctx context.Context, req *InteractiveRequest) (*InteractiveResult, error)
Interact runs an interactive shell session inside the existing session.
type TraceConfig ¶
type TraceConfig = internalruntime.TraceConfig
TraceConfig configures structured execution tracing.
When Mode is TraceOff, [ExecutionResult.Events] is empty and OnEvent is not called. Interactive executions only deliver events to OnEvent; they do not return events in an InteractiveResult.
type TraceMode ¶
type TraceMode = internalruntime.TraceMode
TraceMode controls whether gbash records structured execution events.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cmd documents the shipped gbash CLI entrypoints.
|
Package cmd documents the shipped gbash CLI entrypoints. |
|
gbash
command
Package main provides the primary gbash CLI entrypoint.
|
Package main provides the primary gbash CLI entrypoint. |
|
gbash-gnu
command
Package main provides the GNU compatibility harness used by the gbash project.
|
Package main provides the GNU compatibility harness used by the gbash project. |
|
Package commands provides the stable command authoring and registry API for gbash.
|
Package commands provides the stable command authoring and registry API for gbash. |
|
Package contrib documents the layout of the optional gbash extension modules.
|
Package contrib documents the layout of the optional gbash extension modules. |
|
awk
module
|
|
|
extras
module
|
|
|
htmltomarkdown
module
|
|
|
jq
module
|
|
|
nodejs
module
|
|
|
sqlite3
module
|
|
|
yq
module
|
|
|
Package fs provides the filesystem contracts and virtual filesystem backends used by gbash, including the default mutable in-memory backend and the experimental read-mostly trie-backed backend.
|
Package fs provides the filesystem contracts and virtual filesystem backends used by gbash, including the default mutable in-memory backend and the experimental read-mostly trie-backed backend. |
|
internal
|
|
|
builtins
Package builtins provides gbash's shipped command implementations and default registry assembly.
|
Package builtins provides gbash's shipped command implementations and default registry assembly. |
|
runtime
Package runtime implements the internal execution engine that backs the public gbash API.
|
Package runtime implements the internal execution engine that backs the public gbash API. |
|
shell
Package shell provides gbash's project-owned shell core plus the in-tree parser, expansion, and interpreter packages it executes against.
|
Package shell provides gbash's project-owned shell core plus the in-tree parser, expansion, and interpreter packages it executes against. |
|
shell/expand
Package expand contains code to perform various shell expansions.
|
Package expand contains code to perform various shell expansions. |
|
shell/fileutil
Package fileutil allows inspecting shell files, such as detecting whether a file may be shell or extracting its shebang.
|
Package fileutil allows inspecting shell files, such as detecting whether a file may be shell or extracting its shebang. |
|
shell/interp
Package interp implements an interpreter to execute shell programs parsed by the syntax package.
|
Package interp implements an interpreter to execute shell programs parsed by the syntax package. |
|
shell/pattern
Package pattern allows working with shell pattern matching notation, also known as wildcards or globbing.
|
Package pattern allows working with shell pattern matching notation, also known as wildcards or globbing. |
|
shell/syntax
Package syntax implements parsing and formatting of shell programs.
|
Package syntax implements parsing and formatting of shell programs. |
|
shell/syntax/typedjson
Package typedjson allows encoding and decoding shell syntax trees as JSON.
|
Package typedjson allows encoding and decoding shell syntax trees as JSON. |
|
Package network provides the sandboxed HTTP client used by gbash.
|
Package network provides the sandboxed HTTP client used by gbash. |
|
Package packages documents the non-Go distribution packages shipped from this repository.
|
Package packages documents the non-Go distribution packages shipped from this repository. |
|
gbash-wasm/wasm
command
Package main exposes the js/wasm entrypoint for the GBashWasm browser API.
|
Package main exposes the js/wasm entrypoint for the GBashWasm browser API. |
|
Package policy provides low-level sandbox policy types and enforcement helpers for gbash.
|
Package policy provides low-level sandbox policy types and enforcement helpers for gbash. |
|
Package scripts documents the repository's Go-based maintenance and reporting utilities.
|
Package scripts documents the repository's Go-based maintenance and reporting utilities. |
|
bench-compare
command
Package main provides the benchmark comparison tool used by the gbash repository.
|
Package main provides the benchmark comparison tool used by the gbash repository. |
|
bench-compare/gbash-runner
command
Package main provides the helper command used by the gbash benchmark comparison harness.
|
Package main provides the helper command used by the gbash benchmark comparison harness. |
|
compat-report
command
Package main provides the GNU compatibility report renderer used by the gbash repository.
|
Package main provides the GNU compatibility report renderer used by the gbash repository. |
|
Package server exposes a shared JSON-RPC server mode for gbash runtimes.
|
Package server exposes a shared JSON-RPC server mode for gbash runtimes. |
|
Package trace provides the structured execution event model used by gbash.
|
Package trace provides the structured execution event model used by gbash. |