Workspaces and Sandboxes

A Workspace gives one Run—one top-level Agent or Assembly execution—a stable set of host paths. A Sandbox decides which operations may reach those paths and how child processes are contained.

Use them together when an Agent can read files, change files, or run programs:

require "fileutils"
require "tmpdir"

LittleGhost.configure do |config|
  config.workspace = lambda do |**|
    root = Dir.mktmpdir("little-ghost-support-")
    LittleGhost::Workspace.new(
      root:,
      teardown: lambda do |workspace:, **|
        FileUtils.remove_entry_secure(workspace.root) if File.exist?(workspace.root)
      end
    )
  end

  config.sandbox = {
    provider: :native,
    files: {root: :read_write}
  }
end

This example gives each Run a temporary writable root and removes it during teardown. The :native Sandbox backend selects Seatbelt on macOS or Bubblewrap on Linux. It raises instead of running without isolation when the native backend is unavailable. Unless you configure otherwise, it isolates the host root, removes child-process network access, and starts child processes without inheriting the host environment.

LittleGhost::Tools::Filesystem and LittleGhost::Tools::Shell use the Sandbox assigned to the current Run. Code-mode interpreters also run inside their own Sandbox. Ordinary application Tools, callbacks, and provider requests stay in the Ruby process unless they deliberately delegate an operation.

The split looks like this:

Ruby application process
├── provider requests
├── application Tool#call
└── Sandbox
    ├── bounded filesystem operations
    ├── Shell child processes
    └── code-mode interpreter processes

Give files a stable home

A Workspace names the files available during a Run and controls their setup and cleanup. Its root is the default working directory. Named paths give important directories logical identities:

workspace = LittleGhost::Workspace.new(
  root: "/var/lib/support/run-481",
  paths: {
    source: "/srv/support/source",
    skills: "skills",
    home: "runtime-home"
  }
)

Relative named paths live beneath the root and are created when the Workspace opens. Absolute named paths are references deliberately supplied by the application and must already exist. A setup callback can provision them when needed.

Opening resolves real paths and records which physical directories they refer to. LittleGhost rejects two names that point to the same directory and later fails closed if a configured directory is replaced. Nested paths are allowed, and the most restrictive matching access wins.

Workspace object lifetime and file lifetime are separate. Closing invokes the configured teardown callback, but does not delete files by default. Use a run-scoped temporary root for disposable work. Use application-managed storage, tenant isolation, and concurrency control when several Runs share files.

Give artifacts logical references

Images and documents normally remain provider content. When filesystem Tools or code mode should read the same bytes, configure the conventional artifact path and enable artifact handling:

LittleGhost.configure do |config|
  config.workspace = {
    provider: :directory,
    root: "tmp/agent-runs",
    paths: {artifacts: "artifacts"}
  }
  config.artifacts
end

LittleGhost stores input images and documents after the Workspace and Sandbox open. The model receives the image or document in its normal input without a second text reference. Filesystem Tools can list workspace://artifacts when a later operation needs the stored copy. Messages added while the Run is active receive the same treatment.

LittleGhost limits the number and size of files stored from each message and across the complete Run. Those limits also include Tool artifacts and oversized Tool results. A successful operation stores all of its files. If storage fails partway through, LittleGhost attempts to remove that operation’s files and reports a cleanup error when it cannot. Stored files use private permissions, and the Workspace provider still owns final cleanup.

Declaring the path does not grant model access. When the Agent should read it, grant the Sandbox access to :artifacts and include a filesystem Tool.

Pass logical paths, not host layout

The Filesystem Tool accepts root-relative paths such as notes/today.md. Named paths use references such as workspace://skills/refunds/SKILL.md.

Those references remain meaningful without exposing or translating the host layout. The Filesystem Tool rejects physical absolute paths. Child processes use the Workspace’s real paths directly, start in its root, and receive LITTLE_GHOST_WORKSPACE_ROOT plus one LITTLE_GHOST_WORKSPACE_<NAME> variable for each named path.

Workspace references give application code one stable path format. Each Sandbox backend applies the configured access using the filesystem controls available on its host.

Separate Tool-visible files from process support

Sandbox configuration divides named paths into two groups:

config.sandbox = {
  provider: :native,
  files: {
    root: :read_write,
    source: :read_only,
    skills: :read_only
  },
  runtime_paths: {
    home: :read_write
  }
}

files are visible to both the Filesystem Tool and sandboxed processes. runtime_paths are process-only. Use runtime paths for interpreter libraries, homes, sockets, and service state that a model should not browse through a filesystem Tool.

This is visibility, not secrecy from the process. A child with a runtime-path grant can use that path according to its access mode. The distinction prevents the Filesystem Tool from offering it as a model-visible file tree.

Narrow access with a Scope

A Sandbox::Scope is a non-owning, reduced view of a Sandbox. It can remove paths, change writable access to read-only, remove capabilities (categories of allowed operations), or narrow networking. It cannot widen its parent:

reviewer = run.sandbox.scope(
  files: {source: :read_only},
  runtime_paths: [],
  capabilities: %i[filesystem_read filesystem_list],
  network: false
)

Scopes constrain only code that receives and uses the Scope. Code that keeps a reference to the parent Sandbox keeps the parent’s authority. A Scope does not open or close its parent and owns no resources.

Choose how much of the host exists

root_filesystem controls what a sandboxed process can see beyond declared Workspace paths:

On Seatbelt, host-visible modes permit subprocesses because development tools often need them. A Scope can remove process_spawn for a command that does not.

Start child processes with only the values they need

When environment is omitted, sandboxed processes do not inherit the host environment. LittleGhost starts with LANG, LC_ALL, and PATH, then adds LITTLE_GHOST_WORKSPACE_* variables so the child can locate its Workspace. Locale values come from the host when present and otherwise use C.UTF-8. PATH keeps the host’s absolute entries, removes empty, relative, and duplicate entries, and falls back to /usr/local/bin:/usr/bin:/bin when nothing remains. Credentials, provider keys, package-manager settings, and home-directory variables are not copied into the child.

Safety note: An absolute directory is not necessarily a trusted one. A host PATH may include project directories, temporary directories, or user-managed shims. Configure a fixed PATH when a model can invoke commands by name and you do not trust every host entry.

Declaring environment replaces the locale and path baseline instead of merging with it. Use an empty Hash to omit all configurable values, or set exactly what the process needs. Workspace routing variables remain available:

config.sandbox = {
  provider: :native,
  environment: {
    inherit: false,
    set: {"LANG" => "C.UTF-8", "PATH" => "/opt/my-tool/bin:/usr/bin"}
  }
}

Host inheritance requires both inherit: true in the Sandbox policy and an individual process call that opts into inheritance.

Choose an enforcement backend

Sandbox backend Host What it enforces
:native macOS or Linux Selects Seatbelt on macOS and Bubblewrap on Linux; fails closed elsewhere
:seatbelt macOS Deny-default Seatbelt profile over the configured physical paths
:bubblewrap Linux Fresh user, PID, mount, IPC, UTS, and optional network namespaces
:unrestricted Ruby platforms No containment; commands have the application process’s host authority

LittleGhost::Sandbox.probe(:native) reports whether the platform backend is available. Selecting an enforcing backend never falls back to unrestricted execution.

Bubblewrap owns descendants with a PID namespace and ends them when the supervising process dies. It cannot selectively deny fork inside that namespace, so a request for allow_subprocesses: false fails closed rather than claiming an unenforced restriction. Bubblewrap does not impose a task-count limit by itself. Use an outer cgroup or container supervisor when generated code needs a hard cap on the processes and threads it can create.

Seatbelt can constrain spawned children, but macOS has no PID namespace. It terminates the command process group during cleanup; a child that deliberately detaches from that group may survive. Use an outer process or container supervisor when complete descendant ownership is required on macOS.

Safety note: LittleGhost::Sandboxes::Unrestricted is suitable for application commands and tests that you would already run directly. It validates paths and bounds output, but it does not isolate the command from the host. Use :native for generated commands in production.

Keep process ownership explicit

Sandbox#start_program returns a Sandbox::ProcessSession with bounded input and output, alive?, bounded wait(timeout:), terminate, and close. The session starts the command in a process group so cleanup can stop it and its ordinary descendants together. It applies available CPU, memory, file, and output limits, requests termination, and then forces termination when needed.

Callers that open a ProcessSession own it and must close it. LittleGhost fails closed when it cannot supervise a configured memory limit. The parent samples the visible process tree every 100 milliseconds, so it reacts only to memory present at a sample and may miss peaks between samples. On Linux, three consecutive failures to read the root process or the /proc snapshot end the process. Use an outer cgroup or container when memory must be enforced as a hard limit by the operating system.

A Run closes the Workspace and Sandbox it creates after success, failure, a partial response, or cancellation. Application-supplied instances remain caller-owned.

Trusted setup work, such as unpacking a cache into a new Workspace in a setup hook, does not need a Sandbox. Sandbox::ProcessRunner.capture runs one command in its own process group with a timeout, an output limit, and the Run’s cancellation, and returns a result that reports the exit code, whether the command timed out, and whether either stream was truncated. It waits for every member of the process group, so a backgrounded child cannot outlive the result; pass wait_for_group: false to return once the command itself exits. The command is an Array of arguments and never runs through a shell. It applies no isolation, so never pass it a command the model chose.

Configure child-process networking separately

Sandbox networking has three modes:

Seatbelt, Bubblewrap, and :native default to :none; declare a network mode only when the child needs a different policy. The unrestricted backend uses :inherit because it is not a security boundary.

Proxy environment variables alone are not an allowlist. An external gateway uses named, process-only Workspace paths and verifies that they still point to the configured directories; it does not create a virtual path mapping. LittleGhost does not attest that an external proxy is ready or enforcing the declared destinations. The application must supervise and verify that gateway before giving a child network access.

These settings reach only processes launched through the Sandbox. Providers, callbacks, and application Tool code still use the Ruby process’s network access.

Decide what each host accepts

An allowlist decides which hosts a child can reach. A Network::HostPolicy decides which requests those hosts accept, and it can add a credential the child never sees:

hosts = LittleGhost::Network::HostPolicy.new do
  host "api.example.com" do
    methods :post
    paths "/v1/answers", "/v1/answers/*"
    inject { |request| {"x-api-key" => ENV.fetch("HELP_CENTER_API_KEY")} }
  end

  default do
    methods :get, :head
  end
end

config.sandbox = {
  provider: :native,
  network: hosts.network_policy(allow: ["api.example.com:443", "rubygems.org:443"])
}

network_policy turns on HTTP inspection for the allowed hosts. The gateway decrypts each request with a run-scoped certificate authority, asks the host policy about the method, path, and headers, and then re-encrypts the request to the real host. Client credential headers such as authorization and x-api-key are removed unless the policy injects them. Requests to a host without a rule, or that fail a rule, receive a 403 response. Use pass_headers to forward only named headers, deny_paths to carve out exceptions, require to check application state for each request, and timeout to bound slow hosts.

An allowlist entry may begin with *. to admit one label of subdomains, for example *.blob.core.windows.net:443. The gateway still resolves and verifies each host it connects to, and the certificate it presents to the child covers those hosts with a wildcard name.

Paths are decoded before they are matched, and a path that cannot be matched safely, for example one with an encoded line break or .. segment, receives a 400 response. Anchor Regexp patterns with \A and \z. A rule that declares methods also rejects method overrides such as x-http-method-override headers and _method query parameters. The gateway removes client x-envoy-* headers before it routes a request, and it verifies that every upstream certificate matches the host it connects to, sending that host as the TLS server name.

The inject and require blocks run in the Ruby process for every request, so they can read a credential that rotates. Keep the credential out of exception messages: the gateway answers a failing block with a 503 response and does not log its message.

Give a command a fixed upstream

Some clients accept a base URL but not a proxy certificate. A Network::Facade gives them a plaintext listener that forwards every request to one HTTPS host:

policy = hosts.network_policy(
  facades: [{name: :answers, upstream: "api.example.com", socket: "/run/egress/answers.sock", timeout: 0}]
)

A child configured with the facade’s address as its base URL and a placeholder key reaches api.example.com only through the host policy, which replaces the placeholder. A host can be reachable through a facade without appearing in allow. A timeout of 0 lets streaming responses run as long as the upstream keeps the connection open; responses are not buffered.

Facades listen on a fixed port or socket, so they need an Envoy that the application supervises rather than the run-scoped gateway. Network::EnvoyGateway.write_configuration writes that configuration, and Network::AuthorizerServer#serve runs the host policy as the main loop of a separate process:

LittleGhost::Network::EnvoyGateway.write_configuration(
  path: "/run/egress/envoy.json",
  policy:,
  listener: "/run/egress/proxy.sock",
  paths: {authorizer_socket: "/run/egress-private/authorizer.sock", trusted_ca: "/etc/ssl/certs/ca-certificates.crt"},
  socket_mode: 0o660
)

LittleGhost::Network::AuthorizerServer.new(
  socket_path: "/run/egress-private/authorizer.sock",
  authorizer: hosts.authorizer,
  mode: 0o660,
  peer_uids: [Etc.getpwnam("envoy").uid]
).serve(stop_io: stop_reader)

Running the authorizer as its own user keeps credentials out of both Envoy and the sandbox. peer_uids closes connections from any other user. It compares user IDs as the authorizer’s own user namespace sees them, so it only fits an authorizer that shares Envoy’s namespace; inside a separate namespace, such as a Bubblewrap sandbox, protect the socket with a directory that only Envoy and the authorizer can enter. socket_mode sets the permission bits of the proxy and facade sockets Envoy creates; it never grants access to other users, so give the sandbox user Envoy’s group or run it as Envoy’s user with 0o600. The authorizer answers only requests from listeners in this configuration: Envoy tells it whether a request came from an inspected host or from a facade, and a client cannot change which upstream the authorizer sees. Relay the facade socket into the sandbox as a runtime path, and expose the explicit proxy through an external gateway as described above.

Test the deployed kernel and filesystem, not only the configuration object. Exercise denied reads and writes, runtime paths, child creation, direct sockets, cancellation, limits, and cleanup before depending on the Sandbox to isolate generated code.

Continue with Code Mode to see how a model-authored interpreter uses this setup while every Tool call stays in the parent Ruby process. For exact setup, access, and cleanup behavior, see LittleGhost::Workspace, LittleGhost::Sandbox, and LittleGhost::Sandbox::Scope.