# Chalk Compute Reference: Image
source: https://docs.chalk.ai/compute-docs#section-image

Declarative, composable container image builder using a fluent API.

Each builder method returns a new [`Image`](https://docs.chalk.ai/compute-docs#Image) instance so intermediate images can be shared and extended. Use class methods like `Image.debian_slim()` or `Image.base()` to start, then chain `pip_install`, `run_commands`, `add_local_file`, etc.

## `Image`
source: https://docs.chalk.ai/compute-docs#Image

Class

Declarative, composable container image builder.

Uses a fluent (method-chaining) API. Each method returns a new [`Image`](https://docs.chalk.ai/compute-docs#Image) instance so that intermediate images can be shared and extended.

Call `build` to capture a reusable image with pinned file contents. Built images work with every `image=` parameter and can be transferred between processes using `to_json` and `from_json`.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["requests", "pandas"])
    .workdir("/home/user/app")
)
```

**Attributes**

- `volumes`: `tuple[VolumeMount, ...]`
  Return pinned volumes retained by this image.

  **Returns**

  tuple of VolumeMount Pinned volumes retained independently of worker cleanup.

### `Image.build(volumes, name, chalk_client, poll_interval, timeout)`
source: https://docs.chalk.ai/compute-docs#Image.build

**Build a reusable image and capture immutable versions of its files.Notes**

With no additional volumes, building an already built image returns an equivalent copy without network calls. Authentication, polling, and timeout settings only apply when a build or volume lookup is needed.

ChalkFS volumes persist independently of workers. Keep them while built images remain in use. Pins do not enforce runtime read-only access. Empty-dir mounts are recreated for each worker.

**Parameters**

- `volumes`: `Iterable[tuple[str | Volume, str] | Volume | VolumeMount] | None` = `None`
  Additional volume references, accepting the same forms as Sandbox.
- `name`: `str | None` = `None`
  Optional retained source volume name for local volume files. Defaults to a stable name derived from the build recipe and file layout, excluding local source paths and volume file contents. Pass a name to share source volumes across recipes or make cleanup discoverable. Requires local volume files to upload.
- `chalk_client`: `Any | None` = `None`
  Optional client for authentication. Defaults to the environment.
- `poll_interval`: `float` = `0.5`
  Polling interval in seconds for each build and source upload.
- `timeout`: `float` = `600.0`
  Timeout in seconds for each build and source upload.

**Returns**

`Image`

A new built image with pinned volumes, leaving this recipe unchanged.

**Raises**

- `ValueError`: If a name is supplied without local volume files, or mounts conflict.

### `Image.to_json()`
source: https://docs.chalk.ai/compute-docs#Image.to_json

Serialize a built image without local paths or credentials.

**Returns**

`str`

JSON containing the image URI and pinned volumes.

**Raises**

- `ValueError`: If this image has not been built.

### `Image.from_json(value)`
source: https://docs.chalk.ai/compute-docs#Image.from_json

Load a built image without contacting any service.

**Parameters**

- `value`: `str`
  JSON produced by `to_json`.

**Returns**

`Image`

The built image represented by the JSON value.

**Raises**

- `ValueError`: If the JSON value is invalid or does not describe a built image.

### `Image.base(image)`
source: https://docs.chalk.ai/compute-docs#Image.base

Create an image from an arbitrary base image reference.

**Parameters**

- `image`: `str`
  Full image reference (e.g. `"python:3.14-slim-trixie"`, `"ghcr.io/org/image:tag"`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) based on the given reference.

**Examples**

```python
from chalkcompute import Image
img = Image.base("python:3.14-slim-trixie")
img = Image.base("ghcr.io/my-org/my-image:latest")
```

### `Image.debian_slim(python_version)`
source: https://docs.chalk.ai/compute-docs#Image.debian_slim

Create an image based on `python:<version>-slim-trixie`.

**Parameters**

- `python_version`: `str` = `'3.14'`
  Python version tag.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) based on the selected Python slim image.

**Examples**

```python
from chalkcompute import Image
img = Image.debian_slim()
img = Image.debian_slim("3.14.5")
```

### `Image.sandbox(python_version)`
source: https://docs.chalk.ai/compute-docs#Image.sandbox

Default sandbox image: Python, Git, TLS certificates, and SSH.

Uses Debian slim with `/workspace` as its working directory. Builds lazily through the normal image builder, and can be extended with the same methods as any other Image. A fresh spec is returned each time.

### `Image.from_dockerfile(path)`
source: https://docs.chalk.ai/compute-docs#Image.from_dockerfile

Create an image from an existing Dockerfile.

The Dockerfile contents are transmitted as a `dockerfile_commands` step so that additional builder methods can be chained on top.

**Parameters**

- `path`: `str`
  Path to the Dockerfile.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) whose build steps mirror the Dockerfile.

**Examples**

```python
from chalkcompute import Image
img = Image.from_dockerfile("./Dockerfile")
img = (
    Image.from_dockerfile("./Dockerfile")
    .pip_install(["rich"])
)
```

### `Image.run_commands(commands)`
source: https://docs.chalk.ai/compute-docs#Image.run_commands

Run shell commands during the image build.

Each string is executed as a separate `RUN` instruction.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the run steps appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .run_commands(
        "apt-get update",
        "apt-get install -y curl git",
    )
)
```

### `Image.apt_install(packages)`
source: https://docs.chalk.ai/compute-docs#Image.apt_install

Install Debian/Ubuntu system packages during the image build.

Like `pip_install`, accepts a sequence and returns a new image. Requires `apt-get` and a root build user. Updates package indexes, installs noninteractively without recommended packages, and removes indexes in one build layer. Package versions can be pinned with `name=version`. Other distributions can use `run_commands` with their package manager.

**Examples**

```python
image = Image.sandbox().apt_install(["tmux"])
sandbox = Sandbox(image=image).run()
sandbox.exec("tmux", "new-session", "-d", "-s", "work")
```

### `Image.with_tmux()`
source: https://docs.chalk.ai/compute-docs#Image.with_tmux

Install tmux with `apt_install`.

**Examples**

```python
image = Image.sandbox().with_tmux()
sandbox = Sandbox(image=image).run()
sandbox.exec("tmux", "new-session", "-d", "-s", "work")
```

### `Image.with_gh(version)`
source: https://docs.chalk.ai/compute-docs#Image.with_gh

Install the GitHub CLI from GitHub's apt repository.

Debian's `gh` package lags upstream, so this adds `cli.github.com/packages` and installs from it. Requires `apt-get` and a root build user. Set `GH_TOKEN` at runtime to authenticate.

**Parameters**

- `version`: `str | None` = `None`
  Optional `gh` version, such as `"2.62.0"`. Defaults to the latest release when the image is first built.

**Examples**

```python
image = Image.sandbox().with_gh()
sandbox = Sandbox(
    image=image,
    secrets=[Secret.from_chalk_env("GITHUB_PAT", alias="GH_TOKEN")],
).run()
sandbox.exec("gh", "pr", "list")
```

### `Image.with_claude_code(version, trusted_dirs, permission_mode, skip_dangerous_mode_prompt, api_key_env, settings, theme, disable_nonessential_traffic)`
source: https://docs.chalk.ai/compute-docs#Image.with_claude_code

Install Claude Code and skip its first-run prompts.

Installs the native `claude` binary from Anthropic's signed apt repository, so any Debian or Ubuntu base works without Node.js. Requires `apt-get` and a root build user. Apt installs do not auto-update, so a pinned version stays pinned in running sandboxes.

Also configures Claude Code for the build user so that interactive `claude` starts straight into a session when `CLAUDE_CODE_OAUTH_TOKEN` is set at runtime:

- `~/.claude.json` marks onboarding as done (the onboarding flow otherwise ignores a token supplied at runtime), accepts the trust prompt for `trusted_dirs`, dismisses the one-time "make auto mode your default?" offer shown in bypass-permissions mode, and sets `theme`.
- `~/.claude/settings.json` holds `permission_mode`, `skip_dangerous_mode_prompt`, `api_key_env` and `settings`.

Claude Code refuses bypass-permissions mode as root unless `IS_SANDBOX=1` is set. Chalk sets it in every sandbox, so this image needs nothing extra; set it yourself to run the image elsewhere.

Trusting directories ~~~~~~~~~~~~~~~~~~~~ A trusted directory covers its subdirectories, but inside a Git repository Claude only looks from the working directory up to the repository root. Trusting `/workspace` or `/` therefore does not cover a clone at `/workspace/app`; list the repository root itself. Trusting `"/"` does cover every directory that is not in a Git repository. Paths must not contain symlinks, because Claude compares resolved paths.

To skip the prompt everywhere, set `CLAUDE_CODE_SANDBOXED=1` in the sandbox `env`. Claude Code treats every directory as trusted when it is set. The variable is undocumented and may change between releases; it was checked against Claude Code 2.1.293.

**Parameters**

- `version`: `str | None` = `None`
  Optional Claude Code version, such as `"2.1.270"`. Defaults to the latest release when the image is first built. Pin a version for reproducible images. The Debian revision `-1` is assumed unless the version includes one.
- `trusted_dirs`: `Sequence[str]` = `()`
  Absolute directories to pre-accept in Claude Code's "trust the files in this folder" prompt. Use the root of each repository `claude` runs in. Only trust repositories whose Claude settings and hooks you are willing to run.
- `permission_mode`: `'default' | 'acceptEdits' | 'plan' | 'auto' | 'dontAsk' | 'bypassPermissions' | None` = `None`
  Optional permission mode `claude` starts in, such as `"acceptEdits"` or `"bypassPermissions"`. Defaults to Claude Code's own default, which asks before edits and commands.
- `skip_dangerous_mode_prompt`: `bool` = `True`
  Skip the warning that `claude --dangerously-skip-permissions` (or `permission_mode="bypassPermissions"`) shows on every start. Defaults to [`True`](https://docs.python.org/3/library/constants.html#True); the warning would otherwise block an unattended session.
- `api_key_env`: `str | None` = `None`
  Optional name of a runtime environment variable holding an Anthropic API key, such as `"ANTHROPIC_API_KEY"`. Claude asks before using a raw `ANTHROPIC_API_KEY` and records the answer per key, so it can't be pre-approved in the image. This reads the key through `apiKeyHelper` instead, which doesn't ask. Not needed with `CLAUDE_CODE_OAUTH_TOKEN`.
- `settings`: `Mapping[str, Any] | None` = `None`
  Optional extra user settings for `~/.claude/settings.json`, such as `{"model": "opus"}`. They override the settings derived from the other arguments. See Claude Code's settings documentation for the available keys.
- `theme`: `'auto' | 'dark' | 'light' | 'dark-daltonized' | 'light-daltonized' | 'dark-ansi' | 'light-ansi'` = `'dark'`
  Color theme. Defaults to `"dark"`; `"auto"` follows the terminal.
- `disable_nonessential_traffic`: `bool` = `True`
  Set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` in the image, which turns off telemetry, error reporting, auto-update checks and other calls that aren't needed to talk to the model. Defaults to [`True`](https://docs.python.org/3/library/constants.html#True), so a sandbox whose network policy allows only the model API doesn't spend time on blocked requests. Override it per sandbox through `env`.

**Examples**

```python
image = (
    Image.sandbox()
    .with_claude_code(
        version="2.1.270",
        trusted_dirs=["/workspace/app"],
        permission_mode="bypassPermissions",
    )
    .with_gh()
    .with_tmux()
    .workdir("/workspace/app")
)
```

### `Image.uv_pip_install(packages)`
source: https://docs.chalk.ai/compute-docs#Image.uv_pip_install

Install Python packages via `uv pip install`.

Uses the `uv` resolver instead of `pip` for significantly faster installs. Requires a base image that has `uv` available.

**Parameters**

- `packages`: `Sequence[str]`
  List of pip requirement specifiers (e.g. `["requests", "pandas"]`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the uv pip install step appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.base("ghcr.io/astral-sh/uv:python3.14-trixie-slim")
    .uv_pip_install(["requests", "polars"])
)
```

### `Image.uv_pip_install_from_requirements(path)`
source: https://docs.chalk.ai/compute-docs#Image.uv_pip_install_from_requirements

Install packages from a `requirements.txt` file via `uv pip install`.

The file is read locally and its contents are inlined into the image spec so that the file does not need to be accessible at build time. Uses the `uv` resolver for significantly faster installs than `pip_install_from_requirements`. Requires a base image that has `uv` available.

**Parameters**

- `path`: `str`
  Path to `requirements.txt`.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the uv pip install step appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.base("ghcr.io/astral-sh/uv:python3.14-trixie-slim")
    .uv_pip_install_from_requirements("./requirements.txt")
)
```

### `Image.pip_install(packages)`
source: https://docs.chalk.ai/compute-docs#Image.pip_install

Install Python packages via pip.

**Parameters**

- `packages`: `Sequence[str]`
  List of pip requirement specifiers (e.g. `["requests", "pandas"]`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the pip install step appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["requests", "pandas"])
)
```

### `Image.pip_install_from_requirements(path)`
source: https://docs.chalk.ai/compute-docs#Image.pip_install_from_requirements

Install packages from a `requirements.txt` file.

The file is read locally and its contents are inlined into the image spec so that the file does not need to be accessible at build time.

**Parameters**

- `path`: `str`
  Path to `requirements.txt`.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the pip install step appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install_from_requirements("./requirements.txt")
)
```

### `Image.add_local_file(src, dest, mode, strategy)`
source: https://docs.chalk.ai/compute-docs#Image.add_local_file

Add a local file into the image.

Each call is **additive** — the file is appended to the set of files (or build steps) already registered on the image, not replacing them — so `add_local_file` can be chained many times to bring in several files.

**Parameters**

- `src`: `str`
  Local file path.
- `dest`: `str`
  Absolute destination path in the image.
- `mode`: `int | None` = `None`
  Optional POSIX file permission mode. Written in octal with a `0o` prefix; if omitted, `strategy="volume"` preserves the source file's on-disk permissions and `strategy="copy"` uses the image's default permissions. Common values:

  - `0o755` (`rwxr-xr-x`) — executable scripts and binaries; owner can read/write/execute, everyone else read/execute.
  - `0o644` (`rw-r--r--`) — regular data files; owner can read/write, everyone else read-only.
  - `0o600` (`rw-------`) — private files (credentials, secrets, SSH keys); owner read/write, no access for others.
  - `0o700` (`rwx------`) — owner-only directories or private executables.
  - `0o400` (`r--------`) — immutable/read-only files the workload must not mutate.
- `strategy`: `'copy' | 'volume'` = `'volume'`
  `"copy"` inlines the file contents into the image spec and rejects files larger than 32 KiB or additions that would make the image's total copied content exceed 32 KiB. `"volume"` (default) defers the file as a lazy reference to be mounted at sandbox start.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the file registered for inclusion.

**Raises**

- `ValueError`: If `strategy="copy"` exceeds the per-file or total copied-content limit.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .add_local_file(
        "./config.yaml",
        "/app/config.yaml",
    )
    .add_local_file(
        "./entrypoint.sh",
        "/app/entrypoint.sh",
        mode=0o755,
        strategy="copy",
    )
)
```

### `Image.add_local_dir(src, dest, strategy, exclude, archive)`
source: https://docs.chalk.ai/compute-docs#Image.add_local_dir

Add an entire local directory into the image.

Each call is **additive** — the directory's files are appended to the set already registered on the image, so `add_local_dir` can be chained with other `add_local_dir` / `add_local_file` calls to merge sources from multiple locations.

Automatically respects `.gitignore` and `.chalkignore` files found at any level within `src` (each scoped to its directory subtree, matching go-git's behavior). The `.git/` directory is always excluded. Negation patterns (`!`) are supported. Symlinks whose target resolves outside `src` are skipped.

**Parameters**

- `src`: `str`
  Local directory path.
- `dest`: `str`
  Absolute destination directory in the image.
- `strategy`: `'copy' | 'volume'` = `'volume'`
  `"copy"` inlines all file contents into the image spec and rejects files larger than 32 KiB or additions that would make the image's total copied content exceed 32 KiB. `"volume"` (default) defers each file as a lazy reference to be mounted at sandbox start.
- `exclude`: `Sequence[str] | None` = `None`
  Additional glob patterns to skip (matched against relative paths). These are applied on top of patterns loaded from ignore files, e.g. `["data/**", "*.csv"]`.
- `archive`: `bool` = `False`
  When [`True`](https://docs.python.org/3/library/constants.html#True) (volume strategy only), tar the directory into a single file for upload instead of individual files. The caller is responsible for extracting at the destination.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the directory registered for inclusion.

**Raises**

- `ValueError`: If `strategy="copy"` exceeds the per-file or total copied-content limit.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .add_local_dir(
        "./src",
        "/app/src",
        exclude=["*.pyc", "__pycache__"],
    )
)
```

### `Image.add_local_python_source(modules)`
source: https://docs.chalk.ai/compute-docs#Image.add_local_python_source

Add local Python modules or packages to `/app` in the image. Wraps add_local_dir and add_local_file with sanity checking.

Raises ValueError if a name is dotted, cannot be found on the local Python path, or does not resolve to a pure-Python module or package.

**Examples**

```python
from chalkcompute import Image
img = Image.debian_slim().add_local_python_source("helpers", "mypkg")
```

### `Image.dockerfile_commands(commands)`
source: https://docs.chalk.ai/compute-docs#Image.dockerfile_commands

Add raw Dockerfile instructions.

These are injected verbatim into the generated Dockerfile. Each call is **additive** — instructions are appended to any previous build steps (including prior `dockerfile_commands` calls), not replacing them — so you can split a Dockerfile across multiple calls and interleave with other builder methods.

**Parameters**

- `commands`: `Sequence[str]`
  List of Dockerfile instructions (e.g. `["RUN echo hello", "EXPOSE 8080"]`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the Dockerfile commands appended.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .dockerfile_commands([
        "USER root",
        "EXPOSE 8080",
    ])
)
```

### `Image.env(variables)`
source: https://docs.chalk.ai/compute-docs#Image.env

Set environment variables in the image.

**Parameters**

- `variables`: `dict[str, str]`
  Mapping of variable names to literal strings. Pass Secret values in the runtime consumer's env instead (for example, Sandbox(env=...)).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the environment variables applied.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .env({
        "LOG_LEVEL": "DEBUG",
        "PORT": "8080",
    })
)
```

### `Image.workdir(path)`
source: https://docs.chalk.ai/compute-docs#Image.workdir

Set the working directory in the image.

**Parameters**

- `path`: `str`
  Absolute path for the working directory.

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the working directory set.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .workdir("/home/user/app")
)
```

### `Image.entrypoint(args)`
source: https://docs.chalk.ai/compute-docs#Image.entrypoint

Set the container entrypoint.

The `ENTRYPOINT` is the executable that always runs when the container starts. Unlike `cmd` — which provides _default arguments_ that callers can override at run time — the entrypoint is fixed: callers can't swap it out by passing a different command to `Container.run` or `kubectl exec`, only append to it.

Together, `ENTRYPOINT` and `CMD` form the full command that runs in the container:

- With only an entrypoint: `ENTRYPOINT` runs with no args.
- With only a CMD: the first element of `CMD` is treated as the executable and the rest as its arguments.
- With both: the full command is `ENTRYPOINT + CMD`, where `CMD` supplies the default (overridable) arguments.

Each call **replaces** any previously set entrypoint.

Use exec-form (`["python", "-m", "my_app"]`) rather than shell-form (`"python -m my_app"`) — exec-form skips the shell wrapper and makes signals (SIGTERM, SIGINT) reach your process directly, which matters for graceful shutdown.

**Parameters**

- `args`: `Sequence[str]`
  Entrypoint as exec-form list (e.g. `["/bin/bash"]`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the entrypoint set.

**Examples**

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .entrypoint(["python", "-m", "my_app"])
)
```

### `Image.cmd(args)`
source: https://docs.chalk.ai/compute-docs#Image.cmd

Set the container `CMD`.

The `CMD` is the default argument list passed to the container's entrypoint when the container starts. Unlike `entrypoint` — which sets the executable that always runs — `CMD` defines the _default arguments_ that can be overridden at run time (for example, by a `Container.run(command=[...])` call or a Kubernetes pod spec).

If no `entrypoint` is set, the first element of `CMD` is treated as the executable. If an `entrypoint` is set, `CMD` is appended to it.

**Parameters**

- `args`: `Sequence[str]`
  CMD as exec-form list (e.g. `["/bin/bash", "-l"]`).

**Returns**

`Image`

A new [`Image`](https://docs.chalk.ai/compute-docs#Image) with the CMD set.

**Examples**

Run `python -m my_app` by default, but allow the caller to override the module at run time:

```python
from chalkcompute import Image
img = (
    Image.debian_slim()
    .entrypoint(["python"])
    .cmd(["-m", "my_app"])
)
```

### `Image.as_image_uri_if_possible()`
source: https://docs.chalk.ai/compute-docs#Image.as_image_uri_if_possible

Return the image URI when no custom build is needed.

A bare `Image.base(...)` or `Image.debian_slim()` is equivalent to its base image string. Once the image carries build steps, lazy files, or image config, callers must keep sending the full image spec.

### `Image.from_proto(spec)`
source: https://docs.chalk.ai/compute-docs#Image.from_proto

Reconstruct an [`Image`](https://docs.chalk.ai/compute-docs#Image) from an `ImageSpec` (inverse of `to_proto`; volume files excluded).

### `Image.from_proto_bytes(data)`
source: https://docs.chalk.ai/compute-docs#Image.from_proto_bytes

Reconstruct an [`Image`](https://docs.chalk.ai/compute-docs#Image) from a serialized `ImageSpec` byte string.
