ContainerisedWorkspace

org.llm4s.workspace.ContainerisedWorkspace
See theContainerisedWorkspace companion object
class ContainerisedWorkspace(val workspaceDir: String, val imageName: String, val hostPort: Int, val extraAllowedCommands: Set[String], val sandboxConfig: Option[WorkspaceSandboxConfig], val commandCgroups: Boolean, val idleTimeout: FiniteDuration, val options: ContainerOptions) extends WorkspaceAgentInterface, AutoCloseable

WebSocket-based implementation of ContainerisedWorkspace that communicates with the workspace runner via WebSocket instead of HTTP.

This solves the threading issues of the HTTP version by:

  • Using asynchronous WebSocket communication
  • Implementing heartbeats over the same connection
  • Supporting real-time streaming of command output
  • Eliminating thread pool blocking during long commands

Commands run without a shell, and only programs on the runner's allowlist run (#1756): sandboxConfig, when given, chooses the list (and the paths, limits and network a command gets, design §4.39); otherwise the runner's WORKSPACE_SANDBOX_PROFILE (unset, permissive) does. extraAllowedCommands adds to either.

Only this client can drive the runner (#3046): the container's port is published on the host's loopback only (127.0.0.1:<hostPort>), and every WebSocket handshake carries a random token made for this container and passed to it in its environment, never on a command line. The runner refuses a handshake without it, and any browser's.

The runner never runs as root, and holds no capability (#3064): the container starts --cap-drop ALL with only what the image's entry point needs to set it up (see ContainerisedWorkspace.EntryPointCapabilities), and the entry point drops all of it as it switches to the workspace directory's owner (or ContainerOptions.runAsUser). The container's memory, pids and CPU limits are ContainerOptions'.

start says why a start failed (#3063), and refuses a runner that speaks another protocol version, an image older or newer than this client, naming both.

The container never outlives this client for long (#3053): it starts with --rm --init, a failed start removes whatever it left, stopContainer (or close) removes it even when docker stop fails, a JVM shutdown hook does the same when the JVM exits without calling either, and the runner exits by itself once no client has been connected for idleTimeout. A dropped connection (a long pause of this JVM, which the runner ends after 30 seconds without a message, or a runner that stops answering heartbeats) is reconnected with backoff; when that fails the container is removed and every later call throws a WorkspaceAgentException with code WORKSPACE_UNAVAILABLE. A command in flight when the connection dropped fails CONNECTION_CLOSED: the runner kills a closed connection's commands, and a file change's outcome is then unknown.

Value parameters

commandCgroups

start the container so the runner can give each command a cgroup of its own and kill it whole, so a daemon a command starts (setsid) cannot outlive it (design §4.39, #2008): --cgroupns=private --cap-add SYS_ADMIN --security-opt apparmor=unconfined. The image's entry point uses SYS_ADMIN only to make the container's cgroup writable, and drops it before the runner starts. Off by default: commands' daemons can then outlive them, as the runner logs at startup

extraAllowedCommands

programs the runner may run besides its profile's allowlist (for example sbt), passed to the container as WORKSPACE_EXTRA_COMMANDS; each is a bare program name, never a shell or a launcher (see WorkspaceSandboxConfig.withExtraCommands), and a container is not started with a name the runner would refuse

hostPort

the host port the container's 8080 is published on, on 127.0.0.1 only (or ContainerOptions.publishAddress); 0 lets Docker choose a free one, read back once started (port), so two workspaces never contend for one (#3063)

idleTimeout

how long the runner waits with no client connected before it exits, and its container is removed (#3053); rounded up to whole seconds. Longer than this client's reconnection (about 20 seconds), so a reconnecting client finds the runner still there

imageName

the workspace-runner image

options

how the container is started beyond the sandbox: the startup wait, memory, pids and CPU limits, the user the runner runs as, and where its port is published (#3063, #3064)

sandboxConfig

the runner's whole sandbox config, passed as WORKSPACE_SANDBOX_CONFIG; None leaves the runner on its profile. With networkAllowed = false (the default, and the permissive profile's) the container itself has no egress (#870): it starts with --cap-add NET_ADMIN -e LLM4S_NO_EGRESS=1, and the image's entry point lets it answer the published port but open no connection out, then drops NET_ADMIN before the runner starts. A Docker host where the entry point cannot set that up does not start the container

workspaceDir

the host directory mounted as the container's /workspace

Attributes

Companion
object
Source
ContainerisedWorkspace.scala
Graph
Supertypes
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

def cancelCommand(commandId: String): Boolean

Cancels a running command of this workspace's, by the id its request was sent with (#3063): the one executeCommandWithStreaming was given, or the one its output chunks carry. The runner kills it, its whole process tree, and the call that waits for it returns the runner's answer (exit 143); one not yet started never starts. false when there is no open connection to send it on, or the id is no command this client is waiting for. A file change has no cancellation.

Cancels a running command of this workspace's, by the id its request was sent with (#3063): the one executeCommandWithStreaming was given, or the one its output chunks carry. The runner kills it, its whole process tree, and the call that waits for it returns the runner's answer (exit 143); one not yet started never starts. false when there is no open connection to send it on, or the id is no command this client is waiting for. A file change has no cancellation.

Attributes

Source
ContainerisedWorkspace.scala
override def close(): Unit

Stops and removes the container, as stopContainer does.

Stops and removes the container, as stopContainer does.

Attributes

Definition Classes
Source
ContainerisedWorkspace.scala
override def deleteFile(path: String, expectedHash: Option[String]): DeleteFileResponse

Delete the file, or the empty directory, path; with expectedHash, a compare-and-set as for writeFile (directory for a directory).

Delete the file, or the empty directory, path; with expectedHash, a compare-and-set as for writeFile (directory for a directory).

Attributes

Definition Classes
Source
ContainerisedWorkspace.scala
override def executeCommand(command: String, workingDirectory: Option[String], timeout: Option[FiniteDuration], environment: Option[Map[String, String]], maxOutputBytes: Option[Long]): ExecuteCommandResponse

Execute a command in the workspace. The command is a program and its arguments, not shell text: the runner tokenizes it and runs the program directly, refusing pipes, redirection, ;, $(...) and anything else the sandbox's command policy forbids (see docs/reference/workspace-sandbox.md).

Execute a command in the workspace. The command is a program and its arguments, not shell text: the runner tokenizes it and runs the program directly, refusing pipes, redirection, ;, $(...) and anything else the sandbox's command policy forbids (see docs/reference/workspace-sandbox.md).

Value parameters

command

Command to execute

environment

Environment variables

maxOutputBytes

The most bytes of each of stdout and stderr to keep, measured as the output is carried (UTF-8, JSON-escaped; so also at most that many characters). Default and upper bound: the workspace's maxOutputSize; the rest is read and discarded, and isOutputTruncated set

timeout

Timeout (default: the sandbox's defaultCommandTimeout)

workingDirectory

Working directory (default: workspace root)

Attributes

Returns

Response with command execution result

Definition Classes
Source
ContainerisedWorkspace.scala
def executeCommandWithStreaming(command: String, workingDirectory: Option[String], timeout: Option[FiniteDuration], environment: Option[Map[String, String]], outputHandler: StreamingOutputMessage => Unit, commandId: String): ExecuteCommandResponse

Execute a command with streaming output support. The handler will be called for each chunk of output received.

Execute a command with streaming output support. The handler will be called for each chunk of output received.

Value parameters

commandId

the id the command is sent with, unique among this workspace's commands: another thread may cancel it by this id while this call waits

Attributes

Source
ContainerisedWorkspace.scala
override def exploreFiles(path: String, recursive: Option[Boolean], excludePatterns: Option[List[String]], maxDepth: Option[Int], returnMetadata: Option[Boolean]): ExploreFilesResponse

List files and directories in a specified path, optionally recursively.

List files and directories in a specified path, optionally recursively.

Value parameters

excludePatterns

Glob patterns to exclude

maxDepth

Maximum recursion depth

path

Path to explore

recursive

Whether to explore recursively

returnMetadata

Whether to include file metadata

Attributes

Returns

Response with list of files and directories

Definition Classes
Source
ContainerisedWorkspace.scala
override def fileSnapshot(path: String, includeContent: Boolean, followLinks: Boolean): FileSnapshotResponse

What is at path: nothing, a directory, or a file with the hash of its bytes and, when includeContent, its exact text if it is valid UTF-8 and at most the workspace's maxFileSize. With followLinks = false, a symbolic link at path is described as itself: kind link and a hash of where it points, which a deleteFile compares (it removes the link, not what it names).

What is at path: nothing, a directory, or a file with the hash of its bytes and, when includeContent, its exact text if it is valid UTF-8 and at most the workspace's maxFileSize. With followLinks = false, a symbolic link at path is described as itself: kind link and a hash of where it points, which a deleteFile compares (it removes the link, not what it names).

Attributes

Definition Classes
Source
ContainerisedWorkspace.scala

Retrieve information about the workspace, including default settings and limits.

Retrieve information about the workspace, including default settings and limits.

Attributes

Returns

Response with workspace information

Definition Classes
Source
ContainerisedWorkspace.scala
override def modifyFile(path: String, operations: List[FileOperation]): ModifyFileResponse

Perform targeted modifications to a file without rewriting the entire content.

Perform targeted modifications to a file without rewriting the entire content.

Value parameters

operations

List of operations to perform

path

Path to file

Attributes

Returns

Response with modification result

Definition Classes
Source
ContainerisedWorkspace.scala
def port: Option[Int]

The host port the runner is reached on: hostPort, or the one Docker chose when hostPort is 0; None until start has resolved it.

The host port the runner is reached on: hostPort, or the one Docker chose when hostPort is 0; None until start has resolved it.

Attributes

Source
ContainerisedWorkspace.scala
override def readFile(path: String, startLine: Option[Int], endLine: Option[Int]): ReadFileResponse

Read the content of a file, with options to read specific line ranges.

Read the content of a file, with options to read specific line ranges.

Value parameters

endLine

Optional end line (1-indexed)

path

Path to file

startLine

Optional start line (1-indexed)

Attributes

Returns

Response with file content and metadata

Definition Classes
Source
ContainerisedWorkspace.scala
override def searchFiles(paths: List[String], query: String, searchType: String, recursive: Option[Boolean], excludePatterns: Option[List[String]], contextLines: Option[Int]): SearchFilesResponse

Search for content in files across the workspace.

Search for content in files across the workspace.

Value parameters

contextLines

Number of context lines to include

excludePatterns

Glob patterns to exclude

paths

Paths to search in

query

Search query

recursive

Whether to search recursively

searchType

Search type ("regex" or "literal")

Attributes

Returns

Response with search results

Definition Classes
Source
ContainerisedWorkspace.scala
def start(): Result[Unit]

Starts the workspace runner's container and connects to it (#3063): Right(()) once the runner has accepted a connection and speaks this client's protocol version, else why not, and the container is removed. The reasons:

Starts the workspace runner's container and connects to it (#3063): Right(()) once the runner has accepted a connection and speaks this client's protocol version, else why not, and the container is removed. The reasons:

  • a config docker run was never asked to start: an invalid sandbox config, extraAllowedCommands or ContainerOptions (ConfigurationError);
  • docker run failed (a missing image, a busy port): its exit code and standard error (ExecutionError);
  • the container exited, or no connection was accepted within ContainerOptions.startupTimeout, with the container's last logs where Docker still has them (ExecutionError). The image's entry point exits 78 when it cannot give the sandbox what it asks (no egress), or cannot run the runner as a non-root user;
  • the runner speaks another protocol version, an image older or newer than this client, naming both (ConfigurationError).

Attributes

Source
ContainerisedWorkspace.scala

Starts the workspace runner's container and connects to it, as start does: true when it is running, false (the reason logged) when it is not. A start that fails removes whatever container it left (#3053).

Starts the workspace runner's container and connects to it, as start does: true when it is running, false (the reason logged) when it is not. A start that fails removes whatever container it left (#3053).

Attributes

Source
ContainerisedWorkspace.scala

Stops and removes the container: docker stop, then docker rm -f whatever stop did, so a container that would not stop is still removed. true when the container is gone (or never existed). Safe to call more than once.

Stops and removes the container: docker stop, then docker rm -f whatever stop did, so a container that would not stop is still removed. true when the container is gone (or never existed). Safe to call more than once.

Attributes

Source
ContainerisedWorkspace.scala
override def writeFile(path: String, content: String, mode: Option[String], createDirectories: Option[Boolean], expectedHash: Option[String]): WriteFileResponse

Write content to a file, creating the file if it doesn't exist.

Write content to a file, creating the file if it doesn't exist.

Value parameters

content

Content to write

createDirectories

Create parent directories if they don't exist

expectedHash

A compare-and-set: write only if the path's current FileSnapshotResponse.hash is this, atomically against every other file operation, and replace the file atomically (a reader or a crash sees the old content or the new, never part of it); otherwise HASH_MISMATCH, and nothing is written. Only with mode "overwrite".

mode

Write mode (default: "overwrite")

path

Path to file

Attributes

Returns

Response with write operation result

Definition Classes
Source
ContainerisedWorkspace.scala