.db`) keyed by
> `path + inode + mtime + size` (host paths) or by the URL itself (URL
> fetches). It is **not** synced anywhere, so a row will show an empty
> `SOURCE` whenever:
>
> * the file was uploaded by a different machine, container, or teammate;
> * the file was uploaded by an earlier CLI version that did not yet
> track its origin (those entries backfill the next time the file is
> matched by the local cache);
> * the host file has been moved, renamed, or its `inode/mtime/size` has
> changed since upload (the cache key no longer matches and the
> mapping is treated as missing until the next upload).
>
> There is no way to recover the source of a file uploaded from another
> machine – the server stores only `uuid`, `sha256`, `size`,
> `created_at`, and `updated_at`.
```bash theme={null}
contree file ls
contree file ls --since 1d --limit 200
contree file ls -q # uuid + sha256 + source only
contree -o json file ls | jq 'select(.source != "")'
```
\$ contree file ls --help`usage: contree file ls [-h] [--since SINCE] [--until UNTIL] [--limit LIMIT] [-q]List remote files uploaded to the project and, when present in the local upload cache, show whatproduced them under the 'source' column: either an absolute host path (for run --file / COPYuploads) or a URL (for ADD URL). source is THIS-MACHINE ONLY: the mapping lives in the local CLIcache ($CONTREE_HOME/cli/sessions/.db) and is never synced. Files uploaded from adifferent host, by a teammate, or before tracking landed will show an empty source -- that isexpected, not a bug. Use the remote uuid or sha256 for cross-machine identity.options: -h, --help show this help message and exit --since SINCE Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show files before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --limit LIMIT Stop after this many files and warn if more are available -q, --quiet Emit only uuid, sha256, and source columns. source is populated only for files uploaded from this very machine.examples: contree file ls contree file ls --since 1d contree file ls --limit 5000 contree file ls-q # uuid + sha256 + source contree -o json file ls`
## Pending files
Pending files accumulate until the next `contree run` consumes them.
Explicit `--file` flags on `contree run` take priority over pending files
at the same path.
Files are uploaded with SHA256 dedup – identical content is not re-uploaded.
## See also
* [Working with Files](../tutorial/files) – full tutorial on file injection and editing
* [run - Execute a command in the sandbox](./run) – the `--file` syntax for inline file injection
# grep - Search file contents in the image
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/grep
Search file contents in the session image using server-side ripgrep, without
spawning a sandbox.
## Examples
```bash theme={null}
# Search the session cwd for a pattern
contree grep TODO
# Search a specific file or directory
contree grep "^PermitRootLogin" /etc/ssh/sshd_config
# Search the whole image (PATH omitted defaults to cwd; pass / for the root)
contree grep TODO /
# Restrict to a glob, limit match count, case-insensitive
contree grep --glob '*.py' --max-count 5 --case insensitive def /app
# 2 lines of context before and after each match, like grep -C 2
contree grep -C 2 ERROR /var/log/app.log
# asymmetric context, like grep -A/-B (--after/--before also work)
contree grep -B 1 -A 3 ERROR /var/log/app.log
# JSON output for scripting (one row per match)
contree -o json grep TODO /app
```
## Output
The default format prints classic `PATH:LINE:TEXT` lines, one per match –
the same shape as running `grep -rn` locally:
```
/etc/hosts:1:127.0.0.1 localhost
/etc/hosts:2:255.255.255.255 broadcasthost
```
With `-A`/`-B`/`-C`, context lines use `-` instead of `:` and a `--` line
separates output groups that aren’t directly adjacent – the same
convention GNU grep and ripgrep use:
```
/var/log/app.log-4-starting request
/var/log/app.log:5:ERROR: connection refused
/var/log/app.log-6-retrying
--
/var/log/app.log-40-starting request
/var/log/app.log:41:ERROR: timeout
/var/log/app.log-42-giving up
```
Structured formats (`-o json`, `-o csv`, `-o table`, …) instead get one
row per match/context line with the columns `path`, `line_number`,
`absolute_offset`, `line_bytes`, `line_text`, `type` (`match` or
`context`).
## Help output
\$ contree grep --help``usage: contree grep [-h] [--glob GLOB] [--max-count MAX_COUNT] [--max-total MAX_TOTAL] [--case {sensitive,insensitive,smart}] [-B NUM] [-A NUM] [-C NUM] [--raw] pattern [path ...]Search file contents in the session image.Uses the /inspect/ API (server-side ripgrep) to search file contentswithout spawning an instance. Defaults to the session working directory(set via `cd`) when PATH is omitted -- pass `/` explicitly to search thewhole image. PATH may be repeated to search multiple roots in one call.positional arguments: pattern Regex pattern to search for (Rust regex syntax) path File(s)/directory(ies) inside image (defaults to session cwd); may be repeated to search multiple rootsoptions: -h, --help show this help message and exit --glob GLOB Restrict search to files matching this glob (e.g. '*.py') --max-count MAX_COUNT Stop after this many matches per file --max-total MAX_TOTAL Stop after this many matches total (server default: 1000) --case {sensitive,insensitive,smart} Case sensitivity (default: sensitive) -B, --before-context, --before NUM Show NUM lines of context before each match (max 50) -A, --after-context, --after NUM Show NUM lines of context after each match (max 50) -C, --context NUM Show NUM lines of context before and after (overridden by -A/-B) --raw Print raw JSON (preserves submatches/patterns/truncated)for coding agents: read-only command (inspect API, no instance spawn) defaults to session cwd when PATH is omitted; pass / to search whole image exit code 1 means zero matches (like POSIX grep), not an error exit code 2 means the search was truncated before finding anything -- inconclusive, not confirmed zero matches default format prints classic PATH:LINE:TEXT; use -o json/csv/... for rows use --raw to preserve submatches/patterns/truncated as JSON -A/-B/--context add ripgrep-side context lines (server-computed, not local)agent note: Before using this command in an automated workflow, read: contree agent``
## Behavior
`grep` searches file contents directly in the image filesystem – no sandbox
is started. Matching is powered by ripgrep with Rust regex syntax and
linear-time matching; symlinks are never followed, hidden files are searched,
and binary files (containing a NUL byte) are skipped.
When PATH is omitted, the search defaults to the session working directory
(set via `cd`), consistent with [ls - List files in the image](./ls) and [cat - Show file content from the image](./cat). Pass `/` explicitly
to search the whole image.
`-B`/`--before-context`/`--before`, `-A`/`--after-context`/`--after`, and
`-C`/`--context` request extra lines of context around each match (server
-side, up to 50 lines each way) – `-C` sets both directions unless
overridden by an explicit `-A`/`-B`. This mirrors GNU grep/ripgrep’s own
flags; `-C` is a deliberate one-off exception to this CLI’s usual
uniqueness rule for short flags (`-C` is `--cwd` everywhere else).
Nested match detail (`submatches`) is dropped from structured output; pass
`--raw` to get the full JSON response, including `submatches`, the searched
`patterns`, and the `truncated` flag – useful for `jq` pipelines.
The command exits with status 1 when no matches are found (like POSIX
`grep`), so it composes in shell conditionals:
```bash theme={null}
if contree grep ERROR /var/log/app.log > /dev/null; then
echo "found errors"
fi
```
Exit status 2 is different from 1: it means the search was truncated
(`max_total`/the server deadline was hit) *before finding anything at all*,
which is inconclusive rather than a confirmed zero-match result. A truncated
search that still found at least one match exits 0/none as usual –
`truncated` only affects the exit code when combined with zero matches.
## See also
* [ls - List files in the image](./ls) – list files before searching
* [cat - Show file content from the image](./cat) – view a single file’s full contents
# images - List and import images
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/images
List images in the project. Images are the filesystem snapshots that sandboxes
run from – every non-disposable `contree run` produces a new one.
## Examples
```bash theme={null}
# List all images
contree images
# Filter by tag prefix
contree images --prefix=ubuntu
# Include untagged intermediate images too
contree images -a
# Images created in the last hour
contree images --since=1h
# Find a specific image by UUID
contree images --uuid=3f2a7b1c-9d2e-4f60-8a1b-5c3d7e9f0a2b
# JSON output for scripting
contree -o json images | jq -r '.tag'
```
## Help output
\$ contree images --help```usage: contree images [-h] [--prefix PREFIX] [-i UUID] [-a] [--since SINCE] [--until UNTIL] [--limit LIMIT] {list,ls,import} ...List and import sandbox images.Without a subcommand, lists images (same as ``images list``).Subcommands: list (ls) List images with filtering and pagination import Import image from a container registrypositional arguments: {list,ls,import} list (ls) List images import Import image from container registryoptions: -h, --help show this help message and exit --prefix PREFIX Filter by tag prefix -i, --uuid UUID Filter by image UUID -a, --all Include untagged images (default: tagged only) --since SINCE Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show images before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --limit LIMIT Stop after this many images and warn if more are available (default: 3000)examples: contree images --prefix=ubuntu contree images list --all contree images import ubuntu:latest contree images import ubuntu:{latest,noble,jammy} contree images import ghcr.io/owner/image:tagfor coding agents: `images` / `images list` is read-only `images import` spawns async import operations and polls until completion supports brace expansion for batch imports Ctrl+C cancels all active import operationsagent note: Before using this command in an automated workflow, read: contree agent```
## Filtering
`--prefix` matches the beginning of the tag string. This is useful for
browsing available base images:
```bash theme={null}
contree images --prefix=python
contree images --prefix=common/
```
`--since` and `--until` accept either ISO timestamps or duration intervals
like `1h`, `30m`, `7d`.
## Subcommands
### `images list`
`contree images list` (alias `ls`) is the explicit form of the bare
`contree images` invocation. Both share the same flag set – pick the
explicit form when you want a command that reads symmetrically with
`images import`, or in scripts that already use the subcommand style
everywhere.
\$ contree images list --help`usage: contree images list [-h] [--prefix PREFIX] [-i UUID] [-a] [--since SINCE] [--until UNTIL] [--limit LIMIT]options: -h, --help show this help message and exit --prefix PREFIX Filter by tag prefix -i, --uuid UUID Filter by image UUID -a, --all Include untagged images (default: tagged only) --since SINCE Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show images before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --limit LIMIT Stop after this many images and warn if more are available (default: 3000)`
### `images import`
`contree images import REF [REF ...]` pulls one or more images from an
external OCI registry into the project and waits for the import
operation to finish. Each reference may be a `docker://` URL or any
form the platform accepts; multiple refs are imported sequentially with
shared credentials, and Ctrl-C cancels the in-flight operation cleanly.
\$ contree images import --help`usage: contree images import [-h] [--username USERNAME] [--password PASSWORD] [-t TIMEOUT] refs [refs ...]positional arguments: refs Image references (supports brace expansion)options: -h, --help show this help message and exit --username USERNAME Registry username (enables credentials) --password PASSWORD Registry password (prompted securely if --username given) -t, --timeout TIMEOUT Import timeout in secondsexamples: contree images import ubuntu:latest contree images import --timeout 600 ubuntu:latest contree images import docker.io/ubuntu:latest contree images import docker://docker.io/ubuntu:latest contree images import ghcr.io/ubuntu/ubuntu:latest contree images import ubuntu:{latest,noble,jammy}for coding agents: mutating command — creates import operations all formats are normalised to docker://registry/path:tag polls every 5 seconds until all operations complete Ctrl+C cancels all active import operations`
## See also
* [tag - Tag or untag an image](./tag) – assign a tag to an image
* [Your First Sandbox](../tutorial/first-steps) – browsing and choosing images
# Command Reference
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/index
\$ contree --help``usage: contree [-h] [-v] [-p PROFILE] [--token TOKEN] [-u URL] [-P PROJECT] [-c CONFIG_PATH] [-L {debug,info,warning,error,critical}] [-o {csv,default,json,json-pretty,plain,table,toml,tsv}] [-S SESSION_KEY] {use,ci,run,r,build,bd,images,i,img,tag,t,ps,kill,show,operation,op,ls,cat,grep,cp,export,file,f,session,s,auth,skill,cd,env,agent,man,shell,sh} ...ConTree CLI - command-line client for the ConTree sandbox platform.Run sandboxes, manage images, inspect filesystems, and track operationsthrough the ConTree REST API.Authentication: Bearer token + project ID. Default API URL: https://api.tokenfactory.nebius.com/sandboxes/ Use `contree auth --help` to configure persistent credentials.Coding-agent bootstrap (important): Agents should read `contree agent` before executing task commands.positional arguments: {use,ci,run,r,build,bd,images,i,img,tag,t,ps,kill,show,operation,op,ls,cat,grep,cp,export,file,f,session,s,auth,skill,cd,env,agent,man,shell,sh} use (ci) Set or show current session image run (r) Spawn a sandbox instance build (bd) Build image from Dockerfile images (i, img) List and import images tag (t) Tag an image ps List operations (alias for `operation ls`) kill Cancel operations (alias for `operation cancel`) show Show operation result (alias for `operation show`) operation (op) Manage operations (list/show/cancel) ls List files in image cat Show file content from image grep Search file contents in image cp Copy file from image to local path export Export image rootfs or a subtree as tar.gz file (f) Manage files in session image session (s) Manage session branches and history auth Configure authentication skill Manage agent skills cd Change working directory env Manage session environment variables agent (man) Show manual shell (sh) Interactive shell modeoptions: -h, --help show this help message and exit -v, --version show program's version number and exit -p, --profile PROFILE Use this profile for the current command --token TOKEN API token (overrides profile for this invocation) -u, --url URL API base URL (overrides profile for this invocation) -P, --project PROJECT Project ID (overrides profile for this invocation) -c, --config CONFIG_PATH Config file path (default: /home/runner/.config/contree/auth.ini) -L, --log-level {debug,info,warning,error,critical} Logging level (default: info) -o, --format, --output {csv,default,json,json-pretty,plain,table,toml,tsv} Output format (default: default) -S, --session SESSION_KEY Session key override (alternative to CONTREE_SESSION)examples: contree use tag:ubuntu:latest set session image eval $(contree use tag:ubuntu:latest) set + export env var contree run -- uname -a run command in session image contree run --shell -- 'echo hi' shell mode contree run --file ./app.py:/app.py --disposable -- python /app.py contree run --file ./src:/app/src -- make -C /app/src contree images --prefix=ubuntu contree ps -q contree op ls same as `contree ps` contree op show UUID1 UUID2 multi-UUID show contree op cancel UUID1 UUID2 multi-UUID cancel (or --all) contree show OPERATION_UUID contree tag IMAGE_UUID latest contree ls /etc list files in session image contree cat /etc/os-release show file from session image contree grep TODO /app search file contents in session image contree auth save token (secure prompt) contree auth switch staging contree man user manual contree agent coding-agent manualfor users: contree manfor coding agents (required bootstrap): 1) read: contree agent 2) inspect command syntax: contree --help 3) only then execute task commandsbefore running tasks: ensure auth exists; if missing/invalid, ask user to run `contree auth`high-signal read-only commands: contree images | ps | show UUID | ls [PATH] | cat PATH contree grep PATTERN [PATH] | session | session showmutating commands (change remote or local session state): contree use IMAGE | run -- CMD | file edit PATH | file cp SRC DEST contree tag UUID TAG | kill UUID | cd PATH | session checkout BRANCHenvironment variables: CONTREE_PROFILE Active config profile (selects which profile to use) CONTREE_SESSION Explicit session name (for multi-terminal workflows). If unset, contree auto-generates +<8hex> (derived from profile+ppid+tty); export your own for stable reuse. You can also pass -S/--session instead. CONTREE_SESSION_DB Path to session SQLite database CONTREE_NO_UPDATE_CHECK Set to any value to disable PyPI update checksregistration-time fallbacks (only read by `contree auth`, not at runtime): CONTREE_TOKEN / NEBIUS_API_KEY Token used when --token is omitted CONTREE_URL URL used when --url is omitted CONTREE_PROJECT / NEBIUS_AI_PROJECT Project ID used when --project is omitted``
> [card] [auth - Configure credentials and profiles](./auth)
> [card] [use - Choose an image for the session](./use)
> [card] [run - Execute a command in the sandbox](./run)
> [card] [build - Build an image from a Dockerfile](./build)
> [card] [images - List and import images](./images)
> [card] [tag - Tag or untag an image](./tag)
> [card] [operation - Manage operations](./operation)
> [card] [ps - List activity](./ps)
> [card] [show - Inspect an operation](./show)
> [card] [kill - Cancel operations](./kill)
> [card] [ls - List files in the image](./ls)
> [card] [cat - Show file content from the image](./cat)
> [card] [grep - Search file contents in the image](./grep)
> [card] [cp - Download a file from the image](./cp)
> [card] [cd - Change session working directory](./cd)
> [card] [env - Manage session environment variables](./env)
> [card] [file - Stage file edits for the next run](./file)
> [card] [session - Manage sessions, branches, history](./session)
> [card] [shell - Interactive REPL](./shell)
> [card] [skill - Install agent skills](./skill)
> [card] [agent - Coding-agent manual](./agent)
# kill - Cancel operations
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/kill
> [!NOTE]
>
> **`contree kill` is a top-level shortcut for [operation cancel](./operation) (`contree op cancel`).**
>
> Both share one argparse setup and one handler. The top-level `kill`
> accepts the same positional UUIDs and `--all` flag as `op cancel`,
> including multiple UUIDs in a single invocation. See the
> [operation - Manage operations](./operation) page for the full description.
Cancel running operations. Only active operations (PENDING, ASSIGNED,
EXECUTING) can be cancelled.
## Examples
```bash theme={null}
# Cancel a specific operation
contree kill 3f2a7b...
# Cancel multiple operations in one call
contree kill 3f2a7b... a1b2c3... 9d8e7f...
# Cancel all active operations
contree kill --all
```
## Help output
\$ contree kill --help```usage: contree kill [-h] [-a] [UUID_OR_REF ...]Manage operations (list, inspect, cancel).Aggregates ps/show/kill under a single namespace, and adds multi-UUIDsupport to ``show`` and ``cancel`` so several operations can be actedon in one invocation.Subcommands: list (ls) List operations. ``contree ps`` is an alias. show UUID [UUID...] Show one or more operation results. cancel UUID [UUID...] Cancel one or more operations (or --all).positional arguments: UUID_OR_REF Operations to cancel. Accepts UUIDs and session-history references (HEAD, HEAD~N, @, @N, @-N, @+N, :N, bare N).options: -h, --help show this help message and exit -a, --all Cancel every active operationfor coding agents: list/show are read-only; cancel mutates remote state show and cancel accept multiple UUIDs in one invocation show supports @N session-history references inherited from `contree show`agent note: Before using this command in an automated workflow, read: contree agent```
## Behavior
The CLI sends a `DELETE` request to the API for each UUID. The
operation transitions to `CANCELLED` status. If the sandbox is already
running, execution is interrupted.
`--all` finds and cancels every active operation in the project. When
`--all` is combined with explicit UUIDs, `--all` wins and the explicit
UUIDs are ignored with a `WARNING`.
On per-UUID API errors (e.g. 404 for an unknown UUID), the command
logs the failure and continues with the remaining UUIDs, exiting with
status `1` at the end.
## See also
* [operation - Manage operations](./operation) — the canonical command (`contree kill` is its shortcut)
* [ps - List activity](./ps) — list operations to find UUIDs
* [run - Execute a command in the sandbox](./run) — Ctrl-C during `contree run` also cancels the operation
# ls - List files in the image
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/ls
List files and directories in the session image without spawning a sandbox.
## Examples
```bash theme={null}
# List root directory
contree ls /
# List a specific directory
contree ls /etc/nginx
# JSON output with file metadata
contree -o json ls /usr/bin
```
## Help output
\$ contree ls --help``usage: contree ls [-h] [path]List files in the session image.Uses the /inspect/ API to list directory contents without spawning aninstance. Defaults to the session working directory (set via `cd`).In default format, the API returns a pre-formatted text listing. Instructured formats (json, csv, etc.) the response is cached per(image, path) for instant repeat queries.positional arguments: path Path inside image (defaults to session cwd)options: -h, --help show this help message and exitfor coding agents: read-only command (inspect API, no instance spawn) defaults to session cwd when PATH is omitted use -o json for cacheable structured listingsagent note: Before using this command in an automated workflow, read: contree agent``
## Output
Each entry shows path, size, permissions (octal), owner, group, modification
time, and type (`d` for directory, `l` for symlink, `-` for file).
This command reads the image filesystem directly – no sandbox is started and
no resources are consumed.
## See also
* [cat - Show file content from the image](./cat) – view file contents
* [cp - Download a file from the image](./cp) – download a file locally
* [Your First Sandbox](../tutorial/first-steps) – inspecting the filesystem
# operation - Manage operations
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/operation
Manage operations under a single namespace. Aggregates `ps` (list),
`show` (inspect), and `kill` (cancel), and adds **multi-UUID support** to
`show` and `cancel` so several operations can be acted on in one call.
`op` is the short alias.
## Subcommands
| Subcommand | Aliases | Description |
| - | - | - |
| `list` | `ls` | List operations. Same flags as `contree ps`. |
| `show UUID [UUID...]` | `sh` | Show one or more operation results. |
| `wait UUID [UUID...]` | `w` | Wait for operations to reach a terminal status (or `--all`). |
| `cancel UUID [UUID...]` | `kill`, `k` | Cancel one or more operations (or `--all`). |
## Examples
```bash theme={null}
# List active operations (same as `contree ps`)
contree op list
contree op ls
contree op ls -a --status FAILED # all flags from ps are accepted
# Inspect a single operation
contree op show 3f2a7b...
# Inspect several operations at once
contree op show 3f2a7b... a1b2c3... 9d8e7f...
# History references (inherited from `contree show`)
contree op show @5 @4 @3
# Cancel one or more operations
contree op cancel 3f2a7b...
contree op cancel a1b2c3... 9d8e7f...
# Cancel every active operation
contree op cancel --all
```
## Help output
The top-level `op` command is a dispatcher: by itself it only prints
usage and routes to the three subcommands described below.
\$ contree op --help```usage: contree operation [-h] {list,ls,show,sh,cancel,kill,k,wait,w,events,ev} ...Manage operations (list, inspect, cancel).Aggregates ps/show/kill under a single namespace, and adds multi-UUIDsupport to ``show`` and ``cancel`` so several operations can be actedon in one invocation.Subcommands: list (ls) List operations. ``contree ps`` is an alias. show UUID [UUID...] Show one or more operation results. cancel UUID [UUID...] Cancel one or more operations (or --all).positional arguments: {list,ls,show,sh,cancel,kill,k,wait,w,events,ev} list (ls) List operations show (sh) Show one or more operation results cancel (kill, k) Cancel one or more operations wait (w) Wait for operations to reach a terminal status events (ev) Print an operation's full raw event logoptions: -h, --help show this help message and exitfor coding agents: list/show are read-only; cancel mutates remote state show and cancel accept multiple UUIDs in one invocation show supports @N session-history references inherited from `contree show`agent note: Before using this command in an automated workflow, read: contree agent```
## `op list` – dynamic columns
`contree op list` (alias `op ls`) accepts the same filter flags as
`contree ps` (`-a`, `--status STATUS`, `-K KIND`, `--since`,
`--until`, `-q`/`--quiet`) and shares its rendering pipeline. Reach
for it when you want the operations namespace to feel symmetric with
the multi-UUID `show` and `cancel`; otherwise `contree ps` is just
as good. `-S` is the global session flag and only works BEFORE the
subcommand.
\$ contree op list --help`usage: contree operation list [-h] [-q] [-a] [--status {P,PENDING,A,ASSIGNED,E,EXECUTING,S,SUCCESS,F,FAILED,C,CANCELLED}] [-k {image_import,instance}] [--since SINCE] [--until UNTIL] [-M SHOW_MAX]List operations. ``contree ps`` is an alias of this command.options: -h, --help show this help message and exit -q, --quiet Only show UUIDs, useful for scripting -a, --all Show all operations (default: active only) --status {P,PENDING,A,ASSIGNED,E,EXECUTING,S,SUCCESS,F,FAILED,C,CANCELLED} Filter by status (default: EXECUTING only, unless -a is used) -k, --kind {image_import,instance} Filter by operation kind --since SINCE Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show operations before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. -M, --show-max SHOW_MAX Show at most this many operations, useful for --all with large history (default: 1000)for coding agents: read-only command`
The listing renders **every scalar top-level field** the API returns,
not a hard-coded subset. When the server adds a new field (for example
`cost`, `project_id`, `started_at`), it appears in the output without a
CLI release. Nested structures (`metadata`, `result`, `tags`) are
filtered out – use `op show UUID` for the detail view.
Known fields are lightly typed:
| Field | Transform |
| - | - |
| `created_at`, `started_at`, `finished_at`, `updated_at` | parsed to UTC datetime |
| `duration` | wrapped as `timedelta` (`total_seconds()` in JSON) |
| `error` | `None` is rendered as empty string |
Column order follows the API response, with one exception: **`error`
is pinned to the last column**. Long free-form error messages would
otherwise push the rest of the row out of alignment.
## `op show` – multiple UUIDs
Each UUID is fetched and rendered through the same code path as
`contree show`, so cached terminal results and history references work
uniformly. Accepted reference forms (mirroring `session rollback`
syntax with a git-style alias):
* `@`, `:`, or `HEAD` – the operation at the active branch tip.
* `@N` (or `:N`, bare `N`) – absolute history id.
* `@-N`, `:-N`, or `HEAD~N` – walk N steps back from the tip.
* `HEAD~` – shorthand for `HEAD~1`.
* `@+N` (or `:+N`) – walk N steps forward from the tip, picking the
latest child at each branch point.
On API errors (e.g. 404 for an unknown UUID), the command logs the
failure and continues with the remaining UUIDs, exiting with status
`1` at the end.
\$ contree op show --help``usage: contree operation show [-h] [--raw] UUID_OR_REF [UUID_OR_REF ...]Fetch and display the result of each given operation. Same per-UUID behaviour as `contree show`:terminal results are cached; @N references resolve against session history.positional arguments: UUID_OR_REF Operations to inspect. Accepts UUIDs and session-history references: @ or HEAD for the active branch tip, @N for an absolute history id, @-N or HEAD~N for N steps back, @+N for N steps forward.options: -h, --help show this help message and exit --raw Print each operation's JSON payload as JSONL (one object per line) to stdout. Round-trips through the typed operation model, so fields the model doesn't know about are dropped. Skips formatter routing and derived columns; streams cleanly into `jq -c`. Useful for debugging or for fields the table view omits.for coding agents: read-only command accepts multiple UUIDs; each rendered as its own row``
> [!NOTE]
>
> With table output (`-o table`) and several UUIDs, each operation
> currently renders as its own mini-table. Use `default` or `json` for a
> unified stream view across multiple UUIDs.
## `op wait` – block until completion
Poll the given operations until each reaches a terminal status
(`SUCCESS`, `FAILED`, `CANCELLED`) and print one row per completion
with the columns `uuid`, `status`, `exit_code`, `timed_out`,
`duration` (and every other scalar field the API returns; `error` is
pinned to the last column).
`--all` waits for every currently active operation in the project.
`--timeout SECONDS` (default `60`) caps the wait — when the deadline
hits, the command emits one extra row per unfinished operation with
`timed_out=true` and the operation’s last observed status (e.g.
`EXECUTING`), then exits with status `1`.
`status` is the server’s word: it reflects orchestration (did the
API run the job?), not what the sandbox process did with its exit
code. The exit code is a separate column. The CLI’s own exit status
is `1` whenever any operation finished non-`SUCCESS`, or the actual
`exit_code` when a `SUCCESS` op exited non-zero — so
`op wait UUID && next-step` composes correctly with sandbox commands
like `run -- false`.
> [!NOTE]
>
> `op wait` is a **pure observer**: it polls operation status and
> prints rows, but it **never updates session state**. In particular,
> the `detached-` branch created when you ran
> `contree run -d` keeps pointing at the **starting** image — `op wait` does not advance it to the result image. The pattern therefore
> fits non-image-producing runs (`--disposable`) most cleanly; for
> non-disposable fan-out, the result image of each leg lives only on
> the server and you must recover it explicitly (see the non-disposable
> example below).
> [!WARNING]
>
> `--all` is **project-scoped**. If multiple agents (or multiple shell
> sessions) share the same project, `op wait --all` will block on every
> active operation across all of them — not just the ones you launched.
> The wait still completes correctly; it just waits for more than you
> might expect. For multi-agent setups, prefer the explicit
> `op wait UUID1 UUID2 ...` form with the UUIDs you actually own.
\$ contree op wait --help`usage: contree operation wait [-h] [-a] [-t TIMEOUT] [UUID_OR_REF ...]Poll the given operations until each reaches a terminal status (SUCCESS, FAILED, CANCELLED) andprint one row per completion. With --all, waits for every currently active operation (PENDING,ASSIGNED, EXECUTING).positional arguments: UUID_OR_REF Operations to wait for. Accepts UUIDs and session-history references (HEAD, HEAD~N, @, @N, @-N, @+N, :N, bare N).options: -h, --help show this help message and exit -a, --all Wait for every active operation -t, --timeout TIMEOUT Fail with exit code 1 if not all operations reach a terminal status within this many seconds (default: 60)for coding agents: read-only command (polls the API; no state mutation) fails with exit code 1 if--timeout is hit before all complete exit code 1 also when any operation finished non-SUCCESS`
Preferred — `--disposable` fan-out, no image to track. Note the
global `-o json` before `run` so `jq` sees JSON; the default
formatter is plain.
```bash theme={null}
A=$(contree -o json run -d --disposable -- pytest tests/a | jq -r .uuid)
B=$(contree -o json run -d --disposable -- pytest tests/b | jq -r .uuid)
C=$(contree -o json run -d --disposable -- pytest tests/c | jq -r .uuid)
contree op wait "$A" "$B" "$C"
contree op show "$A" "$B" "$C" # stdout/stderr per leg
```
Non-disposable fan-out — must recover the chosen leg’s image yourself:
```bash theme={null}
A=$(contree -o json run -d -- apt-get install -y curl | jq -r .uuid)
B=$(contree -o json run -d -- apt-get install -y wget | jq -r .uuid)
contree op wait "$A" "$B"
# Pull the result image out and bind it back into the session,
# or tag it for later reuse.
IMG_A=$(contree -o json op show "$A" | jq -r .image)
contree use "$IMG_A"
contree tag "$IMG_A" feature/curl-tools
```
Block on the whole project (5 min cap):
```bash theme={null}
contree op wait --all --timeout 300
```
## `op cancel` – multiple UUIDs or `--all`
Either pass UUIDs explicitly or use `--all` to cancel every active
operation (`PENDING`, `ASSIGNED`, `EXECUTING`). Combining both is allowed:
`--all` wins, and the explicit UUIDs are ignored with a `WARNING`. As
with `op show`, errors on individual UUIDs do not abort the run; the
command exits `1` if any cancellation failed.
\$ contree op cancel --help`usage: contree operation cancel [-h] [-a] [UUID_OR_REF ...]Cancel each given operation. With --all, cancels every active operation (PENDING, ASSIGNED,EXECUTING).positional arguments: UUID_OR_REF Operations to cancel. Accepts UUIDs and session-history references (HEAD, HEAD~N, @, @N, @-N, @+N, :N, bare N).options: -h, --help show this help message and exit -a, --all Cancel every active operationfor coding agents: mutating command pass UUIDs to cancel specific operations or --all foreverything`
```bash theme={null}
# Mixed: --all still wins, "ignored-1" is not cancelled
contree op cancel --all ignored-1
```
## Comparison with the top-level commands
`contree ps` and `contree kill` are top-level **shortcuts** that share
the same argparse setup and handler as `op list` / `op cancel`
respectively — there is no separate implementation. `contree show`
keeps its own single-UUID handler (the multi-UUID `op show` wraps it).
| Need | Use |
| - | - |
| List active operations | `contree ps` *or* `contree op ls` |
| Inspect one operation | `contree show UUID` *or* `contree op show UUID` |
| Inspect multiple | `contree op show UUID1 UUID2 ...` |
| Block on multiple | `contree op wait UUID1 UUID2 ...` |
| Block on everything active | `contree op wait --all` |
| Cancel one operation | `contree kill UUID` *or* `contree op cancel UUID` |
| Cancel multiple | `contree kill UUID1 UUID2 ...` *or* `contree op cancel UUID1 UUID2 ...` |
| Cancel everything active | `contree kill --all` *or* `contree op cancel --all` |
## See also
* [ps - List activity](./ps) – top-level shortcut for `op list`
* [show - Inspect an operation](./show) – single-UUID inspect (delegated to by `op show`)
* [kill - Cancel operations](./kill) – top-level shortcut for `op cancel`
* [run - Execute a command in the sandbox](./run) – the command that creates operations
# ps - List activity
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/ps
> [!NOTE]
>
> **`contree ps` is a top-level shortcut for [operation list](./operation) (`contree op ls`).**
>
> Both share one argparse setup and one handler — `ps` exists for the
> Docker-like UX. New flags or columns added to `operation list` apply
> automatically here. See the [operation - Manage operations](./operation) page for the full
> description of dynamic columns, error handling, and multi-UUID
> workflows in the operation namespace.
List operations and their statuses. By default shows only active operations
(PENDING, ASSIGNED, EXECUTING).
## Examples
```bash theme={null}
# Show active operations
contree ps
# Show all operations (including completed)
contree ps -a
# UUIDs only (for scripting)
contree ps -q
# Filter by status (note: --status, not -S; -S is the global session flag)
contree ps --status FAILED
# Filter by kind
contree ps -k instance
# Operations from the last hour
contree ps -a --since=1h
# Pipe to other commands
contree ps -q | xargs -I {} contree show {}
```
## Help output
\$ contree ps --help```usage: contree ps [-h] [-q] [-a] [--status {P,PENDING,A,ASSIGNED,E,EXECUTING,S,SUCCESS,F,FAILED,C,CANCELLED}] [-k {image_import,instance}] [--since SINCE] [--until UNTIL] [-M SHOW_MAX]Manage operations (list, inspect, cancel).Aggregates ps/show/kill under a single namespace, and adds multi-UUIDsupport to ``show`` and ``cancel`` so several operations can be actedon in one invocation.Subcommands: list (ls) List operations. ``contree ps`` is an alias. show UUID [UUID...] Show one or more operation results. cancel UUID [UUID...] Cancel one or more operations (or --all).options: -h, --help show this help message and exit -q, --quiet Only show UUIDs, useful for scripting -a, --all Show all operations (default: active only) --status {P,PENDING,A,ASSIGNED,E,EXECUTING,S,SUCCESS,F,FAILED,C,CANCELLED} Filter by status (default: EXECUTING only, unless -a is used) -k, --kind {image_import,instance} Filter by operation kind --since SINCE Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show operations before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. -M, --show-max SHOW_MAX Show at most this many operations, useful for --all with large history (default: 1000) (default: 1000)for coding agents: list/show are read-only; cancel mutates remote state show and cancel accept multiple UUIDs in one invocation show supports @N session-history references inherited from `contree show`agent note: Before using this command in an automated workflow, read: contree agent```
## Operation statuses
| Status | Meaning |
| - | - |
| `PENDING` | Queued, waiting for resources |
| `ASSIGNED` | Assigned to a worker |
| `EXECUTING` | Running |
| `SUCCESS` | Completed successfully |
| `FAILED` | Completed with an error |
| `CANCELLED` | Cancelled by the user |
Without `-a`, only `PENDING`, `ASSIGNED`, and `EXECUTING` are shown.
## Dynamic output columns
`ps` renders every scalar top-level field the API returns (not a fixed
subset), so new server fields appear automatically. `error` is pinned
to the last column. See [operation - Manage operations](./operation) for the full description.
## See also
* [operation - Manage operations](./operation) — the canonical command (`contree ps` is its shortcut)
* [show - Inspect an operation](./show) — inspect a specific operation
* [kill - Cancel operations](./kill) — cancel a running operation
* [Scripting & Automation](../tutorial/workflows) — monitoring and scripting patterns
# run - Execute a command in the sandbox
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/run
Spawn a sandbox instance from the session image and execute a command.
## Help output
\$ contree run --help```usage: contree run [-h] [-t TIMEOUT] [-C CWD] [-e ENV] [-H HOSTNAME] [-D] [-I] [-s] [-F FILE] [--file-excludes PATTERN [PATTERN ...]] [-T TRUNCATE] [--preserve-env] [-d] [--use IMAGE] ...Spawn a sandbox instance from the current session image and execute a command.Uses the image from the active session (set via `contree use IMAGE`),or an image specified inline via ``--use IMAGE``.Commands are passed after -- separator; without --, the firstpositional arg is the command.By default the CLI polls until the operation reaches a terminalstatus (SUCCESS, FAILED, CANCELLED) and prints stdout/stderr.Use -d/--detach to exit immediately after spawning.File attachments: Use --file to inject host files or directories into the sandbox before execution. Files are uploaded to the API (with SHA256 dedup) and mounted at the specified instance path. Ownership and permissions default to host file stat unless overridden. Note: non-disposable runs persist filesystem changes into a new image. Files attached once are already part of that image and do not need re-attachment. Use --disposable to discard changes after execution. Format: host_path[:instance_path][:uUID][:gGID][:mMODE] host_path all defaults from stat host_path:/inst/path point a destination path host_path:m0755 override only mode host_path:/inst/path:u0:g0:m0755 all explicit host_path:uroot:groot uid/gid by name (local) Tagged options (u/g/m) can appear in any order after host_path. instance_path is detected by its leading /. For directory attachments, files are walked recursively and default excludes are applied: .*, .git, *.pyc, __pycache__, .venv, .mypy_cache, .pytest_cache, node_modules, dist, build. Add extra patterns with --file-excludes. The CLI also keeps a local upload cache keyed by path+inode+mtime+size and reuses known file UUIDs to avoid unnecessary re-upload checks/uploads. Note: named uid/gid (e.g. uroot) are resolved locally via pwd/grp — use numeric IDs if unsure about host/sandbox mismatch.positional arguments: command_args Command and arguments (after --)options: -h, --help show this help message and exit -t, --timeout TIMEOUT Timeout in seconds (default: 120) -C, --cwd CWD Working directory inside sandbox, absolute path or empty string for use sandbox WORKDIR (default: ) -e, --env ENV Environment variable KEY=VALUE (repeatable) -H, --hostname HOSTNAME Container hostname (default: linuxkit) -D, --disposable Drop filesystem changes after run -I, --interpreter Interpreter (shebang) mode. Read the script file given as the first argument, strip the #! line, and send the body as stdin to /bin/sh -s. Usage: #!/usr/bin/env -S contree run -I -s, --shell Join command args into a single shell expression -F, --file FILE Attach file or directory (repeatable, dirs recurse). Format: host[:inst_path][:uUID][:gGID][:mMODE]. Tagged options (u/g/m) in any order; uid/gid resolved locally from pwd/grp; defaults from host stat. --file-excludes PATTERN [PATTERN ...] Additional glob exclude patterns for directory attachments (repeatable). -T, --truncate TRUNCATE Truncate output to N bytes (default: 65536) --preserve-env Preserve env vars from previous run (server-side) -d, --detach, --no-wait Exit immediately after spawning (do not wait for result) --use IMAGE Switch session to IMAGE before running (UUID or tag:NAME). Equivalent to 'contree use IMAGE' followed by 'run'. Recorded in session history and can be rolled back with 'session rollback'. (default: )examples: contree use ubuntu && contree run -- uname -a contree run --use tag:ubuntu:latest -- uname -a contree run --shell -- 'echo hello && ls /' contree run -e FOO=bar DEBUG=1 -- ./app contree run --file ./app.py:/app.py --disposable -- python /app.py contree run --file ./src:/app/src --file-excludes '*.log' -- make -C /app/src contree run -d -- sleep 3600for coding agents: `run` executes remotely inside the instance image (not on local host) local files/dirs must be mapped with --file to be available remotely mutates session image unless --disposable is set supports directory attachments via --file host_dir:/instance_dir local file cache avoids re-upload when path+inode+mtime+size unchanged returns command exit code when available default formatter prints raw stdout/stderr only use -o json for structured operation metadataagent note: Before using this command in an automated workflow, read: contree agent```
## Quick start with `--use`
Switch session to an image and run a command in one step:
```bash theme={null}
contree run --use tag:ubuntu:latest -- uname -a
```
This is equivalent to:
```bash theme={null}
contree use tag:ubuntu:latest
contree run -- uname -a
```
The image switch is recorded in session history and can be rolled back
with `contree session rollback`.
## Execution modes
**Direct command** (default):
```bash theme={null}
contree run uname -a
```
**Shell mode** (`-s` / `--shell`):
```bash theme={null}
contree run -s -- 'echo hello && ls /'
```
Joins all command args into a single shell expression.
**Interpreter mode** (`-I` / `--interpreter`):
```bash theme={null}
contree run -I ./script.sh
```
Reads a local script, strips the `#!` line, and sends the body as stdin
to `/bin/sh -s`. Enables shebang scripts:
```bash theme={null}
#!/usr/bin/env -S contree run -I
echo "runs inside a ConTree sandbox"
```
**Piped stdin**:
```bash theme={null}
echo 'uname -a' | contree run /bin/sh
```
Local stdin – piped input, or even a large file – is read in the
background and forwarded in bounded chunks rather than buffered in full
before sending, so piping in a large file doesn’t load it all into
memory at once. The first chunk rides along in the spawn request itself;
the pipe is left open and more is forwarded as it arrives, until local
stdin closes. With `-d`/`--detach`, `run` doesn’t return until all of
local stdin has actually been sent.
## Lifecycle
1. Resolve the session image (or switch to `--use IMAGE` first)
2. Upload any `--file` attachments (with SHA256 dedup)
3. Merge pending files from `contree file edit`/`cp`
4. POST `/v1/instances`
5. Poll until terminal status (unless `-d`)
6. Print stdout/stderr; propagate the exit code
On Ctrl-C, the first interrupt sends SIGINT to the spawned process and
keeps streaming its remaining output. A second Ctrl-C, or a failure to
deliver the first signal, cancels the whole operation.
See [Working with Files](../tutorial/files) for `--file` syntax details.
# session - Manage sessions, branches, history
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/session
Manage session branches and history. Sessions track the image state as you
run commands, with support for branching and rollback.
## Examples
```bash theme={null}
# Show current session
contree session
# List all sessions
contree session list
# Show full history
contree session show
# Create and switch to a branch
contree session branch experiment
contree session checkout experiment
# Switch back
contree session checkout main
# Create a branch from another branch
contree session branch hotfix --from main
# List branches (* marks active)
contree session branch
# Undo last operation
contree session rollback
# Undo last 3 operations (`--` stops argparse from eating `-3` as a flag)
contree session rollback -- -3
# Forward one entry
contree session rollback +1
# Absolute jump to a specific history id (use `session show` first)
contree session rollback 42
# Import image from another session
contree session use other-session
# Delete a session
contree session delete my-old-session
contree session rm my-old-session -y
```
## Help output
\$ contree session --help``usage: contree session [-h] {list,ls,use,branch,br,checkout,co,rollback,rb,show,wait,delete,rm,del} ...Manage session branches and history.Without a subcommand, shows the current session info (key, branch,image, last operation).Subcommands: list (ls) List all sessions use KEY Import another session's current image branch (br) List or create branches (--from to fork) checkout (co) Switch active branch rollback (rb) Navigate history: N=absolute, -N=back, +N=forward show Display the session history DAGpositional arguments: {list,ls,use,branch,br,checkout,co,rollback,rb,show,wait,delete,rm,del} list (ls) List all sessions use Import another session's image branch (br) List, create, delete, or prune branches checkout (co) Switch active branch rollback (rb) Navigate history: N=absolute, -N=back, +N=forward show Show session history wait Drain detached ops in the current session delete (rm, del) Delete sessions by keyoptions: -h, --help show this help message and exitfor coding agents: session (no subcommand) is read-only branch/checkout/rollback/session use mutates local session pointers `session show` defaults to last 20 history entries; pass -a/--all for full DAG use `session show` to inspect history DAG before destructive navigation `session wait [OPS...]` waits for active or specified operationsagent note: Before using this command in an automated workflow, read: contree agent``
## Concepts
Each non-disposable `contree run` creates a new history entry and advances
the branch pointer. Branches share the underlying history – creating a
branch just adds a new pointer at the current position.
Rollback moves the branch pointer backwards. History entries are preserved
and can be recovered by creating a new branch.
## Subcommands
### `session list`
`contree session list` (alias `ls`) prints every session known to the
current profile, with the active session marked. The optional
`--filter` flag narrows the list by substring match against the session
key, which is handy when you keep many disposable sessions named after
features or tickets.
\$ contree session list --help`usage: contree session list [-h] [--filter FILTER_TEXT]List locally known sessions and their current branch/image.options: -h, --help show this help message and exit --filter FILTER_TEXT Filter session keys containing this textfor coding agents: read-only command`
### `session use`
`contree session use KEY` imports the **current image** of another
session into the active session as a new history entry. The source
session is not modified; this is a “fork the snapshot, keep working
here” operation, distinct from the top-level `contree use` which starts
or resumes a session against an image reference.
\$ contree session use --help`usage: contree session use [-h] session_nameSet current session image to another session's tip image. Accepts exact key or key suffix.positional arguments: session_name Session key or suffix to matchoptions: -h, --help show this help message and exitfor coding agents: mutates current session history`
### `session branch`
`contree session branch` (alias `br`) lists branches with `*` marking
the active one. Pass a name to create a new branch pointing at the
current history position, or combine with `--from BRANCH` to fork off a
different branch. The `-U`/`--prune` flag removes branches that no
longer reference live history.
\$ contree session branch --help`usage: contree session branch [-h] [--from FROM_BRANCH] [-U] [--prune] [branch_name]List branches (no args). Create with NAME (optionally --from). Delete with --delete NAME. Prunedisposable-/detached- branches with --prune.positional arguments: branch_name Branch name (create/delete target)options: -h, --help show this help message and exit --from FROM_BRANCH Source branch (default: active branch) -U, --delete, --rm Delete the specified branch (NAME required, must not be active) --prune Prune disposable-/detached- branches (non-active only)for coding agents: read-only when NAME/--delete/--prune omitted mutating whencreating/deleting/pruning`
### `session checkout`
`contree session checkout BRANCH` (alias `co`) switches the active
branch pointer. Working directory, pending files, and the current
image are all reset to whatever the target branch currently points at,
so it is the safe way to bounce between parallel experiments.
\$ contree session checkout --help`usage: contree session checkout [-h] checkout_branchMove current session to another existing branch tip.positional arguments: checkout_branch Branch to switch tooptions: -h, --help show this help message and exitfor coding agents: mutates active branch pointer`
### `session rollback`
`contree session rollback [TARGET]` (alias `rb`) navigates the history
of the current branch. With no argument it steps back one entry; a
positive number jumps to that absolute history index, `-N` steps back
`N` entries, and `+N` steps forward. History entries are preserved –
rollback only moves the branch pointer.
\$ contree session rollback --help``usage: contree session rollback [-h] [target]Move branch pointer in session history. Supports absolute ID, relative backward (-N), and forward(+N).positional arguments: target History target: ID (absolute), -N (back), +N (forward) — use `-- -N` for negative valuesoptions: -h, --help show this help message and exitfor coding agents: mutates active branch history pointer``
### `session show`
`contree session show` prints the session history DAG with one row per
entry, including operation IDs, image UUIDs, branch pointers, and
relative timestamps. Use `-a` to include hidden entries, `-k KIND` to
filter by entry kind (e.g. `run`, `cd`), and `-l LAST` to show only the
last N rows.
\$ contree session show --help`usage: contree session show [-h] [-a] [-k KIND] [-l LAST] [--since SINCE] [--until UNTIL] [session_name]Print session history DAG entries and branch labels. By default shows last 20 entries; use-a/--all for full history.positional arguments: session_name Session key or suffix (default: current session)options: -h, --help show this help message and exit -a, --all Show full history (default: last 20 entries) -k, --kind KIND Filter history entries by kind (e.g., run, use, cd) -l, --last LAST Show last N entries after filtering --since SINCE Show entries since. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime. --until UNTIL Show entries before. Parse +/- intervals (bare seconds or smhdMy) or ISO/date to UTC datetime.for coding agents: read-only command`
### `session wait`
`contree session wait [OP_ID ...]` blocks until the specified operations
reach a terminal state (`SUCCESS`, `FAILED`, or `CANCELLED`). When no
IDs are given it waits for every active operation in the session, which
is the canonical way to drain background `contree run -d` jobs before
moving on.
\$ contree session wait --help`` usage: contree session wait [-h] [UUID_OR_REF ...]Drain detached operations in the current session. With no arguments, reads the session's pending-ops cache, polls each to a terminal status, and advances the active branch to each non-disposableresult image (recording `disposable-` branches for disposable runs). With explicit UUIDs,this command degrades to a plain polling loop: it prints completion rows but does NOT touch theactive branch, because the pending metadata is not loaded for explicit UUIDs.positional arguments: UUID_OR_REF Operations to wait for (default: all active in this session). Accepts UUIDs and session-history references (HEAD, HEAD~N, @, @N, @-N, @+N, :N, bare N).options: -h, --help show this help message and exitfor coding agents: no-arg form mutates session history (advances active branch) UUID form is apure polling observer if you need result images from explicit UUIDs, use `op show UUID | jq -r.image` and `contree use` ``
### `session delete`
`contree session delete KEY [KEY ...]` (aliases `rm`, `del`) removes
sessions and all their data – history, branches, pending files, shell
history. The command prompts before deleting unless `-y` is passed.
Use this to garbage-collect throwaway sessions; the disk savings on
the SQLite database can be substantial when many short-lived sessions
accumulate.
\$ contree session delete --help`usage: contree session delete [-h] [-f] KEY [KEY ...]positional arguments: KEY Session keys to deleteoptions: -h, --help show this help message and exit -f, -y, --force Do not ask for confirmation`
```bash theme={null}
contree session delete KEY [KEY ...]
contree session rm KEY -y # skip confirmation
contree session del KEY
```
## See also
* [Sessions, Branches & Rollback](../tutorial/sessions) – full tutorial on sessions, branches, and rollback
* [use - Choose an image for the session](./use) – start or resume a session
# shell - Interactive REPL
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/shell
Start an interactive REPL for managing sessions and running sandbox commands.
## Help output
\$ contree shell --help``usage: contree shell [-h]Start an interactive shell session.Launches a REPL where bare commands (e.g. `apt install curl`) areexecuted in the session sandbox via `run --shell`, and prefixedcommands (e.g. `contree ls /etc`) are dispatched as managementcommands.Built-in commands: cd, pwd, history, help, exit/quit.Tab completion for commands, flags, image paths, tags, and branches.options: -h, --help show this help message and exitfor coding agents: bare commands are implicit `contree run --shell` management commands must be prefixed with `contree` exit with `exit`/`quit` or Ctrl-Dagent note: Before using this command in an automated workflow, read: contree agent``
## Examples
```bash theme={null}
# Start the shell
contree shell
# Start with a specific output format
contree -o json shell
# Start with a named profile
contree --profile=personal shell
```
## Prompt
The prompt shows the current working directory:
```text theme={null}
contree:/> apt-get update -qq
contree:/app> python main.py
```
## Command dispatch
The shell recognises four types of input:
**Bare commands** — executed inside the sandbox as an implicit `contree run`
with `shell=True`:
```text theme={null}
apt-get install -y curl
echo hello && ls /
```
**Prefixed commands** — `contree ...` dispatches management commands through
the same argparse parser as the CLI:
```text theme={null}
contree ls /etc
contree session branch experiment
contree run -e DEBUG=1 -- ./app
```
**Builtins** – handled locally by the shell:
| Builtin | Description |
| - | - |
| `cd [PATH]` | Change working directory (`cd -` for previous) |
| `pwd` | Print working directory |
| `history [SEARCH]` | Show command history, optionally filtered by substring |
| `help [TOPIC]` | Show help (optionally for a specific command) |
| `clear` | Clear the terminal screen |
| `timeout DURATION CMD...` | Run `CMD...` with the API operation timeout set to `DURATION` |
| `--format NAME` / `-f NAME` | Change output format (or show current if no argument) |
| `exit` / `quit` | Exit the shell (also Ctrl-D) |
**Aliases** — bare names intercepted for convenience:
| Alias | Equivalent |
| - | - |
| `ls [PATH]` | `contree ls [PATH]` (API inspect, no sandbox) |
| `cat PATH` | `contree cat PATH` (API inspect, no sandbox) |
| `vim PATH` | `contree file edit PATH` (with `EDITOR=vim`) |
| `vi PATH` | `contree file edit PATH` (with `EDITOR=vi`) |
| `nvim PATH` | `contree file edit PATH` (with `EDITOR=nvim`) |
| `nano PATH` | `contree file edit PATH` (with `EDITOR=nano`) |
> [!NOTE]
>
> `ls` and `cat` aliases fall back to running inside the sandbox when pending
> files exist or when args contain flags or glob characters.
## Implicit run: shell-expression passthrough
Bare commands are forwarded to the sandbox as a single shell expression with
`shell=True`. The entire input line is sent verbatim to the remote `sh -c`,
so operators like `|`, `;`, `&&`, `||`, `>`, `<` are interpreted by the
remote shell exactly as typed:
```text theme={null}
contree:/> mount | grep cgroup
contree:/> echo 1 ; echo 2
contree:/> apt-get update && apt-get install -y curl
contree:/> uname -a > /tmp/info.txt
```
There is no local tokenize/rejoin step, so quoting is preserved:
```text theme={null}
contree:/> python3 -c "print('hello world')"
```
## `timeout` builtin
The shell recognises `timeout DURATION CMD...` and sets the server-side
operation timeout to `DURATION` instead of running the GNU `timeout` binary
inside the sandbox. The kill is enforced by the API, not by a wrapper
process, so the operation surfaces a warning when the limit is hit:
```text theme={null}
contree:/> timeout 30 apk add gcc
contree:/> timeout 5m make build
contree:/> timeout 1h python long_train.py
```
`DURATION` is an integer or decimal optionally followed by a unit suffix:
| Suffix | Meaning |
| - | - |
| (none) | Seconds |
| `s` | Seconds |
| `m` | Minutes |
| `h` | Hours |
| `d` | Days |
If `DURATION` is not a valid spec (for example `timeout --kill-after=5 30 cmd`
or `timeout --help`), the shell falls through and sends the line to the
sandbox unchanged, so the in-image `timeout` binary still handles advanced
flags.
When the limit is hit, the response carries `state.timed_out=true` and the
shell logs:
```text theme={null}
WARNING: Operation timed out after 30s
```
## Tab completion
The shell provides context-aware tab completion for almost everything
except bare (implicit run) commands. Press Tab to complete:
| Context | What completes |
| - | - |
| Empty prompt | All commands, aliases, and builtins |
| `contree ` | Subcommand names |
| `contree CMD -` | Flags for that command |
| `contree CMD --` | Long flags for that command |
| `ls /etc/`, `cat /etc/` | Sandbox file paths |
| `cd /us` | Sandbox directory paths (dirs only) |
| `vim /etc/`, `nano /etc/` | Sandbox file paths |
| `contree use ` | Image UUIDs and `tag:NAME` |
| `contree tag ` | Image UUIDs and `tag:NAME` |
| `contree show ` | Operation UUIDs |
| `contree kill ` | Operation UUIDs |
| `contree session checkout ` | Branch names |
| `contree session branch ` | Branch names |
| `contree session use ` | Session keys |
| `contree file edit ` | Sandbox file paths |
| `help ` | All command and alias names |
Path completions query the sandbox filesystem via the inspect API
and are cached persistently – subsequent completions for the same
directory are instant.
## History search
The `history` builtin takes an optional pattern and filters the
persisted history by case-insensitive substring:
```text theme={null}
contree:/> history # show every entry for this session
contree:/> history apt # any line containing "apt"
contree:/> history 'contree ' # exact "contree " (with trailing space)
contree:/> history make # any line containing "make"
```
History is per-session: searches see only the current `session_key`’s
entries. Up to 10,000 lines are kept; older lines are trimmed on save.
## Line continuation
A trailing `\` at the end of input triggers a `> ` continuation prompt,
just like traditional shells:
```text theme={null}
contree:/> ls \
> -alh \
> /sys
```
Backslash-newline pairs are removed to join the lines into a single
command (`ls -alh /sys`). Unclosed quotes also trigger continuation,
preserving the newline inside the quoted string.
## Limitations
* **No global flags on commands**: `--token`, `--url`, `--log-level` are
not available inside the shell.
* **No local pipes or redirects**: `|`, `>`, `<` are passed as-is to the
sandbox (works for remote commands, not for contree output).
* **No job control**: No `&`, `bg`, `fg`, or Ctrl-Z. Use `contree run -d`
for background tasks.
* **Bare commands use defaults**: `--env`, `--file`, `--disposable`, and
`--detach` require the explicit `contree run` prefix. The operation
timeout has a shorthand: `timeout DURATION CMD...` (see above).
* **No `~` or glob expansion**: Passed as-is to the sandbox.
* **Cannot nest shells**: Running `contree shell` inside a shell is not
supported.
## See also
* [Interactive Shell](../tutorial/shell) – full tutorial on using the interactive shell
* [run - Execute a command in the sandbox](./run) – the `run` command used by implicit bare commands
* [file - Stage file edits for the next run](./file) – the `file edit` command behind editor aliases
# show - Inspect an operation
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/show
> [!NOTE]
>
> **`contree show` is a top-level shortcut for [operation show](./operation) (`contree op show`).**
>
> Both share one argparse setup and one handler. The top-level `show`
> accepts one or more UUIDs and history references — each entry renders
> as its own row. Accepted reference forms:
>
> * `@`, `:`, or `HEAD` — the operation at the active branch tip.
> * `@N`, `:N`, bare `N` — absolute history id.
> * `@-N`, `:-N`, `HEAD~N` — N steps back from the tip.
> * `HEAD~` — shorthand for `HEAD~1`.
> * `@+N`, `:+N` — N steps forward from the tip (latest child).
>
> See the [operation - Manage operations](./operation) page for the full description.
Display the full result of one or more operations, including stdout
and stderr from sandbox execution.
## Examples
```bash theme={null}
# Show a single operation
contree show 3f2a7b...
# Show multiple operations in one call
contree show 3f2a7b... a1b2c3... 9d8e7f...
# History references (resolved against the active session)
contree show @5 @4 @3
# Relative to the active branch tip (like `session rollback`)
contree show @-1 # the operation one step back from the tip
contree show @+1 # the next operation forward (latest child)
# Git-style HEAD notation, equivalent to @ and @-N
contree show HEAD # current tip operation
contree show HEAD~ # one step back (shorthand for HEAD~1)
contree show HEAD~3 # three steps back from the tip
# JSON output for scripting
contree -o json show 3f2a7b...
# Show result of a detached run
contree run -d -- make test
contree show UUID
```
## Help output
\$ contree show --help```usage: contree show [-h] [--raw] UUID_OR_REF [UUID_OR_REF ...]Manage operations (list, inspect, cancel).Aggregates ps/show/kill under a single namespace, and adds multi-UUIDsupport to ``show`` and ``cancel`` so several operations can be actedon in one invocation.Subcommands: list (ls) List operations. ``contree ps`` is an alias. show UUID [UUID...] Show one or more operation results. cancel UUID [UUID...] Cancel one or more operations (or --all).positional arguments: UUID_OR_REF Operations to inspect. Accepts UUIDs and session-history references: @ or HEAD for the active branch tip, @N for an absolute history id, @-N or HEAD~N for N steps back, @+N for N steps forward.options: -h, --help show this help message and exit --raw Print each operation's JSON payload as JSONL (one object per line) to stdout. Round-trips through the typed operation model, so fields the model doesn't know about are dropped. Skips formatter routing and derived columns; streams cleanly into `jq -c`. Useful for debugging or for fields the table view omits.for coding agents: list/show are read-only; cancel mutates remote state show and cancel accept multiple UUIDs in one invocation show supports @N session-history references inherited from `contree show`agent note: Before using this command in an automated workflow, read: contree agent```
## Output
The command renders every scalar top-level field the API returns
(typically: **uuid**, **kind**, **status**, **created\_at**,
**started\_at**, **finished\_at**, **duration**, **session\_key**, …) and
adds these derived fields:
* **exit\_code** – the sandbox process exit code (extracted from
`metadata.result.state.exit_code`)
* **image** – resulting image UUID from `result.image`
* **tag** – image tag from `result.tag`
* **stdout / stderr** – sandbox output, decoded (for `default`,
`json`, and `json-pretty` formats)
`status` is the server’s word: it reflects whether the API ran the
operation to completion, not whether the sandbox process exited with
zero. A `SUCCESS` row with `exit_code=1` means “the API completed the
job; your command returned 1”. `error` is pinned to the last column.
Nested objects (`metadata`, `result`) are dropped from the flat row
– use `--raw` to keep them, or `-o json` to keep the flat structured
row.
Pass `--raw` to skip all of the above and print each operation’s
JSON payload as JSONL (one object per line) to stdout. The payload
round-trips through the typed operation model, so fields the model
doesn’t know about are dropped – it’s not the server’s byte-for-byte
response. Streams cleanly into `jq -c`. Useful for debugging or
pulling fields the table view omits (resources, full metadata, etc.).
Timestamps come back from the API in UTC and are converted to the
**local timezone** for human-readable formatters (`default`, `table`,
`csv`, `tsv`, `plain`). The JSON formatters preserve the source
timezone offset.
For `csv`, `tsv`, and `table` formats, stdout/stderr are omitted – use
`default` or `json` to see sandbox output.
## See also
* [ps - List activity](./ps) – list operations to find UUIDs
* [operation - Manage operations](./operation) – multi-UUID variant: `contree op show UUID1 UUID2 ...`
* [run - Execute a command in the sandbox](./run) – the command that creates operations
# skill - Install agent skills
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/skill
Install, remove, or upgrade ConTree agent skills for Codex and Claude Code.
## Spec format
Commands accept **specs** – a `kind:hint` URI that identifies the skill type
and target path:
| Spec | Resolves to | Skill type |
| - | - | - |
| `claude:` | `.claude/skills/contree` (project) | ClaudeSkill |
| `claude:~` | `~/.claude/skills/contree` (global) | ClaudeSkill |
| `codex:` | `.codex/skills/contree` (project) | CodexSkill |
| `codex:~` | `~/.codex/skills/contree` (global) | CodexSkill |
| `opencode:` | `.opencode/skills/contree` (project) | OpenCodeSkill |
| `opencode:~` | `$OPENCODE_HOME/skills/contree` (or `~/.config/opencode/skills/contree`) | OpenCodeSkill |
| `amp:` | `.amp/skills/contree` (project) | AmpSkill |
| `amp:~` | `~/.config/agents/skills/contree` (global) | AmpSkill |
| `cline:` | `.cline/skills/contree` (project) | ClineSkill |
| `cline:~` | `$CLINE_DIR/skills/contree` (or `~/.cline/skills/contree`) | ClineSkill |
| `claude-subagent:` | `.claude/agents/contree-subagent.md` (project) | ClaudeSubagentSkill |
| `claude-subagent:~` | `~/.claude/agents/contree-subagent.md` (global) | ClaudeSubagentSkill |
| `claude-agent:` | `.claude/agents/contree.md` (project) | ClaudeAgentSkill |
| `claude-agent:~` | `~/.claude/agents/contree.md` (global) | ClaudeAgentSkill |
| `./path` | `./path` (skill type guessed from path) | auto |
When no specs are given, `install` targets the global (`:~`) variant of
**every** known kind. The Claude-based kinds (`claude`, `claude-agent`,
`claude-subagent`) are skipped unless `~/.claude` already exists, so a
machine without Claude Code installed will not have empty directories
created for it.
## Examples
```bash theme={null}
# Install globally to every known kind (Claude kinds gated on ~/.claude)
contree skill install
# Install into project-level .claude/skills/contree
contree skill install claude:
# Install globally into ~/.claude/skills/contree
contree skill install claude:~
# Install both globally
contree skill install codex:~ claude:~
# Install to explicit path (class guessed from path)
contree skill install ./my/custom/path
# Upgrade all remembered installs
contree skill upgrade
# Upgrade specific target
contree skill upgrade claude:~
# Remove by spec
contree skill remove -y claude:~
# Remove by full path
contree skill remove -y /path/to/skills/contree
# List installs with version and outdated status
contree skill list
contree skill ls
```
## Help output
\$ contree skill --help`usage: contree skill [-h] {list,ls,install,i,remove,r,rm,del,upgrade,u,update} ...Install, remove, or upgrade ConTree agent skills.contree skill install # autodetect agent homescontree skill install claude:~ # global ~/.claudecontree skill install codex: # project-level .agents/skillscontree skill install . # project root: every kind under itpositional arguments: {list,ls,install,i,remove,r,rm,del,upgrade,u,update} list (ls) List remembered skill installs install (i) Install ConTree skill files remove (r, rm, del) Remove installed skill files upgrade (u, update) Upgrade installed skill filesoptions: -h, --help show this help message and exitagent note: Before using this command in an automated workflow, read: contree agent`
## Subcommands
### `skill install`
`contree skill install [SPEC ...]` (alias `i`) installs skill directories.
Each spec resolves to a skill class and a filesystem path, both of which
are persisted in `skills.db` so future `list` and `upgrade` calls can
find the install without re-specifying it. With no specs the command
targets the global (`:~`) variant of every known kind – Claude-based
kinds are skipped automatically when `~/.claude` does not exist. Pass
`-y` to overwrite an existing install non-interactively.
\$ contree skill install --help`usage: contree skill install [-h] [-f] [SPEC ...]positional arguments: SPEC claude:~ codex:~ skill path or project rootoptions: -h, --help show this help message and exit -f, -y, --force Overwrite existing`
### `skill list`
`contree skill list` (alias `ls`) shows every remembered install with
its kind, installed version (read from `.version`), the version
bundled with this CLI, an `outdated` flag, and whether the install
path still exists on disk. Stale entries whose path was deleted
externally are pruned from the registry automatically when this
command runs.
\$ contree skill list --help`usage: contree skill list [-h]options: -h, --help show this help message and exit`
### `skill upgrade`
`contree skill upgrade [SPEC ...]` overwrites existing installs with
the version bundled in the current CLI. With no specs it upgrades
every remembered location, which is the normal post-`pip install -U`
maintenance step. Targets that are already at the bundled version are
rewritten anyway so any local edits to skill files are reverted.
\$ contree skill upgrade --help`usage: contree skill upgrade [-h] [SPEC ...]positional arguments: SPEC claude:~ codex:~ skill path or project rootoptions: -h, --help show this help message and exit`
### `skill remove`
`contree skill remove SPEC [...]` (aliases `r`, `rm`, `del`) deletes
installed skill files and forgets the path from the registry. Specs
may be the same URI form accepted by `install`, or a literal filesystem
path. Pass `-y` to skip the confirmation prompt.
\$ contree skill remove --help`usage: contree skill remove [-h] [-f] [SPEC ...]positional arguments: SPEC claude:~ codex:~ skill path or project rootoptions: -h, --help show this help message and exit -f, -y, --force Do not ask for confirmation`
### Install contents
Skill directories contain:
* `.version` — installed package version
* `SKILL.md` — skill prompt with `allowed-tools` frontmatter
* `agents/openai.yaml` — OpenAI-compatible skill config
Skills require `contree` in PATH. If missing, ask the user to install it.
### Skill classes
| Class | Kind | Description |
| - | - | - |
| `ClaudeSkill` | `claude` | Bundled skill directory for Claude Code |
| `CodexSkill` | `codex` | Bundled skill directory for Codex |
| `OpenCodeSkill` | `opencode` | Bundled skill directory for OpenCode |
| `AmpSkill` | `amp` | Bundled skill directory for Amp |
| `ClineSkill` | `cline` | Bundled skill directory for Cline |
| `ClaudeSubagentSkill` | `claude-subagent` | Standalone `.md` subagent file |
| `ClaudeAgentSkill` | `claude-agent` | Custom agent `.md` with `skills: [contree]` |
# tag - Tag or untag an image
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/tag
Assign or remove a tag from an image. Tags are human-readable names that
make images easier to reference.
## Examples
```bash theme={null}
# Tag an image
contree tag 3f2a7b... my-app:v1.0
# Remove a tag
contree tag 3f2a7b... my-app:v1.0 --delete
# Use the tagged image
eval $(contree use tag:my-app:v1.0)
```
## Help output
\$ contree tag --help``usage: contree tag [-h] [-U] ARG [ARG ...]Assign or remove a tag from an image.Tags provide human-readable names for image UUIDs, making them easierto reference in commands like `contree use tag:NAME`.With one argument, tags the current session image.With two arguments, the first is the image reference and the second is the tag.Use -U/--delete/--rm to remove a tag instead of assigning one.positional arguments: ARG TAG (current image) or IMAGE_REF TAGoptions: -h, --help show this help message and exit -U, --delete, --rm Remove tag from imageexamples: contree tag python-dev:latest # tag current session image contree tag UUID python-dev:latest # tag specific image by UUID contree tag tag:alpine:latest my-alpine # re-tag by reference contree tag -U UUID my-tag # remove a tag (or --delete/--rm)for coding agents: mutating command default action assigns tag; use --delete to remove mappingagent note: Before using this command in an automated workflow, read: contree agent``
## Usage
Tags are free-form strings. A common convention is `scope/purpose:version`:
```bash theme={null}
contree tag UUID ubuntu-with-curl:latest
contree tag UUID my-project/dev-env:v2
```
Once tagged, reference the image anywhere with the `tag:` prefix:
```bash theme={null}
contree use tag:ubuntu-with-curl:latest
```
Tagging an image that already has a different tag replaces the old tag.
## See also
* [images - List and import images](./images) – list images and their tags
* [Your First Sandbox](../tutorial/first-steps) – working with images
# use - Choose an image for the session
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/commands/use
Set the session image or show the current session state.
This is typically the first command you run – it tells contree-cli which
image to use for subsequent commands.
## Examples
```bash theme={null}
# Start a session with an image
eval $(contree use tag:ubuntu:latest)
# Start a session with a specific image UUID
eval $(contree use 3f2a7b...)
# Start or resume a named session
export CONTREE_SESSION=my-session
# Show current session info
contree use
# Start a fresh session (new session key)
eval $(contree use -N tag:python:3.11-slim)
```
The `eval` wrapper exports `CONTREE_SESSION` into your shell so all
subsequent commands share the same session. Without `eval`, contree prints
the export line but your shell doesn’t pick it up.
## Help output
\$ contree use --help`usage: contree use [-h] [-N] [image]Set or show the current session image.With an IMAGE argument, resolves it (UUID or tag:NAME) and sets it asthe active session image. Prints a shell export line so that thesession key can be captured with eval: eval $(contree use tag:ubuntu:latest)Without arguments, displays the current session info (image, branch,last operation).Use -N/--new to start a fresh session instead of resuming the currentone. The new session key is printed as an export line.positional arguments: image Image UUID or tagoptions: -h, --help show this help message and exit -N, --new Start a new session instead of resuming the current onefor coding agents: use IMAGE starts/switches a session and prints CONTREE_SESSION export use (without IMAGE) is read-only and prints current session state use --new IMAGE creates a fresh session key without CONTREE_SESSION env var, key is auto-generated as +<8hex> (derived from profile+ppid+tty); export your own for stabilityagent note: Before using this command in an automated workflow, read: contree agent`
## Behavior
**With an image argument**: resolves the image (UUID or `tag:NAME`), sets it
as the session’s current image, and prints a shell export statement.
**Without arguments**: displays the current session info – session key,
active branch, current image, and last operation.
**With `--new`**: generates a new random session key instead of resuming the
existing one. Useful when you want a clean slate in the same terminal.
## Shell detection
The output format adapts to your shell:
* **bash / zsh**: `export CONTREE_SESSION=`
* **fish**: `set -gx CONTREE_SESSION `
Detection uses the `$SHELL` environment variable.
## See also
* [Your First Sandbox](../tutorial/first-steps) – starting your first session
* [Sessions, Branches & Rollback](../tutorial/sessions) – branching and rollback
# Overview
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/index
Command-line client for the [ConTree](https://contree.dev) sandboxing platform.
## What is ConTree?
[ConTree](https://contree.dev) is a secure sandbox API for AI agents with
git-like branching. Every command runs inside a VM-isolated sandbox, and
every execution produces a new **image** – a full filesystem snapshot.
Branch from any checkpoint, explore paths in parallel, pick the winner,
and instantly roll back on failure.
Built for **AI agents that think ahead**:
* **Tree-search execution** – branch the sandbox state so an agent can
explore multiple solution paths in parallel and keep the best one.
* **Instant rollback** – backtrack to any previous checkpoint when a
path fails, without rebuilding from scratch.
* **Safe code execution** – run untrusted or LLM-generated code inside
VM-level isolation. Crashes and side effects stay in the sandbox.
* **Session continuity** – rewind and resume long-running agent
workflows with full filesystem context preserved.
`contree-cli` is the command-line client that talks to the ConTree API.
```bash theme={null}
contree use tag:ubuntu:latest # pick an image for current terminal
contree run apt update -qq # each run snapshots the result
contree run apt install -y curl # builds on the previous snapshot
contree ls /usr/bin/curl # inspect without spawning a VM
```
You can choose name for session by setting the environment variable
`CONTREE_SESSION`.
```bash theme={null}
export CONTREE_SESSION=demo_session # Pick a name for session manually
contree use tag:ubuntu:latest # pick an image for demo_session
contree run -- find /root # run commands
```
## Get started
> [card] [Tutorial](./tutorial/index)
>
> Step-by-step guide from installation to automated workflows.
> Six sections, each building on the previous one.
> [card] [Command Reference](./commands/index)
>
> Every command, flag, and subcommand documented with usage examples.
## Key features
> [card] [Sessions & Branching](./tutorial/sessions)
>
> Every run creates a checkpoint. Branch off to experiment, roll back
> mistakes, resume from any point.
> [card] [File Injection](./tutorial/files)
>
> Map local files into sandboxes with `--file`, edit remote configs
> in-place, stage changes for the next run.
> [card] [Scripting-Friendly](./tutorial/workflows)
>
> JSON, CSV, and TSV output. Detached runs, operation monitoring,
> shebang scripts — built for automation.
> [card] Lightweight
>
> A single runtime dependency: the `contree-client` library.
> [card] [Multi-Profile](./tutorial/configuration)
>
> Named profiles for different projects and environments. Switch with
> a single command.
> [card] [Filesystem Inspection](./commands/ls)
>
> Browse and download files from sandbox images without spawning a
> new instance.
# Building from a Dockerfile
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/build
`contree build` turns a familiar `Dockerfile` into a ConTree image. Each
directive becomes one image layer, every layer is a real session
checkpoint, and re-running the same `Dockerfile` reuses prior layers
through a content-addressed cache. This tutorial walks through the
`build-demo` example shipped with the repo so you can see the moving
parts end-to-end.
## The example project
The tree at `docs/examples/build-demo` contains a minimal Python app
plus a Dockerfile that exercises the directives most builds actually
use:
```
docs/examples/build-demo/
├── .dockerignore
├── Dockerfile
├── hello.py
└── src/
├── __init__.py
└── banner.py
```
`hello.py` reads a greeting from an environment variable and prints a
boxed banner; `src/banner.py` provides the box renderer. Nothing
exotic – it just gives the Dockerfile something to `COPY` and `RUN`.
The Dockerfile itself:
```dockerfile theme={null}
FROM python:3.12-alpine
ARG GREETING=hello
ENV APP_GREETING=${GREETING}
WORKDIR /app
COPY hello.py /app/hello.py
COPY src /app/src
ADD https://github.com/nebius/contree-cli/archive/refs/heads/master.zip /tmp/contree-cli.zip
RUN python -c "import sys; print('python', sys.version)"
RUN python -m zipfile -e /tmp/contree-cli.zip /opt/
RUN pip install --no-cache-dir /opt/contree-cli-master
RUN contree --help | head -20
RUN python /app/hello.py
```
Six directives, in order:
1. `FROM python:3.12-alpine` – resolves the base image. If
`tag:python:3.12-alpine` is not already in the project, `contree build`
auto-imports it from the registry.
2. `ARG GREETING=hello` and `ENV APP_GREETING=${GREETING}` – declare a
build-time variable and pin its value into a runtime environment
variable that the app will read.
3. `WORKDIR /app` – sets the working directory for everything below.
4. Two `COPY` directives stage local files (`hello.py` and the `src/`
directory) into the build’s pending uploads.
5. `ADD https://...master.zip /tmp/contree-cli.zip` – streams a remote
archive straight from GitHub into the contree file store, without
creating a local temp file.
6. Five `RUN` directives prove the toolchain works, unpack the zip,
install the CLI from source, and run the demo app.
## Build context and `.dockerignore`
The first positional argument to `contree build` is the **build
context** – the directory that anchors every `COPY` and `ADD` source
path. Anything outside that directory is invisible to the build. In
this example the context is `docs/examples/build-demo`, and the
Dockerfile sits at the top of it.
A `.dockerignore` next to the Dockerfile keeps junk out of the upload:
```text theme={null}
# Demo .dockerignore: keep build context lean
**/*.log
**/__pycache__
.env*
```
The matcher uses the same rule set as `run --file`: `*` is a
single-segment wildcard, `**` crosses directories, `?` matches one
character, and a leading `!` re-includes a previously ignored path.
The last matching rule wins. On top of your `.dockerignore`, the CLI
always filters `.git`, `__pycache__`, `*.pyc`, `.venv`,
`node_modules`, `dist`, and `build`, so you do not need to repeat the
usual suspects.
## Your first build
From the repository root, run:
```bash theme={null}
contree build docs/examples/build-demo --tag contree-cli-build-demo:latest
```
You should see one log line per directive plus a stdout dump after
each `RUN`:
```text theme={null}
[INFO] FROM python:3.12-alpine -> tag:python:3.12-alpine
[INFO] COPY hello.py -> /app/hello.py
[INFO] COPY src -> /app/src
[INFO] ADD https://.../master.zip -> /tmp/contree-cli.zip
[INFO] RUN spawned op=019e... RUN python -c "import sys; print('python', sys.version)"
[INFO] stdout:
python 3.12.13 ...
[INFO] RUN spawned op=019e... RUN python /app/hello.py
[INFO] stdout:
+---------------+
| hello |
| contree build |
+---------------+
[INFO] tagged as contree-cli-build-demo:latest
IMAGE TAG SESSION
contree-cli-build-demo:latest build:
```
The final tagged image is now usable everywhere a tag is accepted:
```bash theme={null}
eval $(contree use tag:contree-cli-build-demo:latest)
contree run python /app/hello.py
```
## Layer cache: the second build is free
Run the same command a second time. Every step prints **cache hit**
and the build finishes in seconds without spawning a single instance.
The cache key for each layer is a chain hash:
```
sha256(parent_layer_hash || state(workdir/env/user/args)
|| directive || pending_files)
```
That means a layer is reused if and only if:
* the previous layer was identical,
* the directive text is byte-for-byte the same,
* the resolved environment (`WORKDIR`, `ENV`, `USER`, `ARG`) matches, and
* for `COPY`/`ADD`, the **content** of the staged files matches (the
SHA-256 of every uploaded file, not their timestamps).
Edit `hello.py`, run the build again, and only the last `RUN` step
plus everything depending on it rebuilds. The earlier `RUN python -c 'import sys; print(sys.version)'` layer is reused because it has no
dependency on `hello.py`.
Each cached layer is materialised as a branch named
`layer:` inside a session keyed by the absolute path of
the context directory: `build:`. So the
cache is **per-context-path** – moving the directory or building from
a sibling worktree starts a fresh cache.
To inspect the layer history:
```bash theme={null}
contree session list --filter build:
contree session use build:
contree session show
```
`contree session show` prints the DAG with one row per layer and the
chain hash visible in the branch column. Switching to a `layer:` branch
puts you on that layer’s image, so you can `contree run` against any
intermediate snapshot to debug a step in isolation.
To force a rebuild ignoring all cached layers:
```bash theme={null}
contree build docs/examples/build-demo --no-cache \
--tag contree-cli-build-demo:latest
```
## Build args and variable substitution
Variables (`$VAR` and `${VAR}`) expand in `FROM`, `RUN`, `COPY`/`ADD`
arguments, `WORKDIR`, `ENV` values, and `USER`. The lookup order is:
1. `--build-arg KEY=VALUE` for any `ARG` already declared.
2. `ENV` directives processed so far.
3. `ARG` defaults from the Dockerfile.
4. Empty string for unknown names.
The demo declares `ARG GREETING=hello` and uses it through
`ENV APP_GREETING=${GREETING}`. Override it at the CLI:
```bash theme={null}
contree build docs/examples/build-demo --build-arg GREETING=ciao \
--tag contree-cli-build-demo:ciao
```
The final `RUN python /app/hello.py` step now prints `ciao` in the
boxed banner because the chain hash of the layer that ran
`ENV APP_GREETING=...` changed, invalidating every layer below it.
## `ADD URL` streams without a temp file
The `ADD` line in the demo points at a GitHub archive:
```dockerfile theme={null}
ADD https://github.com/nebius/contree-cli/archive/refs/heads/master.zip /tmp/contree-cli.zip
```
`contree build` opens the HTTP connection and pipes the response body
**directly** into `POST /v1/files` – the bytes never touch your local
disk. The CLI also remembers the URL’s `ETag`, `Last-Modified`, and
`Content-MD5` validators in the per-context cache. On the next build
it issues a conditional `HEAD` first; if the validators match, the
upload is skipped entirely and the log line reads
`URL cache hit (HEAD validators match)`.
Two things this does **not** do:
* It does not extract tarballs/zips. Use a `RUN python -m zipfile -e`
(or `tar xf`) directive when you need extraction, exactly like the
demo does.
* It does not follow private auth – the request is anonymous. Mirror
the asset to a public URL, or `COPY` it from your build context.
## Supported and skipped directives
The MVP interpreter implements the directives most Dockerfiles
actually rely on:
| Implemented | Notes |
| - | - |
| `FROM ref[:tag] [AS name]` | Auto-imports missing tags; `AS name` is parsed but multi-stage is not yet executed. |
| `RUN ...` | Shell-form and JSON exec-form. Spawns one instance per `RUN`. |
| `COPY [--chown=] [--chmod=] SRC... DEST` | Honours `.dockerignore`, dedups by SHA-256. |
| `ADD ...` | Local paths behave like `COPY`; URLs stream through `POST /v1/files`. |
| `WORKDIR`, `ENV`, `ARG`, `USER` | Accumulated and applied to subsequent steps. |
Directives that are parsed and **skipped with a warning** (the build
continues, the image is still produced):
`CMD`, `ENTRYPOINT`, `LABEL`, `EXPOSE`, `VOLUME`, `STOPSIGNAL`,
`MAINTAINER`, `HEALTHCHECK`, `ONBUILD`, `SHELL`,
`COPY --from=stage`.
ConTree images are filesystem snapshots, not OCI runtime configs, so
`CMD`/`ENTRYPOINT` have nowhere to live – you express the entrypoint
explicitly at `contree run` time instead.
## When to reach for `build` vs `run`
The same image you can produce with `contree build` can be produced
by hand with a sequence of `contree run` calls. Pick the right tool:
| Situation | Prefer |
| - | - |
| You already have a working `Dockerfile` | `contree build` – just reuse it. |
| You want reproducible, cacheable setup driven from version control | `contree build`. |
| You are still experimenting and do not know the final steps | `contree run` interactively; tag a checkpoint when you are happy. |
| You need `CMD`/`ENTRYPOINT`/`HEALTHCHECK` semantics | Neither – those are runtime concerns for OCI runtimes, not for ConTree. |
| You want multi-stage builds today | Not yet – stage `AS` parses but is skipped. Track Phase 2. |
## Cheat sheet
```bash theme={null}
# Simplest build; finds ./Dockerfile in the context, tags the result.
contree build . --tag myapp:dev
# Out-of-tree Dockerfile.
contree build ./service \
--dockerfile ./service/Dockerfile.prod \
--tag svc:prod
# Override build-time variables.
contree build . \
--build-arg VERSION=2.5 \
--build-arg DEBUG=1
# Force a full rebuild.
contree build . --no-cache --tag myapp:dev
# Raise the per-RUN timeout to 30 minutes.
contree build . --timeout 1800 --tag myapp:dev
# Inspect the build's layer history.
contree session list --filter build:
contree session use build:
contree session show
```
***
You now have a tagged image that came from a `Dockerfile`, a cached
layer history you can branch off, and a feel for which directives
behave and which are parsed-but-skipped. Next, see
[Scripting & Automation](./workflows) for scripting builds into pipelines, or
[build - Build an image from a Dockerfile](../commands/build) for the full reference.
# Configuration & Profiles
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/configuration
Profiles let you store credentials for multiple projects or environments
and switch between them. This section walks through setting up profiles,
switching contexts, and understanding how configuration is resolved.
## Creating profiles
Each profile stores a token and API URL for a specific project or
environment. When you first ran `contree auth`, it created a profile
called `default`. Add more with `--profile`:
```bash theme={null}
contree auth --profile=personal
contree auth --profile=sandbox
```
Each command prompts for a token securely (no echo), verifies it against
the API, and writes it to `~/.config/contree/auth.ini`.
The resulting config file looks like this:
```ini theme={null}
[DEFAULT]
profile = default
[profile:default]
token = eyJ...
url = https://api.tokenfactory.nebius.com/sandboxes
type = iam
project = project-id-default
[profile:personal]
token = eyJ...
url = https://api.tokenfactory.nebius.com/sandboxes
type = iam
project = project-id-personal
[profile:sandbox]
token = eyJ...
url = https://api.tokenfactory.nebius.com/sandboxes
type = iam
project = project-id-sandbox
```
Each profile is a `[profile:NAME]` section with `token`, `url`, `type`,
and `project` keys. The `[DEFAULT]` section stores the name of the active
profile.
## Listing profiles
See all saved profiles and which one is active:
```bash theme={null}
contree auth ls
```
The output shows the profile name, URL, a token hash (first 16 chars of
SHA256), active status, and a health check result.
`auth ls` verifies each profile against the API with a 2-second timeout.
Possible status values:
* `ok` — token is valid and has the required sandbox permission
* `timeout` — server did not respond in time
* `error` — bad token or network error
* `offline mode` — you passed `-O` / `--offline`
* `no url` — the profile has no API URL configured (re-run `contree auth`)
* `inactive` — token authenticates, but the configured project does not
grant the sandbox permission this CLI needs
Skip the network check:
```bash theme={null}
contree auth ls -O
```
For automation, use structured output:
```bash theme={null}
contree -o json auth ls
```
## Switching profiles
### Persistent switch
Change the active profile for all future commands:
```bash theme={null}
contree auth switch personal
```
### Per-command override
Use `-p` / `--profile` on any command:
```bash theme={null}
contree -p personal images
contree -p sandbox run -- uname -a
```
### Environment variable
Override for the entire shell session:
```bash theme={null}
export CONTREE_PROFILE=sandbox
contree images # uses sandbox
```
### Inline token
Pass `--token` and `--url` directly:
```bash theme={null}
contree --token=eyJ... --url=https://api.tokenfactory.nebius.com/sandboxes images
```
> [!WARNING]
>
> Avoid `--token` on the command line in production — the token is
> visible in process listings and shell history.
## Removing profiles
Delete a profile and its session database:
```bash theme={null}
contree auth remove personal
contree auth rm personal -y # skip confirmation
```
If the removed profile was active, the CLI switches to the first
remaining profile.
## Profiles and sessions
Each profile has its own session database
(`~/.config/contree/sessions-{profile}.db`), so:
* **Same profile, same terminal** — resumes the existing session
* **Different profile, same terminal** — different session, different data
Switching from `default` to `personal` does not affect your `default`
sessions — you can switch back and continue where you left off.
> [!TIP]
>
> To share a session across profiles (rare), set `CONTREE_SESSION`:
>
> ```bash theme={null}
> export CONTREE_SESSION=shared-session
> ```
## Data storage
All data lives in `CONTREE_HOME` (default `$XDG_CONFIG_HOME/contree`,
falling back to `~/.config/contree` when `XDG_CONFIG_HOME` is unset):
| Path | Purpose |
| - | - |
| `auth.ini` | Profile credentials and settings (created with mode `0600`) |
| `cli.ini` | Optional user-editable defaults for the CLI |
| `cli/sessions/{profile}.db` | Per-profile sessions, history, branches, cache |
| `cli/skills.db` | Installed agent skill registry |
Override with `$CONTREE_HOME`:
```bash theme={null}
export CONTREE_HOME=/custom/path
```
### `cli.ini`
`cli.ini` is meant for hand-editing. Create it yourself; the CLI never
writes to it. Two kinds of sections are supported:
#### `[cli]` section: per-flag defaults
Keys here become argparse defaults. Use the argparse `dest` name (not
the flag name):
| Key | Maps to flag | Notes |
| - | - | - |
| `log_level` | `--log-level` | One of `debug`, `info`, `warning`, `error`, `critical` |
| `output_format` | `-f` / `--format` | One of the formatter names (`default`, `json`, `json-pretty`, `csv`, `tsv`, `table`) |
| `editor` | `--editor` (file edit) | Fallback when neither `--editor` nor `$EDITOR` is set; if absent the CLI searches `vim` then `nano` on `PATH` and falls back to `vi` |
Example:
```ini theme={null}
[cli]
log_level = debug
output_format = json
editor = nvim
```
Precedence: CLI flag > environment variable > `cli.ini` > built-in
default. A `cli.ini` setting always loses to an explicit flag.
#### `[profile:NAME]` sections: CLI-scoped profiles
`cli.ini` accepts the same `[profile:NAME]` sections as `auth.ini` and
supports the same fields:
| Key | Required | Notes |
| - | - | - |
| `url` | yes for JWT, optional for IAM | API base URL |
| `type` | optional | `jwt` (default) or `iam` |
| `project` | IAM only | Project ID |
| `token` | optional | API bearer token |
The two files are merged at load time and `auth.ini` wins on conflict.
What `cli.ini` is for: profiles (or any field, including `token`) you
want only the `contree` CLI to see. The CLI merges `cli.ini` with
`auth.ini`. Other contree-related tooling that talks to the API
directly (the SDK, the MCP server) reads only `auth.ini`. Use
`cli.ini` when you need a profile that should be invisible to those
direct-API consumers, or to keep `auth.ini` minimal and shared.
Example, CLI-only profile alongside the shared one:
```ini theme={null}
# ~/.config/contree/auth.ini (read by CLI + SDK + MCP, mode 0600)
[DEFAULT]
profile = default
[profile:default]
url = https://contree.dev
token = eyJhbGciOi...
```
```ini theme={null}
# ~/.config/contree/cli.ini (read only by the CLI)
[profile:cli-sandbox]
url = https://staging.contree.dev
token = eyJhbGciOi...different
```
The active profile is still selected by the `profile` key in
`[DEFAULT]` of `auth.ini` (or by `--profile` / `$CONTREE_PROFILE`).
## Environment variables
Read at runtime by any command:
| Variable | Description |
| - | - |
| `CONTREE_HOME` | Data directory (default `$XDG_CONFIG_HOME/contree`, or `~/.config/contree`) |
| `XDG_CONFIG_HOME` | XDG base config dir, used to derive the default `CONTREE_HOME` |
| `CONTREE_PROFILE` | Active profile name (selects which profile commands use) |
| `CONTREE_SESSION` | Explicit session key (overrides auto-generated) |
Read only by `contree auth` (registration-time fallbacks for omitted flags):
| Variable | Used for |
| - | - |
| `CONTREE_TOKEN` / `NEBIUS_API_KEY` | `--token` |
| `CONTREE_URL` | `--url` |
| `CONTREE_PROJECT` / `NEBIUS_AI_PROJECT` | `--project` |
## Resolution precedence
For token, URL, and project at runtime:
1. CLI flag (`--token`, `--url`, `--project`) — overrides profile for the
current invocation only
2. Saved profile field
3. Built-in default URL for IAM: `https://api.tokenfactory.nebius.com/sandboxes`
Environment variables are not consulted at runtime; to refresh credentials
from environment variables, run `contree auth` (which reads
`CONTREE_TOKEN` / `NEBIUS_API_KEY`, `CONTREE_URL`, and `CONTREE_PROJECT` /
`NEBIUS_AI_PROJECT` as fallbacks for the corresponding flags).
For profiles:
1. `-p` / `--profile` flag
2. `CONTREE_PROFILE` environment variable
3. `profile` key in config `[DEFAULT]` section
4. Falls back to `default`
***
See [auth - Configure credentials and profiles](../commands/auth) for the full auth command reference, or
[Command Reference](../commands/index) for all commands.
# Working with Files
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/files
contree-cli lets you inject local files into sandboxes, edit remote files
in-place, and stage changes that automatically apply on the next run.
## Inject a file with `--file`
Use `--file` / `-F` on `contree run` to attach a local file:
> [tab] CLI
>
> ```bash theme={null}
> contree run --file ./app.py python /app.py
> ```
> [tab] Shell
>
> ```text theme={null}
> contree run --file ./app.py python /app.py
> ```
>
> Flags like `--file` require the explicit `contree run` prefix.
By default the file is placed at the same path inside the sandbox.
Specify a different destination with a colon:
```bash CLI theme={null}
contree run --file ./app.py:/app/main.py python /app/main.py
```
```text Shell theme={null}
contree run --file ./app.py:/app/main.py python /app/main.py
```
### Full `--file` syntax
```
host_path[:instance_path][:uUID][:gGID][:mMODE]
```
* **host\_path** – path to the file on your machine (required)
* **instance\_path** – destination path inside the sandbox (detected by
leading `/`). Defaults to the host path.
* **uUID** – owner UID (prefix `u`). Numeric or name (resolved locally).
* **gGID** – group GID (prefix `g`). Numeric or name (resolved locally).
* **mMODE** – octal permission mode (prefix `m`).
Tagged options (`u`, `g`, `m`) can appear in any order after the host
path. Unspecified values default to the host file’s stat.
```bash theme={null}
# Override only mode
contree run --file ./script.sh:m0755 /script.sh
# All explicit
contree run --file ./app.py:/app.py:u0:g0:m0755 python /app.py
# Named uid/gid (resolved from local system)
contree run --file ./app.py:uroot:groot python /app.py
```
> [!NOTE]
>
> Named uid/gid (e.g. `uroot`) are resolved locally via `pwd`/`grp`
> modules. Use numeric IDs if unsure about host/instance mismatch.
### Multiple files
Repeat the `--file` flag:
```bash theme={null}
contree run \
--file ./app.py:/app.py \
--file ./config.yaml:/etc/app/config.yaml \
python /app.py
```
### Directories
`--file` also accepts directories. The entire tree is uploaded recursively:
```bash theme={null}
contree run --file ./src:/app/src -- make -C /app/src
```
Common junk is excluded by default: `.*`, `.git`, `*.pyc`, `__pycache__`,
`.venv`, `.mypy_cache`, `.pytest_cache`, `node_modules`, `dist`, `build`.
Add extra exclusions with `--file-excludes`:
```bash theme={null}
contree run --file ./project:/app --file-excludes '*.log' '*.tmp' -- make -C /app
```
### Upload caching
The CLI keeps a local upload cache keyed by file path, inode, modification
time, and size. Repeated attachments of unchanged files skip both the hash
calculation and the API call. The cache expires after 90 days to account
for server-side file retention.
The server also deduplicates by SHA256 — if the same content was uploaded
from a different session or machine, it is reused without re-uploading.
## Edit remote files
> [tab] CLI
>
> `contree file edit` downloads a file from the session image, opens it
> in your `$EDITOR`, and stages the changes as a pending file:
>
> ```bash theme={null}
> contree file edit /etc/nginx/nginx.conf
> ```
> [tab] Shell
>
> In the interactive shell, `vim`, `vi`, and `nano` are aliases for
> `contree file edit`, using your host `$EDITOR`:
>
> ```text theme={null}
> vim /etc/nginx/nginx.conf
> ```
>
> You can also use the full command:
>
> ```text theme={null}
> contree file edit /etc/nginx/nginx.conf
> ```
What happens step by step:
1. The file is downloaded from the current session image to a temp file
2. Your editor opens (`$EDITOR`, defaults to `vi`)
3. If you saved changes, the modified file is uploaded and staged as pending
4. If the file is unchanged (same SHA256), nothing is staged
If the file does not exist in the image yet, an empty file is created for
you to fill in.
### Iterate without re-running
You can edit multiple files before running:
```bash CLI theme={null}
contree file edit /etc/nginx/nginx.conf
contree file edit /etc/nginx/sites-enabled/default
contree run nginx -t # test config with both edits applied
```
```text Shell theme={null}
vim /etc/nginx/nginx.conf
vim /etc/nginx/sites-enabled/default
nginx -t
```
Both edits are staged as pending and applied together on the next run.
## Stage local files with `contree file cp`
`contree file cp` copies a local file into the session as a pending file:
```bash CLI theme={null}
contree file cp ./config.yaml /etc/app/config.yaml
```
```text Shell theme={null}
contree file cp ./config.yaml /etc/app/config.yaml
```
This uploads the file and records it as pending – it does not run anything.
The file will be included in the next `contree run` automatically.
### Build up a working environment
```bash CLI theme={null}
contree file cp ./app.py /app/app.py
contree file cp ./requirements.txt /app/requirements.txt
contree file cp ./config.yaml /etc/app/config.yaml
contree run pip install -r /app/requirements.txt
contree run python /app/app.py
```
```text Shell theme={null}
contree file cp ./app.py /app/app.py
contree file cp ./requirements.txt /app/requirements.txt
contree file cp ./config.yaml /etc/app/config.yaml
pip install -r /app/requirements.txt
python /app/app.py
```
The first `run` consumes all three pending files and bakes them into the
new image. The second `run` already has them – no re-upload needed.
## How pending files work
Pending files accumulate until the next `contree run`:
1. Each `file edit` or `file cp` records a pending file in the session
2. When you run `contree run`, all pending files are merged into the payload
3. After the run completes, the new image already contains those files
4. The pending queue is effectively cleared (a new history checkpoint is
created past them)
Explicit `--file` flags on `contree run` take priority over pending files
at the same path.
Pending files are branch-aware – switching branches with
`contree session checkout` changes which pending files are visible.
## Deduplication
Files are uploaded to the API with SHA256 dedup. If the same file content
has already been uploaded (from a previous edit or a different session), it
is reused without re-uploading.
***
You can inject and edit files. Next: [Images & Tags](./images).
# Your First Sandbox
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/first-steps
Now that you’re authenticated, let’s spin up a sandbox and explore it.
## Browse images
List available images:
```bash CLI theme={null}
contree images --prefix=ubuntu
```
```text Shell theme={null}
contree images --prefix=ubuntu
```
## Sessions
Every command in ConTree runs inside a **session** — a named workspace
that tracks which image you’re on, your working directory, file uploads,
and full branch/rollback history.
### How sessions are picked
You don’t have to create a session manually. When you run any command,
ConTree auto-generates a session key from your profile, parent process
ID, and terminal (TTY). This means the same terminal window gets the
same session — but **opening a new terminal creates a new session**
because the process ID changes.
There are three ways to control which session is used (in priority order):
1. **`-S` flag** — `contree -S my-session run ...` — explicit, survives terminal restarts
2. **`CONTREE_SESSION` env var** — `export CONTREE_SESSION=my-session` — stable for the shell session
3. **Auto-generated** — derived from profile + PID + TTY (default, tied to current terminal)
### Starting a session
The recommended way is `eval`, which exports the session key so it
survives across commands and is easy to resume later:
```bash theme={null}
eval $(contree use tag:ubuntu:latest)
```
Without `eval`, `contree use` still works within the same terminal —
the auto-generated key is stable as long as the terminal stays open:
```bash theme={null}
contree use tag:ubuntu:latest # sets image
contree run uname -a # same session (same terminal)
```
But if you close the terminal and open a new one, the auto-generated
session key changes. To resume a previous session, use `eval` or `-S`.
### Resuming sessions
List existing sessions and resume one:
```bash theme={null}
contree session list # find the session key
contree -S my-project+a1b2c3d4 use # resume it
```
Or pin a human-readable name from the start:
```bash theme={null}
contree -S build use tag:ubuntu:latest
contree -S build run -- make test
# close terminal, open new one — same session:
contree -S build run -- make deploy
```
> [!TIP]
>
> For agent workflows or scripts, always use `-S`:
>
> ```bash theme={null}
> contree -S build-agent use tag:ubuntu:latest
> contree -S build-agent run -- make build
> contree -S build-agent run -- make test
> ```
>
> This is the most reliable — no `eval`, no terminal dependency.
Inside `contree shell`, you don’t need `eval` — but the shell still
needs a session. Use `-S` or `CONTREE_SESSION` to pin it:
```bash theme={null}
contree -S my-project shell
```
Without `-S`, the auto-generated session is used (tied to current terminal).
## Run a command
> [tab] CLI
>
> ```bash theme={null}
> contree run uname -a
> ```
> [tab] Shell
>
> ```text theme={null}
> uname -a
> ```
>
> Bare commands are executed as implicit `run` in the sandbox.
> `contree run uname -a` works too – use the explicit form when you need
> flags like `-D`, `-e`, or `--file`.
The CLI spawns a sandbox, waits for it to finish, and prints stdout/stderr.
The resulting filesystem becomes the new session image – every non-disposable
run produces a new checkpoint.
> [!TIP]
>
> The `--` separator is optional. ConTree parses its own flags correctly
> regardless. It is a useful convention to visually separate contree options
> from the sandbox command:
>
> ```bash theme={null}
> contree run -D -- apt-get install -y curl
> ```
>
> Both `contree run uname -a` and `contree run -- uname -a` work the same way.
## Check session status
See what image and session you’re working with:
```bash CLI theme={null}
contree use
```
```text Shell theme={null}
contree use
```
Running `contree use` without arguments prints the current session info.
## Install packages
Commands chain naturally. Each run advances the session image:
> [tab] CLI
>
> ```bash theme={null}
> contree run apt-get update -qq
> contree run apt-get install -y curl
> ```
> [tab] Shell
>
> ```text theme={null}
> apt-get update -qq
> apt-get install -y curl
> ```
>
> Or equivalently with the explicit prefix:
>
> ```text theme={null}
> contree run apt-get update -qq
> contree run apt-get install -y curl
> ```
After these two runs the session image includes `curl`.
## Change working directory
Set a working directory for the session — subsequent commands resolve
relative paths against it:
```bash theme={null}
contree cd /app
contree run -- ls # lists /app
contree cat README.md # reads /app/README.md
contree cd # reset to sandbox default
```
## Inspect the filesystem
List files and read content without spawning a new sandbox:
> [tab] CLI
>
> ```bash theme={null}
> contree ls /usr/bin
> contree cat /etc/os-release
> ```
> [tab] Shell
>
> ```text theme={null}
> ls /usr/bin
> cat /etc/os-release
> ```
>
> `ls` and `cat` are aliases for the contree API commands (no sandbox spawned).
> To run the actual instance commands instead, use the explicit prefix:
>
> ```text theme={null}
> contree run ls /usr/bin
> contree run cat /etc/os-release
> ```
## Download a file
Copy a file from the sandbox to your local machine:
> [tab] CLI
>
> ```bash theme={null}
> contree cp /etc/os-release ./os-release.txt
> ```
> [tab] Shell
>
> ```text theme={null}
> contree cp /etc/os-release ./os-release.txt
> ```
>
> There is no short alias for `cp` – use the full `contree cp` prefix.
## Disposable mode
Use `-D` / `--disposable` when you want to run a command without advancing the
session image. Changes are discarded after execution:
> [tab] CLI
>
> ```bash theme={null}
> contree run -D -- rm -rf /important
> ```
> [tab] Shell
>
> ```text theme={null}
> contree run -D -- rm -rf /important
> ```
>
> Flags like `-D` require the explicit `contree run` prefix.
The session image stays exactly where it was before this run.
***
Your session tracks every command. Next: [Interactive Shell](./shell).
# Images & Tags
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/images
Images are filesystem snapshots. Every non-disposable `contree run`
produces a new image. Tags give images human-readable names so you
can find and reuse them later.
All data — images, operations, and uploaded files — is scoped to a
**Project**. Multiple tokens can access the same project and share
its data. Different projects have separate scopes — nothing is
visible across project boundaries.
## Listing images
Show tagged images:
```bash theme={null}
contree images
```
Filter by tag prefix:
```bash theme={null}
contree images --prefix=ubuntu
contree images --prefix=my-app
```
Include untagged images:
```bash theme={null}
contree images -a
```
Filter by time:
```bash theme={null}
contree images --since 1d # last 24 hours
contree images --since 2025-04-01
```
## Tagging images
With one argument, tags the current session image. With two, the first
is the image reference:
```bash theme={null}
contree tag my-app:v1.0 # current session image
contree tag UUID my-app:v1.0 # specific image by UUID
contree tag tag:alpine:latest my-alpine # re-tag by reference
```
The CLI resolves tag references to UUIDs automatically — you don’t
need to look up the UUID first.
Tags follow a free-form `name:version` convention. Common patterns:
```bash theme={null}
contree tag UUID my-app:latest
contree tag UUID my-app:v2.0
contree tag UUID common/python-ml/python:3.11-slim
```
Remove a tag:
```bash theme={null}
contree tag -U UUID my-app:v1.0
```
### Tag rules
* Tags are scoped to your Project (API token)
* Each image can have multiple tags
* Tags are unique — assigning an existing tag to a different image **moves** it
* Allowed characters: `a-z`, `0-9`, `_`, `-`, with `:`, `/`, `.` as separators
* Max length: 256 characters
* Case-sensitive (lowercase recommended)
### Shadow behavior
Public images (like `ubuntu:latest`) have their own tags. When you assign
the same tag to your own image, the public image is still accessible by
UUID but its tag becomes shadowed. Removing your tag restores the public
one.
## Using tags
Use `tag:NAME` anywhere an image UUID is expected:
```bash theme={null}
contree use tag:my-app:latest
```
If both you and a public image share a tag, your image wins.
## Importing images
Pull images from container registries (Docker Hub, GHCR, etc.):
```bash theme={null}
contree images import ubuntu:latest
contree images import --timeout 600 ubuntu:latest
contree images import python:3.11-slim
contree images import ghcr.io/org/repo:tag
```
Import is asynchronous — the CLI polls until the operation completes.
Press Ctrl+C to cancel.
Import multiple at once:
```bash theme={null}
contree images import ubuntu:latest python:3.11-slim node:20-slim
```
### Private registries
Authenticate with `--username`:
```bash theme={null}
contree images import --username=user registry.example.com/image:tag
```
The password is prompted securely if `--username` is provided.
Credentials are used only for the import operation and discarded
immediately after — the server does not store them.
## Reusing images across sessions
A common workflow is to prepare a base environment, tag it, and
reuse it in future sessions:
```bash theme={null}
# Session 1: build the environment
contree use tag:ubuntu:latest
contree run apt-get update -qq
contree run apt-get install -y python3 python3-pip build-essential
contree tag UUID python-dev:latest
# Session 2 (days later): start from the prepared image
contree use tag:python-dev:latest
contree run pip install -r requirements.txt
```
> [!TIP]
>
> Search for existing tagged images before rebuilding:
>
> ```bash theme={null}
> contree images --prefix=python-dev
> ```
***
Images are your checkpoints. Next: [Building from a Dockerfile](./build).
# Tutorial
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/index
Learn contree-cli by building a real workflow – from zero to automated
scripting in nine short sections.
## What you’ll build
By the end of this tutorial you will:
* Spin up sandboxes from images and run arbitrary commands
* Track sandbox state through sessions with branching and rollback
* Inject local files, edit remote configs, and tag working images
* Script everything with JSON output, detached runs, and operation monitoring
## Before you start
You need two things:
* **Python 3.10+** installed on your machine
* **A ConTree API token** — get one from your [project dashboard](https://contree.dev)
## The path
> [card] [1. Install & Authenticate](./installation)
>
> Install contree-cli, save your API token, and set up named profiles for
> different environments.
> [card] [2. Your First Sandbox](./first-steps)
>
> Browse images, run commands, inspect the filesystem, and download files.
> Understand how each run creates a new checkpoint.
> [card] [3. Interactive Shell](./shell)
>
> Use the REPL for rapid iteration: tab completion for paths, images, and
> branches, command aliases, and persistent history.
> [card] [4. Sessions & Branches](./sessions)
>
> Branch off to experiment, roll back mistakes, share sessions across
> terminals, and start fresh when needed.
> [card] [5. Working with Files](./files)
>
> Inject local code into sandboxes, edit remote files in-place, and stage
> changes that auto-attach on the next run.
> [card] [6. Images & Tags](./images)
>
> Tag working images for reuse, import from registries, and search by
> prefix. Build reusable base environments.
> [card] [7. Building from a Dockerfile](./build)
>
> Turn a `Dockerfile` into a tagged ConTree image. Layer caching,
> build args, `.dockerignore`, and URL streaming for `ADD`.
> [card] [8. Scripting & Automation](./workflows)
>
> Shell mode, shebang scripts, detached runs, operation monitoring, and
> machine-readable output formats for pipelines.
> [card] [9. Configuration & Profiles](./configuration)
>
> Create and switch between profiles for different projects, understand
> how profiles affect sessions, and configure environment variables.
## Quick taste
If you just want to see contree-cli in action before diving in:
> [tab] CLI
>
> ```bash theme={null}
> # install
> git clone https://github.com/nebius/contree-cli.git
> cd contree-cli && uv sync
>
> # authenticate (token prompted securely)
> contree auth
>
> # start a session and run a command
> eval $(contree use tag:ubuntu:latest)
> contree run uname -a
>
> # inspect the result
> contree ls /
> contree cat /etc/os-release
> ```
> [tab] Shell
>
> ```bash theme={null}
> # install and authenticate first (see CLI tab)
> contree auth
>
> # start the interactive shell
> contree shell
> ```
>
> Once inside the shell:
>
> ```text theme={null}
> contree use tag:ubuntu:latest
> uname -a
> ls /
> cat /etc/os-release
> ```
Ready? Start with [Install & Authenticate](./installation).
# Install & Authenticate
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/installation
## Requirements
* Python 3.10 or later
* The `contree-client` library (installed automatically)
## Install
```bash uv (recommended) theme={null}
uv tool install contree-cli
```
```bash pip theme={null}
pip install contree-cli
```
```bash pipx theme={null}
pipx install contree-cli
```
```bash From source theme={null}
git clone https://github.com/nebius/contree-cli.git
cd contree-cli
uv sync
```
Verify the installation:
```bash theme={null}
contree --help
```
### Development setup
To work on contree-cli itself:
```bash theme={null}
git clone https://github.com/nebius/contree-cli.git
cd contree-cli
uv sync --group dev
make check # lint + type check
make tests # lint + type check + pytest
```
## Authenticate
All ConTree API calls require a bearer token and a project ID.
### Save credentials
Get an API token and project ID from your ConTree project, then save them:
```bash theme={null}
contree auth
```
You will be prompted to enter:
1. **Token** — entered securely (no echo)
2. **Project ID** — your project identifier
The CLI verifies the token with the API and writes credentials to
`~/.config/contree/auth.ini`. If a profile already exists you will be
prompted to confirm; use `-y` to skip the prompt.
Resolution order for each field during `contree auth` (first match wins):
1. CLI flag (`--token`, `--url`, `--project`)
2. Environment variables, in order:
* token: `CONTREE_TOKEN`, then `NEBIUS_API_KEY`
* URL: `CONTREE_URL`
* project: `CONTREE_PROJECT`, then `NEBIUS_AI_PROJECT`
3. Interactive prompt
So if these variables are already in your environment and no flags
are passed, `contree auth` picks them up automatically, no interactive
prompts needed:
```bash theme={null}
export NEBIUS_API_KEY=eyJ...
export NEBIUS_AI_PROJECT=your-project-id
contree auth -y # fully non-interactive
```
> [!WARNING]
>
> Avoid `contree auth --token=eyJ...` — the token is visible in process
> listings and shell history. Omit `--token` to use the secure prompt.
### Named profiles
Store multiple tokens for different projects or environments:
```bash theme={null}
contree auth --profile=personal
contree auth --profile=sandbox
```
List all profiles:
```bash theme={null}
contree auth ls
```
Switch the active profile permanently:
```bash theme={null}
contree auth switch personal
```
Or use a profile temporarily (single session, no config change):
```bash theme={null}
export CONTREE_PROFILE=personal
contree images # uses personal
```
### Token from environment
`CONTREE_TOKEN` and `NEBIUS_API_KEY` are read **only** by `contree auth`
during profile registration; runtime commands always read credentials
from the saved profile. To bootstrap a profile entirely from environment
variables, run `auth` non-interactively:
```bash theme={null}
export CONTREE_TOKEN=eyJ...
export CONTREE_URL=https://api.tokenfactory.nebius.com/sandboxes
contree auth -y --type jwt # one-shot setup, no prompts
contree images
```
### Inline token
Pass `--token` to any command to override the saved profile for a single
invocation:
```bash theme={null}
contree --token=eyJ... images
```
***
You’re authenticated. Next: [Your First Sandbox](./first-steps).
# Sessions, Branches & Rollback
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/sessions
Sessions track the current image and its history as you run commands. Every
non-disposable `contree run` produces a new image, and the session records
the chain. Sessions also support **branching** and **rollback** for
experimentation.
## Session key
Every session is identified by a **session key** – an arbitrary string.
The CLI computes one automatically so that each terminal window gets its
own session without any extra setup.
The auto-generated key is a deterministic UUID5 derived from three values:
| Component | Source | Purpose |
| - | - | - |
| `profile` | Active config profile name | Isolates sessions per profile |
| `ppid` | Parent process ID (`os.getppid()`) | The shell that launched the CLI |
| `tty` | TTY device of stdin (`os.ttyname()`) | Distinguishes terminal windows |
**In practice this means:**
* Open a new terminal tab – new `ppid` + `tty` – **new session**.
* Run `contree` commands in the same terminal – same `ppid` + `tty` –
**same session** (resumes where you left off).
* Switch profiles – different `profile` – **new session**.
## Viewing session state
```bash CLI theme={null}
contree session # show current session info
contree session list # list all sessions
contree session show # show full history DAG
```
```text Shell theme={null}
contree session
contree session list
contree session show
```
## Branching
Create a branch to experiment without affecting the main line:
```bash CLI theme={null}
contree session branch experiment
contree session checkout experiment
contree run apt-get install -y curl
```
```text Shell theme={null}
contree session branch experiment
contree session checkout experiment
apt-get install -y curl
```
Not happy? Switch back:
```bash CLI theme={null}
contree session checkout main
```
```text Shell theme={null}
contree session checkout main
```
Branches share history entries – creating a branch just creates a new
pointer at the current position.
Create a branch from another branch:
```bash CLI theme={null}
contree session branch hotfix --from main
```
```text Shell theme={null}
contree session branch hotfix --from main
```
List branches (`*` marks the active one):
```bash CLI theme={null}
contree session branch
```
```text Shell theme={null}
contree session branch
```
## Rollback
Move the branch pointer in the history chain. The argument distinguishes
absolute jumps from relative navigation:
| Argument | Meaning |
| - | - |
| *(none)* | Back one entry (default) |
| `-- -N` | Back N entries (the `--` stops argparse from parsing `-N` as a flag) |
| `+N` | Forward N entries |
| `N` (bare positive) | **Absolute** jump to history id `N` |
```bash CLI theme={null}
contree session rollback # back one entry
contree session rollback -- -3 # back three entries
contree session rollback +1 # forward one entry
contree session rollback 42 # absolute jump to history id 42
```
```text Shell theme={null}
contree session rollback
contree session rollback -- -3
contree session rollback +1
contree session rollback 42
```
> [!WARNING]
>
> A bare positive number is an **absolute** history id, not “back N steps”.
> Use `--` followed by a negative number for relative back-navigation.
> Inspect with `contree session show` first to avoid surprise jumps.
The history entries still exist and can be recovered by creating a branch at
a specific point.
## Starting a fresh session
Because the auto-generated key is deterministic, the same terminal always
resumes the same session. Use `--new` (`-N`) to start a fresh session:
> [tab] CLI
>
> ```bash theme={null}
> # bash / zsh
> eval $(contree use -N tag:python:3.11-slim)
>
> # fish
> eval (contree use -N tag:python:3.11-slim)
> ```
>
> Without `eval`, the new session is **not active** until you export the
> printed variable into your shell. You can also copy-paste the `export`
> (or `set -gx`) line that `contree use` prints.
> [tab] Shell
>
> ```text theme={null}
> contree use -N tag:python:3.11-slim
> ```
>
> Inside the interactive shell, no `eval` is needed – the new session is
> activated automatically.
You can also set `CONTREE_SESSION` to any string:
```bash theme={null}
export CONTREE_SESSION=tutorial
contree use tag:python:3.11-slim
```
Unset it to go back to the automatic key:
```bash theme={null}
unset CONTREE_SESSION
```
## Sharing a session across terminals
`contree use` prints the session key. Export it in another terminal to
attach to the same session:
```bash theme={null}
# Terminal 1
contree use tag:ubuntu:latest
# output: export CONTREE_SESSION=
# Terminal 2 -- paste the line above
export CONTREE_SESSION=
contree run ls / # operates on the same session
```
> [!NOTE]
>
> This pattern is CLI-only. The interactive shell manages sessions internally
> and does not require manual session key export.
## Storage
Session data is stored in a per-profile SQLite database at
`~/.config/contree/sessions-{profile}.db`. Override the data
directory with `CONTREE_HOME`:
```bash theme={null}
export CONTREE_HOME=/tmp/contree-data
```
***
You can experiment freely with branches. Next: [Working with Files](./files).
# Interactive Shell
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/shell
`contree shell` starts a REPL that combines management commands and sandbox
execution in a single session. It is the fastest way to explore images, run
commands, edit files, and manage branches – all without leaving the prompt.
## Starting the shell
The shell needs a session, just like any other command. You can pin one
explicitly or let it auto-generate:
```bash theme={null}
contree -S my-project shell # explicit session name
CONTREE_SESSION=my-project contree shell # same via env var
contree shell # auto-generated (tied to terminal)
```
The shell prints a coloured prompt showing the current working directory:
```text theme={null}
contree interactive shell (type 'help' for commands, Ctrl-D to exit)
contree:/>
```
If the session already has an image (from a previous `contree use`), the
shell resumes it. Otherwise, set one first:
```text theme={null}
contree:/> contree use tag:ubuntu:latest
```
## Running commands
Type any command and it runs inside the sandbox:
```text theme={null}
contree:/> apt-get update -qq
contree:/> apt-get install -y curl
contree:/> curl https://example.com
```
Each command is an implicit `contree run` with `shell=True`. The whole
input line is forwarded verbatim to the remote `sh -c`, so pipes,
redirects, `;`, `&&`, and `||` are interpreted by the sandbox shell
exactly as typed:
```text theme={null}
contree:/> echo hello && ls / | head -5
contree:/> mount | grep cgroup
contree:/> echo 1 ; echo 2
contree:/> uname -a > /tmp/info.txt
```
Quoting from your local prompt is also preserved through to the remote
shell:
```text theme={null}
contree:/> python3 -c "print('hello world')"
```
You can also use the explicit form, which is equivalent:
```text theme={null}
contree:/> contree run apt-get install -y curl
```
The explicit `contree run` prefix is required when you need flags like
`-D` (disposable), `-e` (env), `-t` (timeout), `--file`, or `-d` (detach):
```text theme={null}
contree:/> contree run -D -- rm -rf /tmp/*
contree:/> contree run -e DEBUG=1 -- ./app
contree:/> contree run -d -- long-running-task
```
## Tab completion
The shell supports context-aware tab completion for nearly everything.
Press Tab at any point to see available completions.
### What completes
**Commands and subcommands** – type `contree` then Tab to see all
available subcommands. Type a partial name and Tab completes it:
```text theme={null}
contree:/> contree ses
contree:/> contree session
branch checkout list rollback show use
```
**Flags** – type `-` or `--` after a command and Tab shows available
flags:
```text theme={null}
contree:/> contree run --
--cwd --detach --disposable --env --file --hostname ...
```
**Sandbox paths** – any command that takes a file path completes
against the actual sandbox filesystem. The shell queries the image
via the inspect API and caches the results:
```text theme={null}
contree:/> ls /etc/
apt/ bash.bashrc default/ hostname nginx/ passwd ...
contree:/> cat /etc/os-
contree:/> cat /etc/os-release
contree:/> vim /etc/nginx/
nginx.conf sites-enabled/
```
**Directory-only paths** – `cd` completes only directories:
```text theme={null}
contree:/> cd /us
contree:/> cd /usr/
bin/ include/ lib/ local/ sbin/ share/
```
**Images** – `contree use` and `contree tag` complete image references.
Type `tag:` to filter by tag names, or start typing a UUID:
```text theme={null}
contree:/> contree use tag:
tag:ubuntu:latest tag:python:3.11-slim tag:common/rust/ubuntu:noble ...
contree:/> contree use tag:py
contree:/> contree use tag:python:3.11-slim
```
**Operations** – `contree show` and `contree kill` complete operation
UUIDs:
```text theme={null}
contree:/> contree show
a1b2c3d4-... e5f6a7b8-...
```
**Branches and sessions** – session management subcommands complete
branch names and session keys:
```text theme={null}
contree:/> contree session checkout
main experiment hotfix
contree:/> contree session use
abc123_def456 tutorial ci-build-42
```
**Help topics** – `help` completes all command and alias names:
```text theme={null}
contree:/> help
cat cd contree exit help history ls nano pwd quit vim ...
```
### What does not complete
**Bare commands** (implicit `run`) do not have tab completion. The shell
does not know what executables exist inside the sandbox, so typing a
bare command name and pressing Tab will not offer suggestions:
```text theme={null}
contree:/> apt-g # no completion
contree:/> pyth # no completion
```
However, paths starting with `/` do complete even in bare command context:
```text theme={null}
contree:/> python /app/
main.py utils.py config.yaml
```
## Aliases
The shell intercepts several bare command names for convenience:
### `ls` and `cat`
Bare `ls` and `cat` are forwarded as contree API commands – they inspect
the sandbox filesystem without spawning a new instance:
```text theme={null}
contree:/> ls /etc
contree:/> cat /etc/os-release
```
This is equivalent to `contree ls` and `contree cat`. To run the actual
`ls` or `cat` binary inside the sandbox instead, use the explicit prefix:
```text theme={null}
contree:/> contree run ls -la /etc
contree:/> contree run cat -n /etc/os-release
```
> [!NOTE]
>
> When pending files exist (from `contree file edit` or `contree file cp`),
> `ls` and `cat` automatically fall back to running inside the sandbox so
> the pending files are visible.
>
> The same fallback happens when arguments contain flags (`-l`) or glob
> characters (`*`, `?`, `[`).
### `vim`, `vi`, `nvim`, `nano`
Editor names open `contree file edit` with the corresponding host editor:
```text theme={null}
contree:/> vim /etc/nginx/nginx.conf
```
This downloads the file, opens it in vim on your machine, and stages any
changes as a pending file for the next run.
## Builtins
### `cd`
Change the working directory for subsequent commands:
```text theme={null}
contree:/> cd /app
contree:/app> python main.py
contree:/app> cd - # go back to previous directory
contree:/>
```
`cd` without arguments resets to the sandbox’s default working directory.
> [!NOTE]
>
> `cd` does not validate that the path exists in the sandbox. Errors
> surface only when the next command uses the invalid path.
### `pwd`
Print the current working directory:
```text theme={null}
contree:/app> pwd
/app
```
### `history`
Show command history for the current session, optionally filtered by a
case-insensitive substring:
```text theme={null}
contree:/> history # show all entries
contree:/> history apt # only lines containing "apt"
contree:/> history 'contree ' # quoted match (note trailing space)
```
History is persisted in SQLite per session (up to 10,000 lines) and
restored when you re-enter the shell. Search is scoped to the current
session key; different sessions have isolated history.
### `help`
Show general shell help, or help for a specific command or builtin:
```text theme={null}
contree:/> help
contree:/> help cd
contree:/> help run
```
Bare `help` prints an overview of builtins, aliases, line continuation,
and tab completion. `help ` shows detailed help for a builtin,
alias, or contree command.
### `clear`
Clear the terminal screen:
```text theme={null}
contree:/> clear
```
### `timeout`
Run a command with a server-enforced operation timeout. Mirrors the GNU
`timeout` convention but sets `payload.timeout` on the API request instead
of spawning a local wrapper inside the sandbox:
```text theme={null}
contree:/> timeout 30 apk add gcc
contree:/> timeout 5m make build
contree:/> timeout 1h python long_train.py
```
`DURATION` accepts a bare integer or decimal (seconds by default) and
the suffixes `s`, `m`, `h`, `d`. When the value cannot be parsed, the
shell forwards the line untouched so the in-image `timeout` binary still
handles advanced flags like `--kill-after` or `-s SIGTERM`.
When the limit fires, the API returns `state.timed_out=true` (status may
still be `SUCCESS` with `signal=9`), and the shell logs:
```text theme={null}
WARNING: Operation timed out after 30s
```
### `--format` / `-f`
Change the output format mid-session, or show the current format:
```text theme={null}
contree:/> --format json # switch to JSON output
contree:/> -o table # switch to table output
contree:/> --format # show current format name
```
## Workflow example
A typical shell session putting it all together:
```text theme={null}
contree:/> contree use tag:ubuntu:latest
contree:/> apt-get update -qq
contree:/> apt-get install -y python3 python3-pip
contree:/> contree file cp ./app.py /app/app.py
contree:/> contree file cp ./requirements.txt /app/requirements.txt
contree:/> cd /app
contree:/app> pip install -r requirements.txt
contree:/app> python3 app.py
contree:/app> vim app.py # edit and re-run
contree:/app> python3 app.py
contree:/app> contree session branch stable
contree:/app> contree tag UUID my-app:v1
```
## Limitations
* **Output format is fixed** – the `--format` flag is set at `contree shell`
launch. To use JSON output: `contree -o json shell`.
* **No local pipes or redirects** – `|`, `>`, `<` are sent to the sandbox,
not interpreted locally.
* **No job control** – no `&`, `bg`, `fg`, or Ctrl-Z. Use `contree run -d`
for detached execution.
* **Bare commands use defaults** – you cannot pass `--env`, `--file`, or
`--disposable` without the explicit `contree run` prefix. The operation
timeout has a shell shortcut: `timeout DURATION CMD...` (see above).
* **No `~` or glob expansion** – these tokens are passed as-is to the
sandbox.
* **Image list cache** – newly created images during a session won’t appear
in tab completion until the shell is restarted. Path completions are
cached per image and refresh when the session image advances.
***
The shell is the fastest way to iterate. Next: [Sessions, Branches & Rollback](./sessions).
# Scripting & Automation
Source: https://docs.tokenfactory.nebius.com/sandboxes/cli/tutorial/workflows
contree-cli is designed for scripting. Exit codes propagate, output formats
are machine-readable, and shebang mode lets you write executable sandbox
scripts.
## Shebang scripts
> [!NOTE]
>
> Shebang scripts are a CLI-only feature. They are not available in the
> interactive shell.
Any file with a `contree run -I` shebang runs inside a sandbox:
```bash theme={null}
#!/usr/bin/env -S contree run -I
echo "Hello from a ConTree sandbox"
uname -a
```
Save it, `chmod +x`, and run it directly:
```bash theme={null}
chmod +x hello.sh
./hello.sh
```
The `-I` (interpreter) flag reads the script, strips the shebang line, and
sends the body as stdin to `/bin/sh -s` inside the sandbox.
### Combining flags
Shebang flags stack. A disposable run with a 10-second timeout:
```bash theme={null}
#!/usr/bin/env -S contree run -I -D -t 10
apt-get update -qq
apt-get install -y curl
curl https://example.com
```
Since `-D` is set, the session image is not advanced – the script runs in
a throwaway sandbox.
### Passing arguments
Extra arguments after the script name are forwarded to the shell:
```bash theme={null}
#!/usr/bin/env -S contree run -I
echo "arg1=$1 arg2=$2"
```
```bash theme={null}
./script.sh foo bar
# arg1=foo arg2=bar
```
> [!NOTE]
>
> The `-S` flag on `/usr/bin/env` is required because the `contree` entry point
> is a Python script. Without `-S`, the kernel sees a nested shebang
> (script -> script -> binary) and returns ENOEXEC. Using `/usr/bin/env -S`
> (a real binary) splits the argument string and avoids this.
## Execution modes
### Direct command
The default mode. Each positional argument becomes a separate argv entry:
```bash CLI theme={null}
contree run uname -a
```
```text Shell theme={null}
uname -a
```
### Shell mode
`-s` joins all arguments into a single shell expression:
> [tab] CLI
>
> ```bash theme={null}
> contree run -s -- 'echo hello && ls /'
> ```
> [tab] Shell
>
> ```text theme={null}
> echo hello && ls /
> ```
>
> Bare commands in the shell always use shell mode.
Useful when you need pipes, redirects, or `&&` chains.
### Piped stdin
> [!NOTE]
>
> Piped stdin is a CLI-only feature. It is not available in the interactive
> shell.
When stdin is not a TTY, it is read, base64-encoded, and sent to the sandbox:
```bash theme={null}
echo 'uname -a' | contree run /bin/sh
```
```bash theme={null}
cat deploy.sh | contree run /bin/sh
```
### Detached mode
`-d` spawns the operation and exits immediately, printing the operation UUID:
> [tab] CLI
>
> ```bash theme={null}
> contree run -d -- long-running-task
> ```
>
> Check on it later:
>
> ```bash theme={null}
> contree show UUID
> ```
> [tab] Shell
>
> ```text theme={null}
> contree run -d -- long-running-task
> contree show UUID
> ```
>
> Flags like `-d` require the explicit `contree run` prefix.
## Exit codes
> [!NOTE]
>
> Exit code propagation is a CLI-only feature useful for scripting. The
> interactive shell does not expose sandbox exit codes.
The sandbox exit code propagates to the CLI process:
```bash theme={null}
contree run -- /bin/sh -c 'exit 42'
echo $? # 42
```
This means `contree run` works naturally in `if`, `&&`, `||`, and `set -e`
scripts:
```bash theme={null}
set -e
contree run -- make test # script aborts if tests fail
contree run -- make install
```
If the operation fails at the platform level (timeout, cancelled), the CLI
exits with code 1.
## Environment variables
Pass environment variables into the sandbox with `-e`:
> [tab] CLI
>
> ```bash theme={null}
> contree run -e DEBUG=1 -e DB_HOST=postgres -- ./app
> ```
> [tab] Shell
>
> ```text theme={null}
> contree run -e DEBUG=1 -e DB_HOST=postgres -- ./app
> ```
>
> Flags like `-e` require the explicit `contree run` prefix.
The flag is repeatable. Format is `KEY=VALUE`.
## Output truncation
By default, stdout/stderr is capped at 64 KiB in the API response. Override
with `-T`:
```bash CLI theme={null}
contree run -T 1048576 -- ./generate-big-output.sh
```
```text Shell theme={null}
contree run -T 1048576 -- ./generate-big-output.sh
```
## Monitor operations
List running and recent operations:
```bash CLI theme={null}
contree ps # active operations only
contree ps -a # all (including completed)
contree ps -q # UUIDs only, one per line
```
```text Shell theme={null}
contree ps
contree ps -a
contree ps -q
```
Show the full result of a specific operation:
```bash CLI theme={null}
contree show UUID
```
```text Shell theme={null}
contree show UUID
```
Cancel an operation:
```bash CLI theme={null}
contree kill UUID
contree kill --all
```
```text Shell theme={null}
contree kill UUID
contree kill --all
```
### Fan-out + wait
When several independent steps can run at the same time, spawn each
one detached and join them with `contree op wait` (alias `contree operation wait`). The wait command polls the API and prints one row
per operation as soon as it reaches a terminal status, with columns
`uuid`, `status`, `exit_code`, `timed_out`, `duration`, and any other
scalar field the API returns. The `status` column is the server’s
verdict (did the API run the job?) and is reported verbatim; the
sandbox process’s own exit code is in the separate `exit_code` column.
The CLI exit status is `1` when any op finished non-`SUCCESS`, or the
actual `exit_code` when a `SUCCESS` op exited non-zero, so the wait
still composes naturally with `&&`.
> [!NOTE]
>
> `op wait` is a **pure observer** — it polls completion status but
> **does not touch local session state**. That makes the pattern most
> natural with `--disposable` (no image to track). For non-disposable
> fan-out, the result images live only on the server; the
> `detached-` branches created at spawn time still point at
> the **starting** image and never get moved. See the non-disposable
> recovery example below.
The preferred shape — disposable runs, parallel independent checks.
The global `-o json` must come BEFORE the subcommand so that `jq`
gets JSON; the default `run -d` formatter is plain.
```bash theme={null}
# Three parallel test suites, results discarded after the runs
A=$(contree -o json run -d --disposable -- pytest tests/a | jq -r .uuid)
B=$(contree -o json run -d --disposable -- pytest tests/b | jq -r .uuid)
C=$(contree -o json run -d --disposable -- pytest tests/c | jq -r .uuid)
# Block until each one finishes (or 60 s elapses, whichever comes first)
contree op wait "$A" "$B" "$C"
# Inspect stdout/stderr per leg
contree op show "$A" "$B" "$C"
```
Non-disposable fan-out works too, but you have to recover the result
images yourself — `op wait` will not bind them into the session:
```bash theme={null}
A=$(contree -o json run -d -- apt-get install -y curl | jq -r .uuid)
B=$(contree -o json run -d -- apt-get install -y wget | jq -r .uuid)
contree op wait "$A" "$B"
# Pull the winning leg's image out of the operation result and
# attach it to the active session.
IMG_A=$(contree -o json op show "$A" | jq -r .image)
contree use "$IMG_A"
# Or tag it for reuse later.
contree tag "$IMG_A" feature/curl-tools
```
After fan-out + wait the session retains a `detached-`
branch per spawn. They all point at the image that existed when the
fan-out started, so they are mostly cosmetic — feel free to delete
them with `contree session branch --prune` when you no longer need
them.
Useful flags:
* `--timeout SECONDS` — cap on the wait (default 60). If the deadline
hits before every operation reaches a terminal status, `op wait`
emits one extra row per unfinished op with `timed_out=true` and the
operation’s last observed status (e.g. `EXECUTING`), then exits
with status `1`.
* `--all` — wait for every currently active operation in the project,
not just the ones you passed.
```bash theme={null}
# Block on every active op, up to 5 minutes
contree op wait --all --timeout 300
```
> [!WARNING]
>
> `--all` is **project-scoped**. If multiple agents or shell sessions
> share the same project, `op wait --all` will block on every active
> operation across all of them — not just the ones you launched. For
> multi-agent or multi-shell setups prefer the explicit
> `op wait UUID1 UUID2 ...` form with the UUIDs you actually own.
`op wait` exits non-zero whenever any operation finished with a
non-`SUCCESS` status (so it composes naturally with shell `&&`
chains), even when no `--timeout` was hit.
```bash theme={null}
# Run fan-out + tests; bail if any leg failed
contree op wait "$A" "$B" "$C" && echo "all green" || echo "some failed"
```
### Scripting patterns
> [!NOTE]
>
> Shell piping and command substitution are CLI-only features. These patterns
> are not available in the interactive shell.
Combine `-q` with other tools:
```bash theme={null}
# Show results of all active operations
contree ps -q | xargs -I {} contree show {}
# Kill all running operations
contree ps -q | xargs -I {} contree kill {}
# Launch detached, capture UUID
OP=$(contree run -d -- sleep 3600)
# ... do other work ...
contree show "$OP"
```
## Output formats
> [!NOTE]
>
> The `--format` flag is global and set at CLI launch time. In the interactive
> shell, the format is fixed for the entire session and cannot be changed
> mid-session.
Use `-f` / `--format` to control output. The flag is global and goes
before the subcommand:
`default`
: Table-like output optimized for human reading. Some commands (like
`run`) use a custom default that prints only stdout/stderr.
`table`
: Aligned columns with headers. Identical to `default` for most commands.
`csv`
: Comma-separated values with a header row. Useful for spreadsheet import
or `cut`/`awk` processing.
`tsv`
: Tab-separated values with a header row. Works well with `column -t`.
`json`
: One JSON object per line (JSONL/NDJSON). Each output row is a separate
JSON object. Suitable for `jq` processing.
`json-pretty`
: All rows collected into a single pretty-printed JSON array. Output is
flushed at the end.
### Examples
```bash theme={null}
# Pipe JSON to jq
contree -o json ps | jq '.uuid'
# CSV for scripting
contree -o csv images > images.csv
# Tab-separated for column alignment
contree -o tsv ps | column -t
# Get image UUID from tag
contree -o json images --prefix=ubuntu | jq -r '.uuid'
```
### Streaming behavior
`json` and `json-pretty` formatters support streaming output from
commands like `run` and `show` – stdout/stderr are included in the
JSON payload.
`csv`, `tsv`, and `table` formatters do not include stdout/stderr
from sandbox execution. Use `default` or `json` formats to see
sandbox output.
## Session management in scripts
> [!NOTE]
>
> Script-level session management with `eval` and `CONTREE_SESSION` is a
> CLI-only pattern. The interactive shell manages sessions automatically.
The `eval $(contree use ...)` pattern exports the session key into your
shell. In scripts, set `CONTREE_SESSION` explicitly to control which
session you operate on:
```bash theme={null}
#!/bin/bash
export CONTREE_SESSION=ci-build-$$
contree use tag:ubuntu:latest
contree run apt-get update -qq
contree run apt-get install -y build-essential
contree run --file ./src:/src make -C /src test
```
Using `$$` (PID) or a fixed name gives you a predictable, isolated session
per script run.
***
You now know the full CLI. Next: [Configuration & Profiles](./configuration).
# Execution lifecycle
Source: https://docs.tokenfactory.nebius.com/sandboxes/concepts/execution-lifecycle
Understand operations, processes, client waits, event streams, and saved images.
An operation starts fresh compute from an image and runs your command as its primary process. When that process ends, the service stops any remaining subprocesses and finishes the operation.
To reuse changed files, choose to save them before starting the operation. Then use the image UUID returned in its result. Saving an image does not keep the runtime alive.
## Lifecycle
```mermaid theme={null}
flowchart TB
A[Input image] --> B[Choose save or discard]
B --> C
subgraph runtime[Temporary compute]
C[Primary process runs]
C --> D[Primary process ends]
D --> E[Stop children
and finalize]
end
E --> F[Output and result]
F --> G{Saved image?}
G -->|Yes| H[Reuse its UUID]
G -->|No| I[No saved state]
```
For example, one operation can install dependencies and save an image. The next starts from those installed files on fresh compute. A server started during installation must be started again if the next operation needs it.
The primary process determines when finalization begins. Additional subprocesses share its VM, filesystem, resources, and operation lifetime. A subprocess result does not create a separate image.
## Operation states
The public operation API exposes these states:
| State | Meaning for a caller |
| - | - |
| `PENDING` | The operation is waiting to be assigned. |
| `ASSIGNED` | Resources have been assigned; execution may be starting. |
| `EXECUTING` | The operation is running. Wait for an application readiness signal before starting a subprocess that depends on the primary workload. |
| `SUCCESS` | The service completed the operation. Inspect the process exit code, signal, timeout flag, output, and result image separately. |
| `FAILED` | The service could not complete the operation. Use the operation error and ID for diagnosis. |
| `CANCELLED` | Cancellation reached a terminal operation state. Inspect the response before assuming a result image exists. |
> [!NOTE]
>
> `SUCCESS` is an operation state. A process can still report a nonzero exit code, signal, or timeout in its result. Check the process result before using its output or saved image.
## Separate lifetimes
### Client request or wait
A response, disconnect, or client-side limit ends the wait. Query the operation before submitting duplicate work.
### SSE subscription
The stream can complete, fail, or disconnect independently of execution. Resume with the last fully processed event ID when supported, then inspect terminal status.
### Operation compute
Compute ends when the primary workload finalizes, cancellation completes, or the platform fails the operation. Running processes, memory, and connections end with it.
### Stored image
The image remains available until it is removed or reaches the applicable retention boundary. Reuse its immutable UUID only while the image is available.
Do not treat a REST SSE disconnect as cancellation. Resume the stream or query the operation before deciding whether to retry. SDK 0.3.6 follows a different path: when its internal wait exits without observing a terminal state, it attempts to cancel the operation. Handle transport disconnects, SDK wait failures, execution timeouts, and explicit cancellation as separate cases.
## Results and recovery
### `SUCCESS` with exit code `0`
The command completed successfully. Inspect output and the returned image before continuing.
### `SUCCESS` with a nonzero exit code
The service ran the command, which reported failure. Correct the command or input and start a new operation from a known image.
### Process `timed_out=true`
The guest execution reached its configured limit. Inspect signal, exit state, output, and result-image fields. Do not assume timeout persistence.
### `CANCELLED`
The operation stopped after cancellation. Confirm terminal status and result-image availability before retrying.
### `FAILED` or a client exception
No normal successful operation result is available. Keep the operation ID and redacted error details; inspect status before retrying.
Choose the next image using the [result-image rules](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image).
## Continue
* [Images, checkpoints, and branches](/sandboxes/concepts/images-checkpoints-and-branches)
* [Sessions and execution modes](/sandboxes/concepts/sessions-and-execution-modes)
* [Run commands and handle results](/sandboxes/guides/run-commands-and-results)
* [Stream output and events](/sandboxes/guides/stream-output-and-events)
* [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input)
* [Operation status reference](/api-reference/sandboxes/operations/get-an-operation-status)
# Images, checkpoints, and branches
Source: https://docs.tokenfactory.nebius.com/sandboxes/concepts/images-checkpoints-and-branches
Save filesystem state deliberately and start independent work from immutable images.
An **image** is an immutable stored filesystem state. A **checkpoint** is an image chosen as a continuation point. A **branch** is an independent operation started from a selected image.
Images preserve saved files and installed dependencies. They do not preserve running processes, memory, open file handles, connections, or live services.
## Choose persistence before submission
Set persistence explicitly when later work needs the changed files. The Python SDK discards changes by default; the CLI saves them. A session does not override those defaults.
| Interface | Default in this interface | Explicit choice | Session effect |
| - | - | - | - |
| Python SDK 0.3.6 `image.run()` | `disposable=True` | `disposable=False` saves; `True` discards | The returned object exposes the process result and, when saved, an image you can reuse through its UUID or `.run()`. |
| Python SDK 0.3.6 `image.session().run()` | `disposable=True` | Set `disposable=False` for a step the session must reuse | The session object updates its image reference when the retained result supplies one. It does not preserve compute. |
| REST API | `disposable: false` in the public request schema | Always send `disposable: false` or `disposable: true` | REST has no client session unless the application implements one. |
| CLI 0.9.4 `contree run` | Retains changes unless `-D` or `--disposable` is set | Omit `-D` to retain; add `-D` to discard | A retained run advances the local session image; a disposable run leaves it on the prior image. |
| MCP `run` tool | `disposable=true` | Set `disposable=false` to request a saved result | The result includes `result_image` and `filesystem_changed`. Check the connected server's tool list before relying on this behavior. |
## Interpret the result image
Reuse a saved result only when the operation returns an image UUID and you can read the files you need from it. This also applies after a command failure, timeout, or cancellation. If no usable image is returned, restart from your last known-good image.
| Run outcome | Result-image interpretation |
| - | - |
| Save requested and filesystem changed | Use the returned image UUID only after confirming that it is present and inspectable. |
| Save requested and filesystem did not change | An interface may return the input image UUID or report no new image. Use the returned UUID when available; otherwise keep the input image as your starting point. |
| Disposable run | Filesystem changes are discarded. The operation may have output, while its result-image field can be absent. A client session can continue to reference the unchanged input image. |
| Nonzero exit, timeout, cancellation, or platform failure | Check that the result includes an image UUID and that its files can be read before using it. |
An absent result image means there is no new continuation point from that operation. An unchanged image ID means the existing immutable source remains the continuation point.
## Use UUIDs for repeatable work
A tag is a mutable name. Assigning an existing tag to another image moves the tag.
| Workflow | Reference to record |
| - | - |
| Reproducible evaluation or production run | Resolved input image UUID and returned result image UUID, when present |
| Maintained base updated over time | Tag for discovery plus the resolved UUID used by each run |
| Branch point | Immutable image UUID |
## Prepare once, branch twice
Save a shared input file once, then read it in two independent operations. The fragment belongs inside the async `main()` from the [Python quickstart](/sandboxes/start/python-quickstart), with its authenticated `client`. Use an image tag available in your project. The [complete recipe](/sandboxes/cookbook/prepare-once-reuse-safely) also shows how to run the two readers concurrently.
```python theme={null}
base = await client.images.use("alpine:3.19", strict=True)
preparation = base.run(
shell="printf 'shared input\\n' > /tmp/input.txt",
disposable=False,
)
checkpoint = await preparation
if checkpoint.exit_code != 0 or checkpoint.uuid is None:
raise RuntimeError("Preparation did not produce a usable checkpoint")
first = await checkpoint.run(
shell="printf 'first: '; cat /tmp/input.txt",
disposable=True,
)
second = await checkpoint.run(
shell="printf 'second: '; cat /tmp/input.txt",
disposable=True,
)
if first.exit_code != 0 or second.exit_code != 0:
raise RuntimeError("A checkpoint reader failed")
print(first.stdout, end="")
print(second.stdout, end="")
```
Expected output:
```text theme={null}
first: shared input
second: shared input
```
Each child starts from the same immutable checkpoint. A disposable child cannot change the checkpoint or the other child.
```mermaid theme={null}
flowchart TB
A[Base image] --> B[Prepare and save]
B --> C[Checkpoint]
C --> D[Run A]
C --> E[Run B]
D --> F[Output A]
E --> G[Output B]
```
Both runs read the checkpoint file and discard their own changes. The arrows show which image each operation starts from. The branches share a starting image, not a running process or a writable filesystem.
To continue from a branch, that branch must save its own result and return an inspectable image UUID. To return to the checkpoint, start another operation from the checkpoint UUID.
## Environment values
Values passed through `env` are available to the guest process and are represented in operation input metadata. SDK 0.3.6 exposes `preserve_env=True` for saving supported environment metadata together with `disposable=False`. Files attached to a run are also visible inside the guest. Do not put credentials in preserved environment metadata, uploaded files, or commands executed as untrusted code. Follow [Configure networking and secrets](/sandboxes/guides/configure-networking-and-secrets) for the supported controls.
## Continue
* [Branch, compare, and recover](/sandboxes/guides/branch-compare-and-recover)
* [Prepare and reuse environments](/sandboxes/guides/prepare-and-reuse-environments)
* [Python image reference](/sandboxes/sdk/python_sdk/reference/image)
* [REST image and inspection reference](/sandboxes/reference/index#images-and-files)
# Sessions and execution modes
Source: https://docs.tokenfactory.nebius.com/sandboxes/concepts/sessions-and-execution-modes
Distinguish client workflow state from operations and live processes.
A session helps a client remember workflow state. It does not keep a sandbox VM or process alive after an operation ends.
## What each object retains
| Object | Retains | Does not retain |
| - | - | - |
| CLI session | Selected image, working directory, staged files, branches, and local history | VM, process memory, running services, or open connections |
| Python SDK session | The current image reference and latest command result; saved runs update the reference | Compute or a separately addressable live process |
| REST application state | Whatever operation IDs and image UUIDs the application records | Any implicit session supplied by the Sandboxes API |
| MCP client conversation | Client and server tool context, subject to the MCP integration | A VM after its operation ends |
A new command from a saved image always creates new execution.
## Choose an execution mode
| Need | Mode | Result |
| - | - | - |
| Final output from one bounded command | Await Python `run()`, call sync `run().wait()`, use `contree run`, or submit and poll REST | One operation and a terminal process result |
| Launch work and observe it later | REST submit; CLI `contree run -d` followed by `contree op wait OPERATION_ID`; MCP `run(wait=false)` | Operation ID for later status inspection |
| Progressive output with reconnection | REST SSE | Output and lifecycle events plus `Last-Event-Id` resumption |
| Send stdin or a signal to a separately addressed process in active work | REST additional-subprocess endpoints | Subprocess ID inside a parent operation |
| Familiar synchronous subprocess syntax | SDK 0.3.6 `popen()` wrapper | A local wrapper around one remote image execution |
The SDK `popen()` wrapper is not the REST additional-subprocess API. It does not attach a new child to an already-running operation.
## Python run patterns
Complete [Set up access](/sandboxes/start/set-up-access) and install `contree-sdk==0.3.6` as shown in the [Python quickstart](/sandboxes/start/python-quickstart). Each example runs `/bin/echo` so the execution mode is easy to compare. Use an image tag available in your project.
Place the async fragment inside the quickstart’s async `main()`, with its authenticated `client`. The synchronous examples can run as ordinary Python scripts.
Async SDK 0.3.6 prepares the request first and submits it when awaited:
```python theme={null}
image = await client.images.use("alpine:3.19", strict=True)
prepared = image.run(command="/bin/echo", args=["hello"], disposable=True)
result = await prepared
if result.exit_code != 0:
raise RuntimeError(f"Command failed: {result.stderr}")
print(result.stdout, end="")
```
The synchronous client uses `wait()`:
```python theme={null}
from contree_sdk import ContreeSync
client = ContreeSync()
image = client.images.use("alpine:3.19", strict=True)
result = image.run(command="/bin/echo", args=["hello"], disposable=True).wait()
if result.exit_code != 0:
raise RuntimeError(f"Command failed: {result.stderr}")
print(result.stdout, end="")
```
The synchronous subprocess-style wrapper supports the familiar `popen()` and `wait()` sequence in SDK 0.3.6:
```python theme={null}
from contree_sdk import ContreeSync
client = ContreeSync()
image = client.images.use("alpine:3.19", strict=True)
process = image.popen(["/bin/echo", "hello"], text=True)
process.wait()
if process.returncode != 0:
raise RuntimeError(f"Command failed: {process.stderr}")
print(process.stdout, end="")
```
Each example prints:
```text theme={null}
hello
```
Set persistence explicitly in any `run()` call whose state matters. The SDK 0.3.6 session signature also defaults to `disposable=True`; session naming does not change that choice.
## Live processes
An additional subprocess can run only while its parent operation is active. It shares the parent VM, filesystem, resource budget, and lifetime. Use the REST endpoints to:
1. wait for an explicit parent readiness signal;
2. spawn the additional process and record its subprocess ID;
3. observe its output or send ordered stdin;
4. close stdin deliberately or send a signal; and
5. inspect both child and parent results.
A completed child does not create its own checkpoint. See [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input) for the bounded workflow.
## Continue
* [Choose an interface](/sandboxes/start/choose-an-interface)
* [Execution lifecycle](/sandboxes/concepts/execution-lifecycle)
* [Stream output and events](/sandboxes/guides/stream-output-and-events)
* [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input)
* [CLI sessions](/sandboxes/cli/tutorial/sessions)
* [Python session reference](/sandboxes/sdk/python_sdk/reference/session)
# Build and refresh a reusable custom environment
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/build-reusable-custom-environment
Build the supported Dockerfile subset, resolve the immutable UUID, run twice, and refresh after a source change.
`contree build` in CLI 0.9.4 interprets a documented Dockerfile subset on the client and produces Sandboxes image checkpoints. It is distinct from importing an already-built OCI image and is not a general Docker build service.
## Prerequisites and files
Complete [Set up access](/sandboxes/start/set-up-access), install `jq`, and run `uv tool install "contree-cli==0.9.4"`. Create `Dockerfile`:
```dockerfile theme={null}
FROM python:3.12-alpine
ARG MESSAGE=version-1
ENV APP_MESSAGE=${MESSAGE}
WORKDIR /app
COPY verify.py /app/verify.py
RUN python /app/verify.py
```
Create `verify.py` beside it:
```python theme={null}
import os
from pathlib import Path
assert os.environ["APP_MESSAGE"].startswith("version-")
Path("/app/version.txt").write_text(os.environ["APP_MESSAGE"] + "\n")
print(os.environ["APP_MESSAGE"])
```
Run both Bash blocks below in the same shell and the directory containing `Dockerfile` and `verify.py`; the second block reuses `CONTREE_SESSION`, `tag`, and `first_uuid` from the first. Build, resolve the tag to an immutable UUID, and perform two independent read-only runs:
```bash theme={null}
set -eu
export CONTREE_SESSION="docs-custom-env-$$"
tag="docs/custom-env-$CONTREE_SESSION:current"
contree build . --tag "$tag"
contree use "tag:$tag" >/dev/null
first_uuid=$(contree -o json use | jq -er .current_image)
test -n "$first_uuid"
first_read=$(contree run -D -- cat /app/version.txt)
second_read=$(contree run -D -- cat /app/version.txt)
test "$first_read" = version-1
test "$second_read" = version-1
current_uuid=$(contree -o json use | jq -er .current_image)
test "$current_uuid" = "$first_uuid"
printf 'First image: %s\n' "$first_uuid"
printf 'First read: %s\nSecond read: %s\n' "$first_read" "$second_read"
```
Both reads should find `version-1`. They leave the session on the first image because `-D` discards each run's changes. The checks verify that the session still refers to the recorded UUID and print labelled read results.
Rebuild with a new value:
```bash theme={null}
contree build . --build-arg MESSAGE=version-2 --tag "$tag"
contree use "tag:$tag" >/dev/null
second_uuid=$(contree -o json use | jq -er .current_image)
test -n "$second_uuid"
test "$second_uuid" != "$first_uuid"
refreshed_read=$(contree run -D -- cat /app/version.txt)
test "$refreshed_read" = version-2
current_uuid=$(contree -o json use | jq -er .current_image)
test "$current_uuid" = "$second_uuid"
printf 'Refreshed image: %s\n' "$second_uuid"
printf 'Refreshed read: %s\n' "$refreshed_read"
```
The new build resolves to a different UUID. The checks verify that the file contains `version-2` and that the disposable read leaves the session on the refreshed image. A tag can move, so evaluations should use the recorded UUID rather than the example tag.
The labelled reads should show:
```text theme={null}
First read: version-1
Second read: version-1
Refreshed read: version-2
```
The output also includes the two distinct image UUIDs.
The supported CLI subset includes `FROM`, `RUN`, `COPY`/`ADD`, `WORKDIR`, `ENV`, `ARG`, and `USER`; multi-stage `AS` is parsed but not executed. Each `RUN` creates a retained layer, and the client cache can reuse layers. Use `--no-cache` when a refresh must ignore that cache. A failed build should be retried from its declared inputs after correcting the failing directive; do not use the tag for downstream work until the rebuild passes. Checkpoint layers remain subject to image retention.
The verification reads the file created by the Dockerfile `RUN`. CLI 0.9.4 applies Dockerfile `ENV` while interpreting build steps, but this workflow does not rely on that value being inherited by later operations.
Registry imports instead use `images.import_from()` or `images.oci()` and capture a filesystem root. OCI runtime configuration does not define a later Sandboxes command.
The example leaves a named local CLI session, a movable remote tag, and its retained build images. Use a different unique name for another run. Remove local session bookkeeping with the documented CLI session command when it is no longer needed. Removing a tag can make its image eligible for deletion under the [retention policy](/sandboxes/operate/limits-retention-and-usage). Contact [support](/sandboxes/operate/troubleshooting#support-bundle) if you need to delete retained images.
See [Prepare and reuse environments](/sandboxes/guides/prepare-and-reuse-environments) and the [CLI Dockerfile tutorial](/sandboxes/cli/tutorial/build).
# Generate and download a binary artifact
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/generate-and-download-binary-artifact
Produce a deterministic binary file, retain it, download it, and verify exact bytes locally.
Captured stdout is intended for process output and is capped. Store a binary deliverable in the filesystem, retain the result image, then download and verify it as bytes.
## Prerequisites and complete source
Complete [Set up access](/sandboxes/start/set-up-access). In a fresh project, run `uv init --python 3.12` and `uv add "contree-sdk==0.3.6"`. Save as `binary_artifact.py`:
```python theme={null}
import asyncio
import gzip
import hashlib
from pathlib import Path
from contree_sdk import Contree
PAYLOAD = b"untrusted input\x00\x01\xff\n"
GENERATE_ARTIFACT = r"""
import gzip
import hashlib
from pathlib import Path
output_directory = Path("/out")
output_directory.mkdir(parents=True, exist_ok=True)
input_bytes = Path("/input.bin").read_bytes()
compressed_bytes = gzip.compress(input_bytes, mtime=0)
(output_directory / "result.bin").write_bytes(compressed_bytes)
digest = hashlib.sha256(compressed_bytes).hexdigest()
(output_directory / "result.sha256").write_text(digest + "\n")
"""
async def main() -> None:
client = Contree()
base = await client.images.oci("docker.io/library/python:3.12-alpine")
run = await base.run(
shell="python /generate_artifact.py",
files={
"/input.bin": PAYLOAD,
"/generate_artifact.py": GENERATE_ARTIFACT.encode(),
},
disposable=False,
timeout=30,
)
if run.exit_code != 0 or run.uuid is None:
raise RuntimeError('Artifact generation failed or returned no saved image')
print(f"Artifact saved in image {run.uuid}; downloading")
destination = Path("downloaded-result.bin")
await run.download("/out/result.bin", destination)
remote_digest = (await run.read("/out/result.sha256")).decode().strip()
actual = destination.read_bytes()
if actual[:8] != b"\x1f\x8b\x08\x00\x00\x00\x00\x00":
raise RuntimeError('Downloaded file has an unexpected gzip header')
if gzip.decompress(actual) != PAYLOAD:
raise RuntimeError('Downloaded artifact does not contain the original input')
digest = hashlib.sha256(actual).hexdigest()
if digest != remote_digest:
raise RuntimeError('Downloaded bytes do not match the remote SHA-256 digest')
print(f"Downloaded {destination}: {len(actual)} bytes; contents and digest match")
print(f"image={run.uuid} bytes={len(actual)} sha256={digest}")
asyncio.run(main())
```
Run `uv run python binary_artifact.py`. The input bytes are injected into the operation, transformed into a deterministic gzip artifact, downloaded, and checked for its gzip header, decompressed content, and SHA-256 digest. The digest checks that the downloaded bytes match the remote file; decompression checks that the file contains the expected input.
The retained result is required because inspection and download happen after execution. A disposable run returns no image to inspect. If generation exits nonzero or the image UUID is absent, do not download from the input image. If download fails after execution, retry the read by the recorded image UUID rather than rerunning untrusted code. The local file remains until removed by the user; the remote image follows image retention. For large inputs or artifacts, confirm the applicable size limits with [support](/sandboxes/operate/troubleshooting#support-bundle) before running the workload.
See [Work with files and artifacts](/sandboxes/guides/work-with-files-and-artifacts).
# Sandboxes cookbook
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/index
Complete Sandboxes workflows with explicit state, expected outcomes, and failure handling.
Build on the [main Sandboxes jobs](/sandboxes/overview#when-to-use-sandboxes): agent execution, testing and evaluation, and data processing. The recipes below cover individual steps you can combine into those workflows. Each includes setup instructions, a complete program, expected output, and guidance for handling failures and saved state.
## Prepare and reuse
> [card] [Prepare once, reuse safely](/sandboxes/cookbook/prepare-once-reuse-safely)
>
> **Python SDK** · Read the same prepared input in two independent runs.
> [card] [Build and refresh a custom environment](/sandboxes/cookbook/build-reusable-custom-environment)
>
> **CLI** · Build an image, reuse it, and rebuild after a change.
## Run and observe
> [card] [Stream a build or test run](/sandboxes/cookbook/stream-a-build-or-test-run)
>
> **REST SSE** · Watch test output, reconnect, and check the result.
> [card] [Interact with a process](/sandboxes/cookbook/interact-with-a-process)
>
> **REST** · Send two lines to a child and collect its response.
> [card] [Generate and download a binary artifact](/sandboxes/cookbook/generate-and-download-binary-artifact)
>
> **Python SDK** · Download a gzip file and check its contents and digest.
## Test and recover
> [card] [Try two coding fixes](/sandboxes/cookbook/try-two-coding-fixes)
>
> **Python SDK** · Compare two patches and continue from the passing one.
> [card] [Verify with networking disabled](/sandboxes/cookbook/verify-with-networking-disabled)
>
> **REST** · Read prepared input in an operation with networking disabled.
> [card] [Run a bounded evaluation batch](/sandboxes/cookbook/run-bounded-evaluation-batch)
>
> **REST with Python** · Separate passing tests, failing tests, and cancelled work.
> [card] [Recover from a known-good image](/sandboxes/cookbook/recover-from-known-good-image)
>
> **Python SDK** · Correct a failed check and retry from the saved image.
## Framework integration status
> [!WARNING]
>
> The [Mini-SWE-Agent adapter](/sandboxes/sdk/integrations/mini-swe-agent) currently has an SDK compatibility issue: `ContreeEnvironment` uses removed configuration imports and an incompatible client interface. Its example stops with `RuntimeError`.
Use the recipes above to implement execution, file transfer, and state reuse directly. Before adopting the Mini-SWE-Agent adapter, check its integration page for a compatible adapter and SDK version pair.
Start with [Set up access](/sandboxes/start/set-up-access), then read [Execution lifecycle](/sandboxes/concepts/execution-lifecycle) for the shared state model.
# Interact with a process during an operation
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/interact-with-a-process
Spawn a child in an active operation, send two inputs and EOF, test signals and parent finalization, and clean up on failure.
Send input to a process while its operation is running, then collect its output. The main example uses a child that reads two lines and writes a completion file for the parent. Two further cases show how signalling and parent shutdown affect the child:
1. A child receives two ordered stdin writes and EOF, returns the expected output, and lets the parent finish.
2. A child receives `SIGTERM` while its parent continues to a successful exit.
3. A parent finishes before its child, so operation finalization ends the child.
Every parent is disposable. A `finally` block cancels any operation that the program still owns if a result check, network request, or deadline fails.
## Prerequisites
Complete [Set up access](/sandboxes/start/set-up-access). The program requires Python 3.11 or later and uses only the standard library. Export the REST values:
```bash theme={null}
export CONTREE_BASE_URL="https://api.tokenfactory.nebius.com/sandboxes"
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_PROJECT_ID="YOUR_PROJECT_ID"
export IMAGE_UUID="YOUR_IMMUTABLE_IMAGE_UUID"
```
The image must contain a POSIX shell and the ordinary `sleep`, `touch`, and `test` commands. The client credential stays in the local process and is not passed to either sandbox process.
## Follow the interaction
Start with `normal_interaction()`. The parent prints `parent-ready` and waits for `/tmp/child-complete`, for at most 20 iterations with a one-second sleep. After observing readiness, the client starts a child, sends `first line` and `second line`, and closes stdin on the second write.
The child returns `received:first line|second line` and creates the completion file. The client prints that received text. The client checks the child's result and then the parent's result. Both should finish successfully. The [process sequence diagram](/sandboxes/guides/run-subprocesses-and-send-input#keep-the-parent-alive-until-the-work-is-done) shows this coordination.
To adapt the example, replace `READ_TWO_LINES` and the input messages in `normal_interaction()`. Keep a bounded readiness and completion condition for the parent. `child_signal()` and `parent_finishes_first()` demonstrate the two shutdown cases separately.
The signal case holds the parent open until the client verifies the signalled child and releases the parent. The parent-first case waits for the child to create a readiness file, then releases the parent while that child is still sleeping. Both use bounded conditions instead of a fixed delay before parent exit.
Representative output follows; process IDs, operation UUIDs, and the parent-finalization signal can vary:
```text theme={null}
--- two writes and EOF ---
received:first line|second line
child= exit=0; parent=SUCCESS
--- signal child; parent continues ---
child= signal=15; parent=SUCCESS
--- parent finishes first ---
parent=SUCCESS; child exit=-1 signal=
Completed input, signal, and parent-shutdown examples.
```
## Run the complete example
Save this as `interact.py` and run `python3 interact.py`. Use `--deadline` to change the default 120-second deadline for the full program.
> [accordion] Complete program
>
> ```python theme={null}
> #!/usr/bin/env python3
> import argparse
> import base64
> import json
> import os
> import time
> import urllib.error
> import urllib.parse
> import urllib.request
>
>
> def main():
> parser = argparse.ArgumentParser()
> parser.add_argument("--deadline", type=float, default=120.0)
> args = parser.parse_args()
> client = Client(args.deadline)
> try:
> normal_interaction(client)
> child_signal(client)
> parent_finishes_first(client)
> print("Completed input, signal, and parent-shutdown examples.")
> finally:
> client.cancel_owned()
>
>
> def normal_interaction(client):
> print("\n--- two writes and EOF ---")
> parent = client.create_parent(WAIT_FOR_CHILD)
> client.wait_ready(parent)
> child = client.spawn_child(
> parent,
> {
> "command": READ_TWO_LINES,
> "shell": True,
> "stdin": {"value": "", "encoding": "ascii", "close": False},
> "truncate_output_at": 1048576,
> },
> )
> client.write_stdin(parent, child, "first line\n", close=False)
> client.write_stdin(parent, child, "second line\n", close=True)
> child_result = client.wait_child(parent, child)
> child_state = child_result["state"]
> if child_state["exit_code"] != 0 or child_state["signal"] != -1:
> raise RuntimeError('Child did not exit successfully')
> received = decode_stream(child_result["stdout"])
> if received != "received:first line|second line\n":
> raise RuntimeError('Child did not return both input lines in order')
> if decode_stream(child_result["stderr"]) != "":
> raise RuntimeError('Child wrote unexpected stderr output')
> print(received, end="")
> parent_result = client.wait_parent(parent)
> assert_parent_success(parent_result)
> print(f"child={child} exit=0; parent={parent_result['status']}")
>
>
> def child_signal(client):
> print("\n--- signal child; parent continues ---")
> parent = client.create_parent(WAIT_FOR_RELEASE)
> client.wait_ready(parent)
> child = client.spawn_child(parent, {"command": "sleep 30", "shell": True})
> client.signal_child(parent, child)
> child_result = client.wait_child(parent, child)
> if child_result["state"]["signal"] != 15:
> raise RuntimeError('Child result did not report SIGTERM')
> if child_result["state"]["exit_code"] != -1:
> raise RuntimeError('Signalled child returned an unexpected exit code')
> release_parent(client, parent)
> parent_result = client.wait_parent(parent)
> assert_parent_success(parent_result)
> print(f"child={child} signal=15; parent={parent_result['status']}")
>
>
> def parent_finishes_first(client):
> print("\n--- parent finishes first ---")
> parent = client.create_parent(WAIT_FOR_RELEASE)
> client.wait_ready(parent)
> child = client.spawn_child(parent, {"command": LONG_LIVED_CHILD, "shell": True})
> release_parent(client, parent, wait_for_child=True)
> parent_result = client.wait_parent(parent)
> assert_parent_success(parent_result)
> child_result = client.wait_child(parent, child)
> child_state = child_result["state"]
> if child_state.get("exit_code") == 0 and child_state.get("signal") in (-1, None):
> raise RuntimeError("Child unexpectedly survived parent finalization")
> print(
> f"parent={parent_result['status']}; child exit={child_state.get('exit_code')} "
> f"signal={child_state.get('signal')}"
> )
>
>
> def release_parent(client, parent, wait_for_child=False):
> command = RELEASE_AFTER_CHILD_STARTS if wait_for_child else RELEASE_PARENT
> release = client.spawn_child(parent, {"command": command, "shell": True})
> result = client.wait_child(parent, release)
> state = result["state"]
> if state.get("exit_code") != 0 or state.get("signal") not in (-1, None):
> raise RuntimeError(f"Could not release the parent: {state}")
>
>
> # Each parent waits for a file condition with a bounded remote lifetime.
> WAIT_FOR_CHILD = r"""
> printf 'parent-ready\n'
> i=0
> while [ ! -f /tmp/child-complete ] && [ "$i" -lt 20 ]; do
> i=$((i + 1))
> sleep 1
> done
> test -f /tmp/child-complete
> """
>
> READ_TWO_LINES = r"""
> read first
> read second
> printf 'received:%s|%s\n' "$first" "$second"
> touch /tmp/child-complete
> """
>
> WAIT_FOR_RELEASE = r"""
> printf 'parent-ready\n'
> i=0
> while [ ! -f /tmp/parent-release ] && [ "$i" -lt 20 ]; do
> i=$((i + 1))
> sleep 1
> done
> test -f /tmp/parent-release
> """
>
> LONG_LIVED_CHILD = r"""
> touch /tmp/child-started
> sleep 30
> """
>
> RELEASE_PARENT = "touch /tmp/parent-release"
>
> RELEASE_AFTER_CHILD_STARTS = r"""
> i=0
> while [ ! -f /tmp/child-started ] && [ "$i" -lt 10 ]; do
> i=$((i + 1))
> sleep 1
> done
> test -f /tmp/child-started || exit 1
> touch /tmp/parent-release
> """
>
>
> TERMINAL = {"SUCCESS", "FAILED", "CANCELLED"}
>
>
> def required(name):
> value = os.environ.get(name)
> if not value:
> raise SystemExit(f"Set {name}; see https://docs.tokenfactory.nebius.com/sandboxes/start/set-up-access")
> return value
>
>
> def retry_delay(headers):
> try:
> return max(0.1, float(headers.get("Retry-After", "1")))
> except ValueError:
> return 1.0
>
>
> def decode_stream(stream):
> value = (stream or {}).get("value", "")
> encoding = (stream or {}).get("encoding", "ascii")
> if encoding == "base64":
> return base64.b64decode(value).decode("utf-8", errors="replace")
> if encoding == "ascii":
> return value
> raise RuntimeError(f"Unsupported stream encoding: {encoding}")
>
>
> class Client:
> def __init__(self, deadline_seconds):
> self.base = os.environ.get(
> "CONTREE_BASE_URL", "https://api.tokenfactory.nebius.com/sandboxes"
> ).rstrip("/")
> self.token = required("NEBIUS_API_KEY")
> self.project = required("NEBIUS_PROJECT_ID")
> self.image = required("IMAGE_UUID")
> self.deadline = time.monotonic() + deadline_seconds
> self.owned = set()
>
> def remaining(self):
> value = self.deadline - time.monotonic()
> if value <= 0:
> raise TimeoutError("Recipe deadline exceeded")
> return min(15.0, value)
>
> def request(self, method, path, body=None, allowed=()):
> headers = {
> "Authorization": f"Bearer {self.token}",
> "Project": self.project,
> "Accept": "application/json",
> }
> data = None
> if body is not None:
> data = json.dumps(body).encode()
> headers["Content-Type"] = "application/json"
> request = urllib.request.Request(
> self.base + "/v1" + path, data=data, headers=headers, method=method
> )
> try:
> with urllib.request.urlopen(request, timeout=self.remaining()) as response:
> payload = response.read()
> decoded = json.loads(payload) if payload else None
> return response.status, response.headers, decoded
> except urllib.error.HTTPError as error:
> payload = error.read()
> decoded = json.loads(payload) if payload else None
> if error.code in allowed:
> return error.code, error.headers, decoded
> raise RuntimeError(f"HTTP {error.code} for {method} {path}: {decoded}") from error
>
> def create_parent(self, command):
> status, _, result = self.request(
> "POST",
> "/instances",
> {
> "image": self.image,
> "command": command,
> "shell": True,
> "disposable": True,
> "timeout": 30,
> "truncate_output_at": 1048576,
> },
> )
> if status != 201:
> raise RuntimeError(f"Expected parent create status 201, got {status}")
> operation_id = result["uuid"]
> self.owned.add(operation_id)
> return operation_id
>
> def operation(self, operation_id, inflight=False):
> suffix = "?inflight=1" if inflight else ""
> return self.request("GET", f"/operations/{operation_id}{suffix}")
>
> def wait_ready(self, operation_id, marker="parent-ready"):
> while True:
> _, headers, result = self.operation(operation_id, inflight=True)
> status = result["status"]
> process = (result.get("metadata") or {}).get("result") or {}
> if status in {"ASSIGNED", "EXECUTING"} and marker in decode_stream(
> process.get("stdout")
> ):
> return
> if status in TERMINAL:
> raise RuntimeError(f"Parent ended before readiness: {result}")
> time.sleep(min(retry_delay(headers), self.remaining()))
>
> def wait_parent(self, operation_id):
> while True:
> _, headers, result = self.operation(operation_id)
> if result["status"] in TERMINAL:
> self.owned.discard(operation_id)
> return result
> time.sleep(min(retry_delay(headers), self.remaining()))
>
> def spawn_child(self, operation_id, body):
> path = f"/operations/{operation_id}/subprocesses"
> while True:
> status, headers, result = self.request("POST", path, body, allowed=(425, 504))
> if status == 201:
> return result["spid"]
> if status == 425:
> time.sleep(min(retry_delay(headers), self.remaining()))
> continue
> raise RuntimeError(
> "Child spawn timed out with uncertain outcome; inspect the event stream before retrying"
> )
>
> def write_stdin(self, operation_id, spid, value, close):
> status, _, _ = self.request(
> "POST",
> f"/operations/{operation_id}/subprocesses/{spid}/stdin",
> {"value": value, "encoding": "ascii", "close": close},
> allowed=(504,),
> )
> if status == 504:
> raise RuntimeError("Stdin delivery is uncertain; do not retry this chunk blindly")
> if status != 204:
> raise RuntimeError(f"Expected stdin status 204, got {status}")
>
> def signal_child(self, operation_id, spid, signal="SIGTERM"):
> query = urllib.parse.urlencode({"signal": signal})
> status, _, _ = self.request(
> "DELETE", f"/operations/{operation_id}/subprocesses/{spid}?{query}"
> )
> if status != 204:
> raise RuntimeError(f"Expected signal status 204, got {status}")
>
> def wait_child(self, operation_id, spid):
> path = f"/operations/{operation_id}/subprocesses/{spid}"
> while True:
> status, headers, result = self.request("GET", path, allowed=(425,))
> if status == 200:
> return result
> time.sleep(min(retry_delay(headers), self.remaining()))
>
> def cancel_owned(self):
> self.deadline = max(self.deadline, time.monotonic() + 15.0)
> for operation_id in list(self.owned):
> try:
> _, _, current = self.operation(operation_id)
> if current["status"] not in TERMINAL:
> self.request("DELETE", f"/operations/{operation_id}")
> self.wait_parent(operation_id)
> except Exception as error:
> print(f"Cleanup failed for {operation_id}: {error}")
>
>
> def assert_parent_success(result):
> process = (result.get("metadata") or {}).get("result") or {}
> state = process.get("state") or {}
> if result.get("status") != "SUCCESS" or state.get("exit_code") != 0:
> raise RuntimeError(f"Parent did not finish successfully: {result}")
> if state.get("signal") not in (-1, None) or state.get("timed_out"):
> raise RuntimeError(f"Parent was interrupted: {state}")
>
>
>
>
> if __name__ == "__main__":
> main()
> ```
The normal case prints a child exit of `0` and parent status `SUCCESS`. The signal case checks child signal `15` and exit code `-1`, then checks that the parent still reaches `SUCCESS`. The parent-first case requires a successful parent result and a terminal child result that shows interruption.
The program keeps create, readiness, child-result, and parent-result polling within one deadline. It honors `Retry-After` for documented `425` responses. It does not retry a `504` child create or stdin write because either request may already have taken effect.
See [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input) for the lifecycle and retry rules. Exact fields and errors remain in the [spawn](/api-reference/sandboxes/operation/spawn-an-additional-subprocess-inside-a-running-instance), [stdin](/api-reference/sandboxes/operation/write-to-a-subprocesss-stdin-andor-close-it), [signal](/api-reference/sandboxes/operation/kill-one-subprocess), and [operation status](/api-reference/sandboxes/operations/get-an-operation-status) references.
# Prepare once, reuse safely
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/prepare-once-reuse-safely
Save one prepared filesystem image and reuse it in independent later operations.
Use one retained setup operation when several tasks need the same dependencies or fixtures. Each task starts on new compute from the saved filesystem image; processes, memory, services, and connections from setup are gone.
## Prerequisites
* Complete [Set up access](/sandboxes/start/set-up-access).
* In a fresh project, run `uv init --python 3.12` and `uv add "contree-sdk==0.3.6"`.
* Use an immutable image UUID already in the project, or allow the example to import `docker.io/library/alpine:3.19`.
## Complete source
Save as `reuse.py`:
```python theme={null}
import asyncio
from uuid import UUID
from contree_sdk import Contree
def require_success(run, label: str) -> None:
if run.exit_code != 0:
raise RuntimeError(f"{label} failed: {run.stderr}")
async def main() -> None:
client = Contree()
base = await client.images.oci("docker.io/library/alpine:3.19")
if not isinstance(base.uuid, UUID):
raise RuntimeError('Image import did not return a UUID')
prepared = await base.run(
shell="mkdir -p /workspace && printf 'prepared-v1\\n' > /workspace/prepared.txt",
disposable=False,
timeout=60,
)
require_success(prepared, "prepare")
if prepared.uuid is None:
raise RuntimeError("Preparation returned no reusable image")
checkpoint_uuid = prepared.uuid
checkpoint = await client.images.use(checkpoint_uuid, strict=True)
first, second = await asyncio.gather(
checkpoint.run(
shell="test \"$(cat /workspace/prepared.txt)\" = prepared-v1 && printf 'A\\n'",
disposable=True,
timeout=30,
),
checkpoint.run(
shell="test \"$(cat /workspace/prepared.txt)\" = prepared-v1 && printf 'B\\n'",
disposable=True,
timeout=30,
),
)
require_success(first, "task A")
require_success(second, "task B")
if first.stdout != "A\n":
raise RuntimeError('Task A did not return its expected output')
if second.stdout != "B\n":
raise RuntimeError('Task B did not return its expected output')
if first.uuid is not None or second.uuid is not None:
raise RuntimeError('Disposable tasks unexpectedly returned saved images')
print(checkpoint_uuid)
print(first.stdout + second.stdout, end="")
if __name__ == "__main__":
asyncio.run(main())
```
Run `uv run python reuse.py`. The output ends with `A` and `B`. The first line is the immutable checkpoint UUID to record with the setup revision.
## State, failure, and retention
The setup explicitly uses `disposable=False`; its UUID is the branch source. Both readers explicitly use `disposable=True`, so they return output but no reusable image. SDK 0.3.6 represents that outcome with `uuid is None`; attempting another run from that result raises `DisposableImageRunError` locally.
If either reader fails, inspect its stdout, stderr, exit code, and `first.result.truncated` or `second.result.truncated`, then rerun only that task from `checkpoint_uuid`. An SDK wait timeout triggers a best-effort cancellation; do not resubmit until the operation outcome is known. Checkpoint images are retained for 180 days; after that, untagged and unreferenced images may be deleted. See [Limits, retention, and usage](/sandboxes/operate/limits-retention-and-usage) before choosing a long-term storage strategy.
## References
* [Python SDK image reference](/sandboxes/sdk/python_sdk/reference/image)
* [Python branching guide](/sandboxes/sdk/python_sdk/branching)
* [Limits, retention, and usage](/sandboxes/operate/limits-retention-and-usage)
# Recover from a known-good image
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/recover-from-known-good-image
Diagnose a deliberate command failure and retry corrected work from the recorded checkpoint.
Recovery begins from an immutable checkpoint whose contents were already verified. This avoids assuming that a failed, cancelled, or timed-out operation produced reusable state.
## Prerequisites and complete source
Complete [Set up access](/sandboxes/start/set-up-access). In a fresh project, run `uv init --python 3.12` and `uv add "contree-sdk==0.3.6"`. Save as `recover.py`:
```python theme={null}
import asyncio
from contree_sdk import Contree
async def main() -> None:
client = Contree()
base = await client.images.oci("docker.io/library/alpine:3.19")
checkpoint = await base.run(
shell="mkdir -p /work && printf 'known-good\\n' > /work/state.txt",
disposable=False, timeout=30,
)
if checkpoint.exit_code != 0 or checkpoint.uuid is None:
raise RuntimeError('Preparation failed or returned no saved checkpoint')
known_good_uuid = checkpoint.uuid
print(f"Saved known-good checkpoint: {known_good_uuid}")
known_good = await client.images.use(known_good_uuid, strict=True)
failed = await known_good.run(
shell="test \"$(cat /work/state.txt)\" = wrong-value",
disposable=True, timeout=30,
)
if failed.exit_code == 0:
raise RuntimeError('The intentionally wrong check unexpectedly passed')
print(f"deliberate failure exit={failed.exit_code} stderr={failed.stderr!r}")
retry_base = await client.images.use(known_good_uuid, strict=True)
recovered = await retry_base.run(
shell="test \"$(cat /work/state.txt)\" = known-good && printf 'recovered\\n'",
disposable=True, timeout=30,
)
if recovered.exit_code != 0 or recovered.stdout != "recovered\n":
raise RuntimeError('Retry did not produce the expected recovered output')
print(f"checkpoint={known_good_uuid} recovered")
asyncio.run(main())
```
Run `uv run python recover.py`. You should see the intentional command failure, followed by `recovered` from the same known-good image.
Both attempts are disposable because they only check the saved file and print a result. Record stdout, stderr, exit code, truncation, and the operation ID when using REST. A nonzero exit is a workload result; an SDK exception can represent a platform failure, cancellation, or wait timeout. SDK 0.3.6 makes a best-effort cancellation when its wait times out. After uncertain transport or cancellation, inspect the existing operation before retrying. For files from a failed run, follow the [result-image rules](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image).
See [Troubleshooting](/sandboxes/operate/troubleshooting).
# Run a bounded evaluation batch
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/run-bounded-evaluation-batch
Correlate item, operation, and image IDs; classify outcomes; and cancel only work owned by the batch.
This REST example prepares one retained evaluation fixture, then runs two deterministic cases and one deliberately slow case from that image. It records application item IDs, operation IDs, input image UUIDs, and result image UUIDs, then cancels only the slow operation owned by this batch.
## Prerequisites
Complete [Set up access](/sandboxes/start/set-up-access). In a fresh project, run `uv init --python 3.12` followed by `uv add "httpx==0.28.1"`. Export `NEBIUS_API_KEY`, `NEBIUS_PROJECT_ID`, and `IMAGE_UUID`; the script supplies the public API URL by default. Use an Alpine 3.19 image UUID, or an equivalent image with `/bin/sh`, `mkdir`, `cat`, `chmod`, `test`, `printf`, `sleep`, and `/etc/os-release`. The fixture relies on these commands and the OS release file.
## Read the outcomes
The three cases start from the same prepared image. The `pass` case checks a file that exists. `test-fail` checks a missing file. `slow-cancel` waits in a loop until the client cancels it after collecting the other results. A 120-second execution timeout bounds the guest process if cancellation cannot be confirmed.
The final records should report `passed`, `test-failure`, and `cancelled`, each with its own operation ID. A command failure stays separate from a platform failure so it does not count as an infrastructure error in your evaluation results.
This example caps work by submitting exactly three cases. The HTTP connection limit controls client connections, not the number of remote operations. For a larger dataset, hold a semaphore or worker slot from submission until each operation reaches a terminal state; see [Run concurrent workloads](/sandboxes/guides/run-concurrent-workloads).
## Run the complete example
Save as `bounded_eval.py`:
> [accordion] Complete program
>
> ```python theme={null}
> import asyncio
> import base64
> import os
> import time
> from dataclasses import dataclass
>
> import httpx
>
> BASE = os.environ.get(
> "CONTREE_BASE_URL", "https://api.tokenfactory.nebius.com/sandboxes"
> ).rstrip("/")
> HEADERS = {
> "Authorization": f"Bearer {os.environ['NEBIUS_API_KEY']}",
> "Project": os.environ["NEBIUS_PROJECT_ID"],
> }
> BASE_IMAGE = os.environ["IMAGE_UUID"]
> FIXTURES = {
> "pass": "/fixture/evaluate.sh pass",
> "test-fail": "/fixture/evaluate.sh fail",
> "slow-cancel": "/fixture/evaluate.sh slow",
> }
> TERMINAL = {"SUCCESS", "FAILED", "CANCELLED"}
>
>
> @dataclass
> class Record:
> item_id: str
> input_image_id: str
> operation_id: str | None = None
> result_image_id: str | None = None
> outcome: str | None = None
> evidence: str = ""
>
>
> async def main():
> deadline = time.monotonic() + 90
> limits = httpx.Limits(max_connections=3)
> async with httpx.AsyncClient(timeout=20, limits=limits) as http:
> preparation = await http.post(
> f"{BASE}/v1/instances",
> headers=HEADERS,
> json={
> "image": BASE_IMAGE,
> "command": PREPARE_FIXTURE,
> "shell": True,
> "disposable": False,
> "timeout": 30,
> "truncate_output_at": 1048576,
> },
> )
> preparation.raise_for_status()
> preparation_id = preparation.json()["uuid"]
> print(f"accepted preparation={preparation_id} input_image={BASE_IMAGE}")
> prepared = await wait_operation(http, preparation_id, deadline)
> if prepared["status"] != "SUCCESS":
> raise RuntimeError('Preparation operation did not complete successfully')
> if prepared["metadata"]["result"]["state"]["exit_code"] != 0:
> raise RuntimeError('Preparation command failed')
> image = prepared["result_image_uuid"]
> if not image:
> raise RuntimeError('Preparation returned no saved fixture image')
>
> records = {item: Record(item, image) for item in FIXTURES}
> owned_operation_ids = set()
> try:
> for item, command in FIXTURES.items():
> response = await http.post(
> f"{BASE}/v1/instances",
> headers=HEADERS,
> json={
> "image": image,
> "command": command,
> "shell": True,
> "disposable": True,
> "timeout": 120,
> "truncate_output_at": 1048576,
> },
> )
> if response.status_code == 429:
> records[item].outcome = "rate-or-quota-rejection"
> continue
> if response.status_code == 503:
> records[item].outcome = "service-unavailable-rejection"
> continue
> response.raise_for_status()
> operation_id = response.json()["uuid"]
> records[item].operation_id = operation_id
> owned_operation_ids.add(operation_id)
> print(f"accepted item={item} operation={operation_id} image={image}")
>
> observed_items = [
> item for item in ("pass", "test-fail")
> if records[item].operation_id is not None
> ]
> completed = await asyncio.gather(
> *(
> wait_operation(http, records[item].operation_id, deadline)
> for item in observed_items
> )
> )
> for item, data in zip(observed_items, completed, strict=True):
> records[item].outcome = classify(data)
> records[item].result_image_id = data.get("result_image_uuid")
> result = (data.get("metadata") or {}).get("result")
> if result:
> records[item].evidence = (
> decoded(result.get("stdout") or {})
> + decoded(result.get("stderr") or {})
> )[:80].replace("\n", " ")
>
> slow = records["slow-cancel"]
> if slow.operation_id in owned_operation_ids:
> response = await http.delete(
> f"{BASE}/v1/operations/{slow.operation_id}",
> headers=HEADERS,
> )
> response.raise_for_status()
> slow_data = await wait_operation(http, slow.operation_id, deadline)
> slow.outcome = classify(slow_data)
> slow.result_image_id = slow_data.get("result_image_uuid")
> finally:
> for record in records.values():
> if record.operation_id in owned_operation_ids and record.outcome is None:
> try:
> response = await http.delete(
> f"{BASE}/v1/operations/{record.operation_id}",
> headers=HEADERS,
> )
> response.raise_for_status()
> data = await wait_operation(
> http,
> record.operation_id,
> time.monotonic() + 30,
> )
> record.outcome = classify(data)
> record.result_image_id = data.get("result_image_uuid")
> except (httpx.HTTPError, TimeoutError):
> record.outcome = "cleanup-uncertain"
>
> print("\nBatch summary:")
> for record in records.values():
> print(f" {record.item_id}: {record.outcome or 'unresolved'}")
> print(f" operation_id: {record.operation_id}")
> print(f" input_image_id: {record.input_image_id}")
> print(f" result_image_id: {record.result_image_id}")
> if record.evidence:
> print(f" evidence: {record.evidence.strip()}")
> if records["pass"].outcome != "passed":
> raise RuntimeError('Passing case did not complete as passed')
> if records["test-fail"].outcome != "test-failure":
> raise RuntimeError('Failing case did not report a test failure')
> if records["slow-cancel"].outcome != "cancelled":
> raise RuntimeError('Slow case was not cancelled')
> if any(record.result_image_id is not None for record in records.values()):
> raise RuntimeError('Disposable evaluation returned an unexpected saved image')
> if "case=pass" not in records["pass"].evidence:
> raise RuntimeError('Passing case output marker was missing')
> if "case=test-fail" not in records["test-fail"].evidence:
> raise RuntimeError('Failing case output marker was missing')
>
>
> async def wait_operation(http, operation_id, deadline):
> while time.monotonic() < deadline:
> response = await http.get(
> f"{BASE}/v1/operations/{operation_id}",
> headers=HEADERS,
> )
> response.raise_for_status()
> data = response.json()
> if data["status"] in TERMINAL:
> return data
> await asyncio.sleep(1)
> raise TimeoutError(operation_id)
>
>
> def classify(data):
> if data["status"] == "CANCELLED":
> return "cancelled"
> if data["status"] == "FAILED":
> return "platform-failure"
> state = data["metadata"]["result"]["state"]
> if state.get("timed_out"):
> return "execution-timeout"
> if state.get("signal", -1) > 0:
> return "process-signal"
> if state["exit_code"] != 0:
> return "test-failure"
> return "passed"
>
>
> def decoded(stream):
> value = stream.get("value", "")
> if stream.get("encoding") == "base64":
> return base64.b64decode(value).decode("utf-8", errors="replace")
> return value
>
>
> # This shell program runs inside the sandbox to prepare the retained image.
> PREPARE_FIXTURE = r"""
> set -e
> mkdir -p /fixture
> cat > /fixture/evaluate.sh <<'SH'
> #!/bin/sh
> case "$1" in
> pass)
> test -f /etc/os-release && printf 'case=pass\n'
> ;;
> fail)
> printf 'case=test-fail\n' >&2
> test -f /fixture/missing
> ;;
> slow)
> printf 'case=slow\n'
> while :; do sleep 1; done
> ;;
> *) exit 64 ;;
> esac
> SH
> chmod +x /fixture/evaluate.sh
> """
>
>
> asyncio.run(main())
> ```
Run `uv run python bounded_eval.py`. The program prints accepted IDs as it submits work, followed by a labelled summary with these outcomes (UUIDs vary):
```text theme={null}
Batch summary:
pass: passed
operation_id:
input_image_id:
result_image_id: None
evidence: case=pass
test-fail: test-failure
operation_id:
input_image_id:
result_image_id: None
evidence: case=test-fail
slow-cancel: cancelled
operation_id:
input_image_id:
result_image_id: None
```
The client collects the first two outcomes before requesting cancellation of `slow-cancel`. The slow fixture keeps waiting during that step, with its execution timeout as a fallback bound. Each disposable result has no result image. The retained fixture image UUID and fixture markers in stdout or stderr make each outcome inspectable.
The example bounds evaluation work to three accepted operations and all waits with deadlines. The public Beta maximum is 50 simultaneous operations; it is a ceiling, not a target. An accepted operation has `outcome=None` until a terminal result is observed. If cleanup cannot confirm that result, it reports `cleanup-uncertain`. Transport failure after acceptance is uncertain, so query a known ID before resubmitting. Cleanup sends `DELETE` only for IDs inserted into `owned_operation_ids` and observes terminal state; it never uses project-wide cancellation. The retained fixture follows the [image retention policy](/sandboxes/operate/limits-retention-and-usage). Recover cancelled work from a known-good image; contact support if cancellation billing or retention affects your workload.
See [Run concurrent workloads](/sandboxes/guides/run-concurrent-workloads).
# Stream a build or test run
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/stream-a-build-or-test-run
Run a deterministic test suite, display stdout and stderr over SSE, resume after disconnect, and verify both success and failure.
Show test progress in your application while a command is still running. This example uses a small shell test suite so you can see stdout, stderr, and a failing test without preparing a repository. It also disconnects and reconnects the event stream to show how to resume from a saved event ID.
## Prerequisites
Complete [Set up access](/sandboxes/start/set-up-access). The program requires Python 3.11 or later and uses only the standard library. Export the documented REST values:
```bash theme={null}
export CONTREE_BASE_URL="https://api.tokenfactory.nebius.com/sandboxes"
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_PROJECT_ID="YOUR_PROJECT_ID"
export IMAGE_UUID="YOUR_IMMUTABLE_IMAGE_UUID"
```
The selected image must contain a POSIX shell and the ordinary `test`, `grep`, and `sleep` commands. Keep the bearer credential in the client environment; the program does not send it to sandboxed code.
## Follow the workflow
1. `create_test_run()` starts the command and records its operation ID.
2. `consume_events()` displays each complete output event, then saves its ID. The first connection closes after five processed events, counting lifecycle events and output events. This count is chosen only to demonstrate reconnection.
3. The next subscription sends the saved ID in `Last-Event-Id`. It continues the same operation's output.
4. `final_result()` checks the operation and process outcome. A second run includes a failing test so you can see stderr and exit code `1`.
Representative output follows. Event IDs, UUIDs, and output chunk boundaries can vary:
```text theme={null}
--- success: operation ---
[event] spawn id=2
[stdout] PASS arithmetic
[stdout] PASS file-content
[client] disconnect after processed event
[client] resume after event
[stdout] SUMMARY passed=2 failed=0
[final] operation=SUCCESS process_exit=0
--- expected failure: operation ---
[stdout] PASS arithmetic
[stdout] PASS file-content
[stderr] FAIL deliberate-failure
[stdout] SUMMARY passed=2 failed=1
[final] operation=SUCCESS process_exit=1
```
For your own test suite, replace `TEST_SUITE` and adjust the expected output checks in `run_variant()`. Keep the cursor handling and final status check. See the [reconnection diagram](/sandboxes/guides/stream-output-and-events#commit-a-resumable-cursor) for the order of requests.
## Run the complete example
Save the following as `stream_tests.py` and run `python3 stream_tests.py`. The 120-second deadline covers both operations and can be changed with `--deadline`.
> [accordion] Complete program
>
> ```python theme={null}
> #!/usr/bin/env python3
> import argparse
> import base64
> import json
> import os
> import sys
> import time
> import urllib.error
> import urllib.request
>
>
> def main():
> parser = argparse.ArgumentParser()
> parser.add_argument("--deadline", type=float, default=120.0)
> args = parser.parse_args()
> client = Client(args.deadline)
> try:
> run_variant(client, expect_failure=False, disconnect=True)
> run_variant(client, expect_failure=True, disconnect=False)
> print("Observed the successful and nonzero test outcomes.")
> finally:
> client.cancel_owned()
>
>
> def run_variant(client, expect_failure, disconnect):
> label = "expected failure" if expect_failure else "success"
> operation_id = client.create_test_run(expect_failure)
> print(f"\n--- {label}: operation {operation_id} ---", flush=True)
> cursor = None
> if disconnect:
> cursor, _ = client.consume_events(operation_id, disconnect_after=5)
> print(f"[client] resume after event {cursor}", flush=True)
> _, completed = client.consume_events(operation_id, cursor=cursor)
> result = client.final_result(operation_id)
> process = verify_result(result, 1 if expect_failure else 0)
> stdout = decode_stream(process["stdout"])
> stderr = decode_stream(process["stderr"])
> if expect_failure:
> if "FAIL deliberate-failure" not in stderr:
> raise RuntimeError('Failing run did not report the expected test error')
> if "SUMMARY passed=2 failed=1" not in stdout:
> raise RuntimeError('Failing run returned an unexpected summary')
> else:
> if "SUMMARY passed=2 failed=0" not in stdout:
> raise RuntimeError('Successful run returned an unexpected summary')
> print(f"[final] operation={result['status']} process_exit={process['state']['exit_code']}")
> if not completed:
> print("[final] stream ended without a completion frame; final status supplied the outcome")
>
>
> # Replace this fixture suite with your build or test command.
> TEST_SUITE = r"""
> set -u
> passed=0
> failed=0
>
> check() {
> label=$1
> shift
> if "$@"; then
> printf 'PASS %s\n' "$label"
> passed=$((passed + 1))
> else
> printf 'FAIL %s\n' "$label" >&2
> failed=$((failed + 1))
> fi
> sleep 1
> }
>
> check arithmetic test $((2 + 2)) -eq 4
> printf 'alpha\n' > /tmp/fixture.txt
> check file-content grep -qx alpha /tmp/fixture.txt
> # OPTIONAL_FAILURE
> printf 'SUMMARY passed=%s failed=%s\n' "$passed" "$failed"
> test "$failed" -eq 0
> """
>
>
> def read_sse_frames(response, check_deadline):
> """Yield complete SSE frames; a partial frame never advances the cursor."""
> frame_lines = []
> while True:
> check_deadline()
> raw = response.readline()
> if not raw:
> return
> line = raw.decode("utf-8").rstrip("\r\n")
> if line:
> frame_lines.append(line)
> continue
> if not frame_lines:
> continue
> fields = {}
> for item in frame_lines:
> if item.startswith(":"):
> continue
> key, separator, value = item.partition(":")
> if separator:
> # SSE removes at most one space after the colon.
> if value.startswith(" "):
> value = value[1:]
> fields.setdefault(key, []).append(value)
> frame_lines = []
> yield fields
>
>
> TERMINAL = {"SUCCESS", "FAILED", "CANCELLED"}
>
>
> def required(name):
> value = os.environ.get(name)
> if not value:
> raise SystemExit(f"Set {name}; see https://docs.tokenfactory.nebius.com/sandboxes/start/set-up-access")
> return value
>
>
> def retry_delay(headers):
> try:
> return max(0.1, float(headers.get("Retry-After", "1")))
> except ValueError:
> return 1.0
>
>
> def decode_stream(stream):
> value = stream.get("value", "")
> encoding = stream.get("encoding", "ascii")
> if encoding == "base64":
> return base64.b64decode(value).decode("utf-8", errors="replace")
> if encoding == "ascii":
> return value
> raise RuntimeError(f"Unsupported output encoding: {encoding}")
>
>
> class Client:
> def __init__(self, deadline_seconds):
> self.base = os.environ.get(
> "CONTREE_BASE_URL", "https://api.tokenfactory.nebius.com/sandboxes"
> ).rstrip("/")
> self.token = required("NEBIUS_API_KEY")
> self.project = required("NEBIUS_PROJECT_ID")
> self.image = required("IMAGE_UUID")
> self.deadline = time.monotonic() + deadline_seconds
> self.owned = set()
>
> def remaining(self):
> value = self.deadline - time.monotonic()
> if value <= 0:
> raise TimeoutError("Recipe deadline exceeded")
> return min(15.0, value)
>
> def request(self, method, path, body=None, extra_headers=None):
> headers = {
> "Authorization": f"Bearer {self.token}",
> "Project": self.project,
> "Accept": "application/json",
> }
> data = None
> if body is not None:
> data = json.dumps(body).encode()
> headers["Content-Type"] = "application/json"
> if extra_headers:
> headers.update(extra_headers)
> request = urllib.request.Request(
> self.base + "/v1" + path, data=data, headers=headers, method=method
> )
> with urllib.request.urlopen(request, timeout=self.remaining()) as response:
> payload = response.read()
> return response.status, response.headers, json.loads(payload) if payload else None
>
> def create_test_run(self, expect_failure):
> command = TEST_SUITE.replace(
> "# OPTIONAL_FAILURE", "check deliberate-failure false" if expect_failure else ""
> )
> status, _, result = self.request(
> "POST",
> "/instances",
> {
> "image": self.image,
> "command": command,
> "shell": True,
> "disposable": True,
> "timeout": 30,
> "truncate_output_at": 1048576,
> },
> )
> if status != 201:
> raise RuntimeError(f"Expected create status 201, got {status}")
> operation_id = result["uuid"]
> self.owned.add(operation_id)
> return operation_id
>
> def open_events(self, operation_id, last_event_id=None):
> while True:
> headers = {
> "Authorization": f"Bearer {self.token}",
> "Project": self.project,
> "Accept": "text/event-stream",
> }
> if last_event_id is not None:
> headers["Last-Event-Id"] = str(last_event_id)
> request = urllib.request.Request(
> f"{self.base}/v1/operations/{operation_id}/events?follow=1",
> headers=headers,
> )
> try:
> return urllib.request.urlopen(request, timeout=self.remaining())
> except urllib.error.HTTPError as error:
> if error.code not in {410, 425, 502, 504}:
> raise
> time.sleep(min(retry_delay(error.headers), self.remaining()))
>
> def consume_events(self, operation_id, cursor=None, disconnect_after=None):
> response = self.open_events(operation_id, cursor)
> processed = 0
> saw_completion = False
> try:
> for fields in read_sse_frames(response, self.remaining):
> event = fields.get("event", ["message"])[0]
> if event == "sse_error":
> raise ConnectionError("SSE server reported an in-band error")
> if "id" not in fields or "data" not in fields:
> continue
> event_id = int(fields["id"][0])
> payload = json.loads("\n".join(fields["data"]))
> if cursor is not None and event_id <= cursor:
> continue
> if payload.get("type") in {"stdout", "stderr"}:
> channel = payload["type"]
> text = decode_stream(payload["data"])
> print(f"[{channel}] {text}", end="", flush=True)
> elif payload.get("type") in {"spawn", "exit", "completion"}:
> print(f"[event] {payload['type']} id={event_id}", flush=True)
> # The frame is complete, valid, and displayed. Commit its cursor now.
> cursor = event_id
> processed += 1
> saw_completion = saw_completion or payload.get("type") == "completion"
> if disconnect_after is not None and processed >= disconnect_after:
> print(f"[client] disconnect after processed event {cursor}", flush=True)
> break
> finally:
> response.close()
> return cursor, saw_completion
>
> def final_result(self, operation_id):
> while True:
> _, headers, result = self.request("GET", f"/operations/{operation_id}")
> if result["status"] in TERMINAL:
> self.owned.discard(operation_id)
> return result
> time.sleep(min(retry_delay(headers), self.remaining()))
>
> def cancel_owned(self):
> self.deadline = max(self.deadline, time.monotonic() + 15.0)
> for operation_id in list(self.owned):
> try:
> _, _, current = self.request("GET", f"/operations/{operation_id}")
> if current["status"] not in TERMINAL:
> self.request("DELETE", f"/operations/{operation_id}")
> self.final_result(operation_id)
> except Exception as error:
> print(f"Cleanup failed for {operation_id}: {error}", file=sys.stderr)
>
>
> def verify_result(result, expected_exit):
> process = result.get("metadata", {}).get("result") or {}
> state = process.get("state") or {}
> actual = state.get("exit_code")
> if result.get("status") != "SUCCESS":
> raise RuntimeError(f"Operation failed: {result.get('status')} {result.get('error')}")
> if actual != expected_exit:
> raise RuntimeError(f"Expected process exit {expected_exit}, got {actual}")
> if state.get("timed_out") or state.get("signal") not in (-1, None):
> raise RuntimeError(f"Process was interrupted: {state}")
> for channel in ("stdout", "stderr"):
> if (process.get(channel) or {}).get("truncated"):
> raise RuntimeError(f"{channel} was truncated")
> return process
>
>
>
>
> if __name__ == "__main__":
> main()
> ```
The first run prints `PASS` records and `SUMMARY passed=2 failed=0`. The client closes its first connection only after it has decoded, displayed, and committed a complete event. The resumed request sends that ID in `Last-Event-Id`, and the client ignores any event ID it has already processed.
The second run prints `FAIL deliberate-failure` on stderr, finishes with `SUMMARY passed=2 failed=1`, and reports `process_exit=1`. The program exits nonzero if the API operation fails, the observed process exit differs from the expected outcome, output is truncated, or the deadline expires.
Both operations set `disposable: true`, so they do not create retained images. Their 30-second remote timeout bounds execution if the client disappears. The client also records every operation UUID and cancels any operation it still owns after a local failure. It deliberately reconnects once to demonstrate cursor resumption; an unexpected transport or in-band SSE error stops the recipe and triggers that cleanup.
See [Stream output and events](/sandboxes/guides/stream-output-and-events) for cursor and recovery mechanics. The [SSE endpoint reference](/api-reference/sandboxes/operations/stream-the-operation-event-log-via-server-sent-events) defines the exact frame and error contract; [Get operation status](/api-reference/sandboxes/operations/get-an-operation-status) defines the terminal result fields.
# Try two coding fixes and keep the passing branch
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/try-two-coding-fixes
Apply two isolated patches to failing deterministic tests, select the passing image, and continue from it.
This recipe creates a tiny failing repository, saves it as a checkpoint, tries two fixes independently, and continues only from the branch whose tests pass.
## Prerequisites
Complete [Set up access](/sandboxes/start/set-up-access). In a fresh project, run `uv init --python 3.12` and `uv add "contree-sdk==0.3.6"`. The example imports `docker.io/library/python:3.12-alpine`; an existing immutable image UUID can be substituted.
## Complete source
```python theme={null}
import asyncio
from contree_sdk import Contree
TEST_SOURCE = """
from calc import add
assert add(2, 3) == 5
assert add(-1, 1) == 0
print("PASS")
"""
BROKEN_SOURCE = """
def add(a, b):
return a - b
"""
MULTIPLY_SOURCE = """
def add(a, b):
return a * b
"""
ADDITION_SOURCE = """
def add(a, b):
return a + b
"""
FOLLOW_UP_SOURCE = """
from calc import add
assert add(10, 7) == 17
print("FOLLOW-UP PASS")
"""
async def main() -> None:
client = Contree()
base = await client.images.oci("docker.io/library/python:3.12-alpine")
prepared = await base.run(
shell="true",
files={
"/repo/calc.py": BROKEN_SOURCE.encode(),
"/repo/test_calc.py": TEST_SOURCE.encode(),
},
disposable=False,
timeout=60,
)
if prepared.exit_code != 0 or prepared.uuid is None:
raise RuntimeError('Preparation failed or returned no saved image')
print(f"Prepared test image: {prepared.uuid}")
baseline = await client.images.use(prepared.uuid, strict=True)
baseline_test = await baseline.run(
shell="python test_calc.py",
cwd="/repo",
disposable=True,
timeout=30,
)
if baseline_test.exit_code == 0:
raise RuntimeError('The baseline should fail before either patch is applied')
print("Baseline fails as expected; trying both fixes")
multiply_result, addition_result = await asyncio.gather(
baseline.run(
shell="python test_calc.py",
files={"/repo/calc.py": MULTIPLY_SOURCE.encode()},
cwd="/repo",
disposable=False,
timeout=30,
),
baseline.run(
shell="python test_calc.py",
files={"/repo/calc.py": ADDITION_SOURCE.encode()},
cwd="/repo",
disposable=False,
timeout=30,
),
)
outcomes = {"multiply": multiply_result.exit_code, "add": addition_result.exit_code}
if outcomes != {"multiply": 1, "add": 0}:
raise RuntimeError('Expected the multiplication patch to fail and the addition patch to pass')
if addition_result.stdout != "PASS\n" or addition_result.uuid is None:
raise RuntimeError('Passing patch did not return PASS output and a saved image')
selected_source = await addition_result.read("/repo/calc.py")
if selected_source != ADDITION_SOURCE.encode():
raise RuntimeError('Saved source does not contain the selected addition fix')
print(f"Patch results: {outcomes}; continuing from {addition_result.uuid}")
selected_image = await client.images.use(addition_result.uuid, strict=True)
continued = await selected_image.run(
shell="python test_calc.py && python follow_up.py",
files={"/repo/follow_up.py": FOLLOW_UP_SOURCE.encode()},
cwd="/repo",
disposable=True,
timeout=30,
)
if continued.exit_code != 0:
raise RuntimeError('The selected image failed the follow-up checks')
print(continued.stdout, end="")
print(f"baseline={prepared.uuid} chosen={addition_result.uuid} outcomes={outcomes}")
asyncio.run(main())
```
Save as `branch_fixes.py` and run `uv run python branch_fixes.py`. The output reports `outcomes={'multiply': 1, 'add': 0}` along with the baseline and chosen image UUIDs. The multiplication patch fails; the addition patch passes. The final operation starts from the selected image; it does not merge branches or resume a previous process.
Both patch runs retain filesystem state because comparison includes the changed source. Selection uses the passing branch only and does not depend on failure-state persistence. If the API operation itself fails, retry from the recorded baseline UUID after classifying the platform error. All retained branch images follow the current image-retention policy.
See [Branch, compare, and recover](/sandboxes/guides/branch-compare-and-recover).
# Prepare inputs, then verify with networking disabled
Source: https://docs.tokenfactory.nebius.com/sandboxes/cookbook/verify-with-networking-disabled
Save prepared inputs, verify them without a guest network interface, and inspect both operations using Python.
Prepare files in one operation, save the resulting image, then verify those files in a new operation with networking disabled. This recipe uses Python to call the REST API, where `networking.enabled` controls the guest network interface. The setting defaults to `true` and must be chosen for each operation.
## Prerequisites
Complete [Set up access](/sandboxes/start/set-up-access). Export `NEBIUS_API_KEY`, `NEBIUS_PROJECT_ID`, and an immutable `IMAGE_UUID` containing `/bin/sh` and the `cat`, `mkdir`, `test`, and `printf` commands. In a new local directory, create a Python project:
```bash theme={null}
uv init --bare --python 3.12
uv add "httpx==0.28.1"
```
The client keeps the API credential locally. It is not passed to guest code.
## Follow the workflow
1. Prepare `/fixture/expected.txt` with networking enabled and `disposable=False`.
2. Keep the returned image UUID. It supplies the prepared files to the next operation.
3. Run verification from that image with `networking=False` and `disposable=True`.
The verification checks the file contents and confirms that `/sys/class/net` contains no interface other than loopback. It does not depend on reaching an external host. Saving the preparation image carries the files into the second operation; it does not carry the earlier network setting.
## Run the complete example
Save the program as `verify_no_network.py` and run `uv run python verify_no_network.py`. Start with `main()`: it describes the two operations. The `run_operation()` helper submits each request once, prints its ID, and polls with a 90-second deadline. Each guest command has a 30-second execution limit.
Expected output includes two operation IDs, the saved checkpoint UUID, and:
```text theme={null}
fixture-ok network-disabled
```
> [accordion] Complete program
>
> ```python theme={null}
> import base64
> import os
> import time
>
> import httpx
>
> PREPARE_INPUTS = r"""
> mkdir -p /fixture
> printf 'expected-v1\n' > /fixture/expected.txt
> """
>
> VERIFY_OFFLINE = r"""
> test "$(cat /fixture/expected.txt)" = expected-v1
> for interface in /sys/class/net/*; do
> test "${interface##*/}" = lo
> done
> printf 'fixture-ok network-disabled\n'
> """
>
>
> def main():
> with httpx.Client(
> base_url=os.getenv(
> "CONTREE_BASE_URL", "https://api.tokenfactory.nebius.com/sandboxes"
> ).rstrip("/") + "/",
> headers={
> "Authorization": f"Bearer {os.environ['NEBIUS_API_KEY']}",
> "Project": os.environ["NEBIUS_PROJECT_ID"],
> },
> timeout=15,
> ) as client:
> prepared, _ = run_operation(
> client,
> os.environ["IMAGE_UUID"],
> PREPARE_INPUTS,
> networking=True,
> disposable=False,
> )
> checkpoint = prepared.get("result_image_uuid")
> if not checkpoint:
> raise RuntimeError("Preparation returned no saved image")
> print(f"Checkpoint: {checkpoint}", flush=True)
>
> verified, output = run_operation(
> client,
> checkpoint,
> VERIFY_OFFLINE,
> networking=False,
> disposable=True,
> )
> if (
> output != "fixture-ok network-disabled\n"
> or verified.get("result_image_uuid")
> ):
> raise RuntimeError("Verification output or disposable result was unexpected")
> print(output, end="")
>
>
> def run_operation(client, image, command, *, networking, disposable):
> # Submit once. A transport error can leave the submission outcome uncertain.
> response = client.post(
> "v1/instances",
> json={
> "image": image,
> "command": "set -e\n" + command,
> "shell": True,
> "networking": {"enabled": networking},
> "disposable": disposable,
> "timeout": 30,
> "truncate_output_at": 1048576,
> },
> )
> response.raise_for_status()
> if response.status_code != 201:
> raise RuntimeError(f"Unexpected create status: {response.status_code}")
> operation_id = response.json()["uuid"]
> print(f"Operation: {operation_id}", flush=True)
> deadline = time.monotonic() + 90
> while True:
> remaining = deadline - time.monotonic()
> if remaining <= 0:
> raise TimeoutError(f"Inspect operation {operation_id} before retrying")
> response = client.get(f"v1/operations/{operation_id}", timeout=min(15, remaining))
> response.raise_for_status()
> operation = response.json()
> status = operation["status"]
> if status == "SUCCESS":
> break
> if status not in {"PENDING", "ASSIGNED", "EXECUTING"}:
> raise RuntimeError(f"Operation {operation_id} ended as {status}")
> retry_after = response.headers.get("Retry-After", "1")
> delay = max(1, int(retry_after)) if retry_after.isdecimal() else 1
> time.sleep(max(0, min(delay, deadline - time.monotonic())))
>
> result = operation["metadata"]["result"]
> state = result["state"]
> stdout = decode_output(result["stdout"])
> stderr = decode_output(result["stderr"])
> if (
> state["exit_code"] != 0
> or state.get("timed_out")
> or state.get("signal") not in (None, -1)
> ):
> raise RuntimeError(f"Process failed in {operation_id}: {state}; stderr={stderr}")
> return operation, stdout
>
>
> def decode_output(stream):
> if stream.get("truncated"):
> raise RuntimeError("Output was truncated; increase the output limit")
> if stream["encoding"] == "base64":
> return base64.b64decode(stream["value"], validate=True).decode("utf-8")
> if stream["encoding"] in {"ascii", "utf-8", "utf8"}:
> return stream["value"]
> raise ValueError(f"Unsupported output encoding: {stream['encoding']}")
>
>
> if __name__ == "__main__":
> main()
> ```
The preparation checkpoint remains subject to image retention. The verification returns no saved image because it is disposable. To adapt the recipe, replace `PREPARE_INPUTS` and `VERIFY_OFFLINE` while keeping the saved-image check and the network setting on the verification operation.
If a request fails or polling reaches its deadline, inspect the printed operation ID before resubmitting. Polling failure does not cancel accepted work. If submission fails before an ID is returned, resolve that uncertain outcome before repeating the POST. The remote execution limit still bounds an accepted workload.
A failed verification may indicate a missing or incorrect fixture, or an unexpected guest interface. Keep the operation and image IDs with the redacted process result when investigating. Disabling networking applies to the whole operation, including its subprocesses. Use it when verification can run entirely offline.
See [Configure networking and secrets](/sandboxes/guides/configure-networking-and-secrets) and the [spawn API reference](/api-reference/sandboxes/instances/spawn-a-new-container-instance).
# Branch, compare, and recover
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/branch-compare-and-recover
Run alternatives from one image, select a verified result, and recover from a known-good checkpoint.
Branching means starting independent operations from one immutable image UUID. Each branch receives new compute and its own filesystem changes.
## Compare two candidate fixes
1. Verify a baseline operation and record its result image UUID.
2. Resolve that UUID with `images.use(..., strict=True)`.
3. Start alternatives from the same object; set `disposable=False` when the changed files must be inspected or selected.
4. Compare command exit codes and deterministic artifacts. An accepted or terminal API operation alone does not establish test success.
5. Resolve the passing branch's result UUID and start a new continuation operation from it.
The fragment below shows the selection logic. It runs inside an async function with `asyncio` imported, an authenticated `client`, and a verified `baseline` image. `apply-left`, `apply-right`, and `run-tests` stand for commands supplied by the application; Sandboxes does not provide commands with those names. Use [Try two coding fixes and keep the passing branch](/sandboxes/cookbook/try-two-coding-fixes) for a complete runnable example.
```python theme={null}
left, right = await asyncio.gather(
baseline.run(shell="apply-left && run-tests", disposable=False, timeout=120),
baseline.run(shell="apply-right && run-tests", disposable=False, timeout=120),
)
passing = [run for run in (left, right) if run.exit_code == 0 and run.uuid is not None]
if len(passing) != 1:
raise RuntimeError("Selection is ambiguous")
chosen = await client.images.use(passing[0].uuid, strict=True)
verification = await chosen.run(shell="run-tests", disposable=True, timeout=120)
assert verification.exit_code == 0
```
No API merges two images. A chosen branch does not continue a process from its test run.
## Recovery boundary
After a nonzero exit, platform failure, cancellation, timeout, or disconnect, keep the operation ID and safe diagnostics. Query the operation before resubmitting. Choose the next image using the [result-image rules](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image).
Tags are mutable pointers. Use them for discovery and record UUIDs for reproducibility.
See [Recover from a known-good image](/sandboxes/cookbook/recover-from-known-good-image) and [Troubleshooting](/sandboxes/operate/troubleshooting).
# Configure networking and secrets
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/configure-networking-and-secrets
Disable the guest network where supported and keep credentials out of retained state and output.
The REST spawn request has one public network control:
```json theme={null}
{"networking": {"enabled": false}}
```
`enabled` defaults to `true`. When false, the VM starts without a guest network interface. Set it on every independent operation that requires this boundary. An additional subprocess shares its parent VM and cannot select a separate VM network setting.
Use `networking.enabled=false` when the workload must run without a guest network interface. Inspect `/sys/class/net` and assert that no interface other than loopback is present so the workload verifies this boundary without depending on an external service. See [Verify with networking disabled](/sandboxes/cookbook/verify-with-networking-disabled). If the workload requires destination allowlists, private networking, ingress, specific DNS behavior, or network logs, contact the Sandboxes team to confirm support before deployment.
## Separate setup and verification
Fetch dependencies and fixtures in a controlled setup operation, retain the result, then run verification from its immutable UUID with networking disabled. Saving an image carries filesystem state, not the earlier network policy, connection, DNS cache, or authentication session.
## Credential boundary
* Keep the API credential in the client process; sandbox code does not need it unless it intentionally calls the control plane.
* Pass short-lived, narrow credentials only to operations that need them.
* Avoid command-line arguments, stdout, stderr, uploaded files, Dockerfile arguments, and retained filesystem locations for secrets.
* `preserve_env=True` writes the combined environment into result-image metadata. Leave it false for secrets.
* A disposable run prevents its filesystem changes from becoming a branch source, but it is not a deletion or log-retention guarantee.
Before sharing operation diagnostics, remove authorization headers, credentials, customer data, and sensitive command output. Confirm encryption-at-rest, deletion, and retention requirements with the Sandboxes team before processing data that depends on those guarantees; see [Security and data handling](/sandboxes/operate/security-and-data-handling).
# Prepare and reuse environments
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/prepare-and-reuse-environments
Create a reusable filesystem image from setup commands, OCI import, or the supported CLI Dockerfile workflow.
Move stable setup out of repeated work. Record the immutable UUID produced by preparation and start later operations from that UUID.
## Choose a preparation path
| Input | Public path | Result |
| - | - | - |
| Existing Sandboxes image | `images.use(UUID, strict=True)` | Verified image reference; no compute |
| OCI registry image | `images.import_from()` or `images.oci()` | Imported filesystem image |
| Setup command | `image.run(..., disposable=False)` | Result image containing filesystem changes |
| Dockerfile subset | CLI 0.9.4 `contree build` | Cached checkpoint sequence and final tag |
OCI import captures the filesystem root. Do not rely on OCI `CMD`, `ENTRYPOINT`, ports, health checks, or a service lifetime as the command for a later operation.
## Python preparation
Complete [Set up access](/sandboxes/start/set-up-access). In a fresh project, run `uv init --python 3.12` and `uv add "contree-sdk==0.3.6"`. The fragments below run inside an async `main()`; [Prepare once, reuse safely](/sandboxes/cookbook/prepare-once-reuse-safely) contains the complete entry point.
With `contree-sdk==0.3.6`, `run()` prepares an awaitable request and execution begins when it is awaited:
```python theme={null}
from contree_sdk import Contree
client = Contree()
base = await client.images.oci("docker.io/library/alpine:3.19")
prepared = await base.run(
shell="mkdir -p /opt/example && printf 'version=1\\n' > /opt/example/config.ini",
disposable=False,
timeout=60,
)
if prepared.exit_code != 0 or prepared.uuid is None:
raise RuntimeError("Preparation failed or returned no saved image")
checkpoint_uuid = prepared.uuid
```
A later read starts new compute:
```python theme={null}
checkpoint = await client.images.use(checkpoint_uuid, strict=True)
verification = await checkpoint.run(
shell="cat /opt/example/config.ini",
disposable=True,
timeout=30,
)
if verification.exit_code != 0:
raise RuntimeError(f"Configuration read failed: {verification.stderr}")
if verification.stdout != "version=1\n":
raise RuntimeError("The saved configuration has an unexpected value")
if verification.uuid is not None:
raise RuntimeError("A disposable read unexpectedly returned a saved image")
print(verification.stdout, end="")
```
Expected output:
```text theme={null}
version=1
```
Filesystem state survives only through a retained image. Processes, memory, services, and network connections do not.
## Dockerfile and refresh rules
CLI 0.9.4 supports `FROM`, `RUN`, `COPY`/`ADD`, `WORKDIR`, `ENV`, `ARG`, and `USER`. Multi-stage `AS` is parsed but not executed. Each `RUN` is a Sandboxes operation; the client caches compatible layers. Use `--no-cache` for a deliberate full rebuild.
Pin base images and dependencies, record the final UUID with the source revision, run a disposable smoke test, then move a shared tag. Keep registry credentials and build secrets outside uploaded files, retained environment values, and command output.
See [Build and refresh a reusable custom environment](/sandboxes/cookbook/build-reusable-custom-environment) and [Update images and clients](/sandboxes/operate/update-images-and-clients).
# Run commands and handle results
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/run-commands-and-results
Choose command or shell execution, make persistence explicit, and interpret operation and process results.
Each request to `POST /v1/instances` starts a new operation from an image. The operation result describes the primary process. A retained result image, when requested and produced, represents filesystem state after the operation; it does not preserve processes, memory, or connections.
Complete [access setup](/sandboxes/start/set-up-access). The runnable example uses the Python SDK to submit a command, wait for completion, and decode its output. The REST response fields are explained below for applications that call the API directly.
## Choose direct or shell execution
Use `command` with `args` when the executable accepts ordinary arguments. This avoids shell expansion and is the safer choice for dynamic values. For pipes, redirects, variable expansion, or compound statements, pass the command string as `shell="..."` in the SDK. In a REST request, put that string in `command` and set `shell: true`.
The execution environment also depends on that choice. A shell receives the environment stored in the image. For direct execution, pass every required variable in `env` according to the [spawn reference](/api-reference/sandboxes/instances/spawn-a-new-container-instance). Use the REST `preserve_env` flag only when environment values should be written to result-image metadata for later operations. Do not concatenate untrusted values into shell source.
## Choose whether to retain filesystem changes
Set `disposable` explicitly. Python uses `False` and `True`; the REST JSON values are shown below:
| Goal | Value | Result |
| - | - | - |
| Keep changed files as a continuation point | `false` | A successful operation can return `result_image_uuid`. Record that immutable UUID before starting later work. |
| Use only the process result | `true` | No result image is created. Files written by the operation cannot be used as a later branch source. |
The SDK exposes a saved result image through the returned object's `uuid`; REST uses `result_image_uuid`. The input image remains unchanged. A result image is distinct from the operation UUID. Confirm that `result_image_uuid` is present before using it; an unchanged filesystem or an unsuccessful operation may not produce a new image.
## Run a command with Python
Use Python 3.12 and the SDK installation from the [Python quickstart](/sandboxes/start/python-quickstart). Export `NEBIUS_API_KEY`, `NEBIUS_PROJECT_ID`, and an immutable `IMAGE_UUID` from the [image-discovery step](/sandboxes/start/set-up-access#find-an-image-uuid).
Save this as `run_command.py`, then run `uv run python run_command.py`:
```python theme={null}
import asyncio
import os
from contree_sdk import Contree
async def main():
client = Contree()
image = await client.images.use(os.environ["IMAGE_UUID"], strict=True)
result = await image.run(
shell='printf "ready\\n"; printf "diagnostic\\n" >&2',
disposable=True,
timeout=30,
truncate_output_at=1048576,
)
print(f"stdout: {result.stdout}", end="")
print(f"stderr: {result.stderr}", end="")
if result.result.truncated:
raise RuntimeError("Output was truncated; increase the output limit")
if result.exit_code != 0:
raise RuntimeError(f"Command failed with exit code {result.exit_code}")
print(f"Result: process_exit={result.exit_code}")
asyncio.run(main())
```
Expected output:
```text theme={null}
stdout: ready
stderr: diagnostic
Result: process_exit=0
```
Awaiting the run submits it and waits for an operation result. The SDK decodes stdout and stderr into strings. The command has a 30-second execution limit, and `disposable=True` discards its filesystem changes. To invoke an executable directly, replace `shell=...` with `command="/bin/echo", args=["ready"]`.
A returned process result still needs checking: nonzero exit codes indicate command failure, and truncated output may be incomplete. SDK exceptions can indicate request, transport, or operation failures. Do not interpret them as a normal process result.
> [!NOTE]
>
> SDK 0.3.6 attempts best-effort cancellation when its wait ends without observing a terminal result. Resolve an interrupted operation's outcome before repeating the command. A REST polling timeout or event-stream disconnect does not itself cancel execution. See [Execution lifecycle](/sandboxes/concepts/execution-lifecycle).
## Start, observe, and finish
Applications that call the API directly follow three stages:
1. Submit the command to [POST /v1/instances](/api-reference/sandboxes/instances/spawn-a-new-container-instance). A `201` response means the operation was accepted; keep its UUID immediately.
2. Poll [GET /v1/operations/\{operationId}](/api-reference/sandboxes/operations/get-an-operation-status) until its status is `SUCCESS`, `FAILED`, or `CANCELLED`. The process result can be null while work is pending.
3. Inspect the terminal response's process state and output. Operation `SUCCESS` means the service finished the work; the process exit code tells you whether the command passed.
### See the requests
For direct execution, the POST request body can be as small as:
```json theme={null}
{
"image": "YOUR_IMMUTABLE_IMAGE_UUID",
"command": "/bin/echo",
"args": ["ready"],
"shell": false,
"disposable": true,
"timeout": 30
}
```
Send the access headers described in [Set up access](/sandboxes/start/set-up-access). The response's `uuid` is the operation ID for subsequent status requests; it is distinct from the input or result image UUID.
### Run with bounded polling
Give each status request a timeout and the polling loop a total deadline. Honor `Retry-After` when provided. If the deadline expires, keep the operation ID and inspect or cancel that operation before resubmitting. A transport failure during POST can leave submission uncertain; do not automatically send the POST again.
The [networking recipe](/sandboxes/cookbook/verify-with-networking-disabled) includes a complete Python HTTP example with bounded polling and operation IDs. For exact request and response schemas, use the separate API reference.
After a terminal response, check both layers:
1. `status` and `error` describe the operation.
2. `metadata.result.state` describes the primary process, including `exit_code`, `signal`, and `timed_out` when available.
3. `metadata.result.stdout` and `metadata.result.stderr` contain the recorded process output and indicate its encoding and whether it was truncated.
4. `result_image_uuid` identifies retained filesystem state when one was produced.
A `SUCCESS` operation can contain a nonzero process exit code. Treat that command as failed. A closed event stream or a completed HTTP request is also insufficient; inspect the terminal response.
| Outcome | Action |
| - | - |
| `SUCCESS`, exit code `0`, no signal or timeout | Consume the result. Use `result_image_uuid` only when it is present. |
| `SUCCESS`, nonzero exit code | Inspect stdout and stderr, correct the command or input, then start a new operation. |
| Process signal or `timed_out: true` | Treat the process as interrupted and decide whether the operation is safe to repeat. |
| `FAILED` | Read `error` and any available process result. Correct platform, capacity, or request problems before retrying. |
| `CANCELLED` | Confirm cleanup and do not assume a result image exists. |
Use `?inflight=1` only when partial stdout or stderr is needed; it performs additional work on an executing instance. See [Get operation status](/api-reference/sandboxes/operations/get-an-operation-status), [Cancel an operation](/api-reference/sandboxes/operations/cancel-an-operation), and the [timeout and disconnection guidance](/sandboxes/operate/troubleshooting#timeouts-and-disconnections).
To display output as the process runs, continue with [Stream output and events](/sandboxes/guides/stream-output-and-events). To add a process to an operation that is already active, use [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input).
# Run concurrent workloads
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/run-concurrent-workloads
Bound parallel operations, correlate state, classify failures, and cancel only work owned by the batch.
Use a semaphore or fixed worker pool. Give each work item a stable application ID and record:
| Field | Purpose |
| - | - |
| Item ID and attempt | Application correlation and duplicate detection |
| Input image UUID | Reproducible starting state |
| Operation ID | Status, result, and cancellation target |
| Persistence mode | Whether a result image is expected |
| Terminal status | Platform outcome: `SUCCESS`, `FAILED`, or `CANCELLED` |
| Process state | Exit code, signal, or timed-out flag |
| Result image UUID | Continuation point when present |
Tags can move while a batch runs; resolve them before scheduling. Plan for no more than 50 simultaneous operations, then keep the application bound below the effective limit returned for the current token. Leave room for recovery or interactive work.
## Classify before retrying
| Observation | Safe action |
| - | - |
| Request validation or authorization rejection | Correct the request; no accepted operation ID means no status target |
| Rate or service rejection | Back off according to the response and inspect token limits; do not label an undocumented 503 as capacity |
| Transport failure before an operation ID | Acceptance is uncertain; use application correlation and avoid blind resubmission |
| Client wait or observation timeout with an ID | Query that operation before resubmitting |
| `FAILED` platform status | Inspect platform error; retry from known input only when safe |
| `SUCCESS` plus timed-out flag, signal, or nonzero exit | Classify as workload timeout, signal, or failure |
| Result collection failure | Retry retrieval by recorded operation/image ID |
Create requests have no documented idempotency key. An application item ID helps reconcile duplicates but does not make execution idempotent.
## Stop safely
On an early-stop condition, stop scheduling, cancel unfinished operation IDs owned by this batch with `DELETE /v1/operations/{operation_id}`, and observe each terminal state until a deadline. Never use a project-wide cancel-all action from shared automation. Resume cancelled work from its recorded input image UUID. Follow the [result-image rules](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image) when recovering files from cancelled work. Contact the Sandboxes team if cancellation retention or usage affects capacity or cost controls.
See [Run a bounded evaluation batch](/sandboxes/cookbook/run-bounded-evaluation-batch), [Troubleshooting](/sandboxes/operate/troubleshooting), and [Limits, retention, and usage](/sandboxes/operate/limits-retention-and-usage).
# Run subprocesses and send input
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/run-subprocesses-and-send-input
Start an additional process inside an active operation, exchange input, observe output, and end it deliberately.
Use an additional subprocess when two processes need the same live environment. For example, a primary process can wait for a result file while a child receives input and writes that file. Both processes share the operation's filesystem and resource limits.
Use the REST subprocess endpoints for this workflow. Starting a new operation creates a separate runtime; the Python SDK's `popen()` wrapper also starts its own operation.
Complete [access setup](/sandboxes/start/set-up-access) before using the REST endpoints. The complete [interactive-process recipe](/sandboxes/cookbook/interact-with-a-process) uses one bounded standard-library Python program.
## Keep the parent alive until the work is done
The primary process controls the operation lifetime. When it finishes, finalization begins and additional subprocesses cannot continue independently. Design the parent with a bounded coordination condition, such as waiting for a completion file until a deadline. A subprocess finishing does not finalize the parent or create its own result image.
Before spawning a child, confirm that the parent has reached `ASSIGNED` or `EXECUTING` and has published an application readiness signal. Status alone says that the runtime is active; it does not prove that a service or file inside the runtime is ready. A short `GET /operations/{operationId}?inflight=1` poll can inspect partial parent output when a dedicated readiness endpoint is unavailable.
```mermaid theme={null}
%%{init: { "sequence": { "diagramMarginX": 10, "actorMargin": 25, "width": 100, "height": 40, "mirrorActors": false, "wrap": true } } }%%
sequenceDiagram
participant Client
participant Parent
participant Child
Parent-->>Client: Readiness observed
Client->>Child: Spawn child
Client->>Child: First input
Client->>Child: Last input + EOF
Child-->>Parent: Completion file
Child-->>Client: Child result
Parent-->>Client: Parent ends
Finalize operation
```
Client arrows represent REST requests, not direct connections to guest processes. This is the normal path in the [interactive recipe](/sandboxes/cookbook/interact-with-a-process). The file coordinates the two processes. If the primary process ends first, finalization stops any remaining child; the client cannot keep it alive by continuing to poll.
## Spawn and address the child
Send an `ExecSpec` to `POST /operations/{operationId}/subprocesses`. VM-level fields such as `image`, `disposable`, `timeout`, and `resources_limits` belong to the parent operation and are not accepted in the child request.
A successful response returns a fresh `spid` of 2 or greater and a `Location` for its result. Preserve both the parent operation UUID and the child `spid`. If the create request times out, inspect the event stream for a matching `spawn` event before retrying because the child may already exist.
See [Spawn an additional subprocess](/api-reference/sandboxes/operation/spawn-an-additional-subprocess-inside-a-running-instance).
## Send ordered input and EOF
Set the child's initial `stdin.close` to `false` when later writes are required. Send each chunk to `POST /operations/{operationId}/subprocesses/{spid}/stdin`. Serialize writes to the same child when order matters; concurrent writes have unspecified order. The API does not append a newline.
Use `encoding: "ascii"` for text and `encoding: "base64"` for arbitrary bytes. Send `close: true` on the final write, or send an empty close-only request, to deliver EOF. A `204` confirms the request completed. A `504` leaves delivery uncertain, so a blind retry can duplicate input. Add sequence numbers or another application-level idempotency marker when duplicate input would be harmful.
See [Write to subprocess stdin](/api-reference/sandboxes/operation/write-to-a-subprocesss-stdin-andor-close-it).
## Observe completion or signal the process
Read `GET /operations/{operationId}/subprocesses/{spid}` until the child result is ready. Honor `Retry-After` for a `425` response and keep polling bounded. Check the child's exit code, signal, timeout flag, stdout, stderr, encoding, and truncation separately from the parent result.
To stop a live child, call `DELETE /operations/{operationId}/subprocesses/{spid}?signal=SIGTERM` or choose another documented signal. The signal targets the subprocess's process group. Completion is observed later in the child result: a signalled child reports `exit_code: -1` and the signal number. Signalling `spid=1` ends the primary workload and therefore ends the operation.
See [Signal a subprocess](/api-reference/sandboxes/operation/kill-one-subprocess).
## Handle lifetime races
| Race | Required behavior |
| - | - |
| Child exits first | Inspect its result, then let the primary workload reach its own terminal condition. |
| Parent exits first | Stop child requests. Finalization terminates remaining children; inspect both terminal results rather than retrying against the finished runtime. |
| Client fails while parent remains active | Cancel the parent if the workflow owns it and cannot safely resume. Poll until the parent is terminal. |
| Stdin write returns `504` | Treat delivery as unknown and reconcile at the application protocol level. |
The [interactive-process recipe](/sandboxes/cookbook/interact-with-a-process) covers normal two-write input with EOF, a child terminated by `SIGTERM` while the parent completes normally, and a negative case where the parent finishes first. Its `finally` block cancels any parent operation left active after a client-side failure.
# Stream output and events
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/stream-output-and-events
Observe stdout, stderr, and operation events over SSE, resume after disconnect, and verify the final result.
The REST event endpoint exposes a server-sent events (SSE) stream for one operation. It carries primary-process and child-process events, including stdout, stderr, spawn, exit, and completion. The subscription observes execution; disconnecting it does not cancel the operation or extend its lifetime.
Complete [access setup](/sandboxes/start/set-up-access), create an operation, and keep its UUID. The end-to-end [streaming recipe](/sandboxes/cookbook/stream-a-build-or-test-run) runs a small test suite and includes a standard-library Python SSE client.
## Choose live or historical reading
Use `follow=1` to send available events and continue following an active operation. Use `follow=0` to read only the events currently available. Following requires the operation's spawn permission in addition to baseline list permission because the server keeps subscription state.
Every normal frame has an `id`, an `event` name, and JSON `data`. Keepalive comments start with `:` and contain no application event. An `sse_error` frame reports an in-band stream failure after HTTP `200` has already been sent.
The JSON object identifies the process with `spid`. The primary process is `spid=1`; additional subprocesses use `spid` values of 2 or greater. Add `spid=` to the query when only one process is relevant.
## Decode output as it arrives
For `stdout` and `stderr` events, inspect `data.encoding` before displaying `data.value`. Decode `base64` values to bytes. An `ascii` value can be displayed as text. Preserve the channel label: stderr is useful even when the process ultimately succeeds.
Output chunks reflect process writes and buffering. They are not guaranteed to align with application lines. Ordering is represented by the event IDs in the combined stream; do not infer a stronger ordering guarantee between the operating system's stdout and stderr streams.
## Commit a resumable cursor
Parse a complete SSE frame, validate its JSON, perform the application's side effect, and only then save its event ID. The saved ID means “fully processed,” not merely “received from the socket.” If the connection breaks halfway through a frame, leave the cursor unchanged.
Reconnect with the last successfully processed ID:
```http theme={null}
GET /sandboxes/v1/operations/OPERATION_ID/events?follow=1 HTTP/1.1
Authorization: Bearer YOUR_API_KEY
Project: YOUR_PROJECT_ID
Last-Event-Id: 42
```
The service sends events after that ID. Consumers should still deduplicate by event ID so a crash between an external side effect and cursor persistence does not display or apply an event twice.
```mermaid theme={null}
%%{init: { "sequence": { "diagramMarginX": 10, "actorMargin": 25, "width": 100, "height": 40, "mirrorActors": false, "wrap": true } } }%%
sequenceDiagram
participant Client
participant Events
participant Operation
Client->>Events: Subscribe
Events-->>Client: Event 42
Note over Client: Process 42
Save ID 42
Note over Client,Events: Disconnected
Note over Operation: Still running
Client->>Events: Resume after 42
Events-->>Client: Events after 42
Client->>Operation: Get final status
Operation-->>Client: Status and result
```
The cursor belongs to your event consumer. Reconnecting continues observation of the same operation; it does not submit the command again.
## Separate stream completion from execution success
An `exit` event reports that a process ended. A `completion` event describes operation completion. Neither replaces the final status query. After the stream closes, query `GET /operations/{operationId}` and check the terminal operation status, primary process exit code, signal, timeout flag, truncation flags, and any operation error.
If recorded output is truncated, the stream is not an unlimited log store. Use the final result and a retained file artifact when the workload requires complete output, subject to the documented retention rules.
## Recover observation failures
| Response or event | Action |
| - | - |
| Early connection close | Reconnect from the last processed event ID, then query final status if the operation may already be terminal. |
| `sse_error` | Treat the stream as broken, wait briefly, and reconnect from the last processed ID. |
| `410` or `425` | Honor `Retry-After` and retry the observation request. |
| `401` or `403` | Refresh the credential or obtain the required permission. |
| `502` or `504` while opening | Retry observation from the saved cursor. Do not resubmit the operation. |
The [SSE endpoint reference](/api-reference/sandboxes/operations/stream-the-operation-event-log-via-server-sent-events) defines the wire format, query parameters, permissions, event schemas, and errors. The [streaming recipe](/sandboxes/cookbook/stream-a-build-or-test-run) demonstrates progressive output, deliberate disconnect and resume, a successful test run, and a test run whose process exits nonzero.
# Work with files and artifacts
Source: https://docs.tokenfactory.nebius.com/sandboxes/guides/work-with-files-and-artifacts
Inject files, retain generated artifacts, inspect images, and download bytes after execution.
Upload inputs before a run. After it finishes, read logs from the operation result and download generated files from its saved image.
| Need | Interface | Persistence |
| - | - | - |
| Supply one input | `files={"/guest/path": local_or_bytes}` | Follows that operation and its save choice |
| Prepare reusable files | `apply_files()` or retained run | New image UUID |
| Read one saved file | `image.read()` | Returns bytes without guest compute |
| Download one saved file | `image.download()` or inspect REST API | Local file plus existing image |
| Download a directory | Inspect tar-archive REST endpoint | Local archive plus existing image |
## Generate and retrieve
Complete [Set up access](/sandboxes/start/set-up-access), then place this fragment inside the async `main()` from the [Python quickstart](/sandboxes/start/python-quickstart), replacing its file-saving workflow. It uses the authenticated `client` created there and selects an image containing `mkdir` and `cp`. Use [Generate and download a binary artifact](/sandboxes/cookbook/generate-and-download-binary-artifact) for a complete program, fresh-project setup, and byte-integrity checks.
```python theme={null}
from pathlib import Path
image = await client.images.use("alpine:3.19", strict=True)
run = await image.run(
shell="mkdir -p /out && cp /input.bin /out/result.bin",
files={"/input.bin": b"\x00input\xff"},
disposable=False,
timeout=30,
)
if run.exit_code != 0 or run.uuid is None:
raise RuntimeError("File generation failed or returned no saved image")
destination = Path("result.bin")
await run.download("/out/result.bin", destination)
if destination.read_bytes() != b"\x00input\xff":
raise RuntimeError("Downloaded bytes differ from the input")
print(f"Downloaded and verified {destination}")
```
Expected output: `Downloaded and verified result.bin`.
Use absolute guest paths. The SDK uploads local inputs before spawn and uses content hashes for server-side deduplication. The operation result image is required for post-execution inspection. A disposable result has `uuid is None`.
Captured stdin, stdout, and stderr each default to 1 MiB and can be set up to 10 MiB with `truncate_output_at`; the cap applies to recorded streams, not stdin delivery. `run.result.truncated` is true when either stdout or stderr was truncated. Store large or binary output as a file and validate its size or digest after download.
If an artifact read fails after a successful retained run, retry by the recorded image UUID before executing the producer again. Contact the Sandboxes team before a workload depends on specific upload, download, or image-size limits, or on deletion and retention guarantees for each data surface. Do not put credentials in uploaded inputs, logs, or a retained image.
See [Security and data handling](/sandboxes/operate/security-and-data-handling) and the [file download reference](/api-reference/sandboxes/inspect/download-a-file-from-image).
# Cheatsheet
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/cheatsheet
Quick reference card for AI agents using Contree MCP.
## Tools at a Glance
| Tool | When to Use | Cost |
| - | - | - |
| `list_images` | Before importing anything | Free |
| `import_image` | Need new base image | VM |
| `rsync` | Local files needed in container | Free |
| `run` | Execute code | VM |
| `upload` | Single file to container | Free |
| `download` | Extract file from container | Free |
| `get_image` | Check if image exists | Free |
| `set_tag` | Name frequently-used images | Free |
| `list_files` | Explore container filesystem | Free |
| `read_file` | Read file from container | Free |
| `get_operation` | Poll async operation | Free |
| `list_operations` | Find running operations | Free |
| `wait_operations` | Wait for multiple ops | Free |
| `cancel_operation` | Stop stuck operation | Free |
| `get_guide` | Get documentation sections | Free |
## Common Workflows
### Run Python Code
```
1. list_images(tag_prefix="python") → Check existing
2. import_image(docker://python:3.11) → If needed
3. rsync(source="/project", dest="/app") → Sync files
4. run(cmd, image, ds_id) → Execute
```
### Install Dependencies
```
1. run(pip install ..., disposable=false) → Save image
2. Use result_image for subsequent commands
```
### Parallel Execution
```
1. run(cmd1, wait=false) → op-1
2. run(cmd2, wait=false) → op-2
3. wait_operations([op-1, op-2]) → Get both results
```
### Rollback
```
1. Save last good image UUID
2. If something breaks, use the saved UUID
3. No cleanup needed—images are immutable
```
### Inspect Container (No VM)
```
1. list_files(image, path="/etc") → List directory
2. read_file(image, path="/etc/os-release") → Read file
```
## Decision Quick Guide
| Situation | Action |
| - | - |
| First time using an image | `list_images` first |
| Running existing code | `rsync` + `run` |
| Installing packages | `run` with `disposable=false` |
| Multiple independent tasks | Use `wait=false` + `wait_operations` |
| Long-running command | Increase `timeout` |
| Large output expected | Increase `truncate_output_at` |
| Need to save state | `disposable=false` |
| One-off experiment | `disposable=true` (default) |
## Parameters Quick Reference
### run
```json theme={null}
{
"command": "...", // Required
"image": "uuid", // Required
"directory_state_id": "ds-...", // From rsync
"disposable": true, // Discard changes (default)
"timeout": 30, // Seconds
"env": {"KEY": "value"}, // Environment
"wait": true // Sync execution (default)
}
```
### rsync
```json theme={null}
{
"source": "/local/path", // Required
"destination": "/container/path", // Required
"exclude": ["__pycache__", ".git", ".venv", "node_modules"]
}
```
### import\_image
```json theme={null}
{
"registry_url": "docker://image:tag", // Required
"tag": "my-tag", // Optional, for frequent reuse
"wait": true // Sync (default)
}
```
## Key Rules
1. **Check before importing** — `list_images` first
2. **Reuse directory\_state\_id** — Valid for entire session
3. **Use UUIDs directly** — Only tag frequently-used images
4. **One step per command** — Easier rollback and debugging
5. **Always exclude** — `__pycache__`, `.git`, `.venv`, `node_modules`
## Error Recovery
| Error | Solution |
| - | - |
| Image not found | `list_images` to find correct UUID |
| Directory state not found | Re-run `rsync` |
| Command timed out | Increase `timeout` parameter |
| Output truncated | Increase `truncate_output_at` |
| Operation stuck | `cancel_operation` + retry |
## Resources (Read-Only)
| URI Pattern | Returns |
| - | - |
| `contree://image/{uuid}/read/{path}` | File contents |
| `contree://image/{uuid}/ls/{path}` | Directory listing |
| `contree://image/{uuid}/lineage` | Parent-child history |
| `contree://guide/{section}` | Documentation |
| `contree://operations/instance/{id}` | Command execution result |
| `contree://operations/import/{id}` | Image import result |
# Core Concepts
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/concepts/core
How Contree runs code and manages container images.
## Execution Model
When you call `run`, Contree:
1. Spins up an isolated microVM (\~2-5 seconds)
2. Mounts the specified image as the filesystem
3. Injects any files from `directory_state_id` or `files`
4. Executes your command as root
5. Captures stdout, stderr, exit code
6. Optionally saves the resulting filesystem as a new image
**Isolation guarantees:** Every command runs in a separate kernel with full network/filesystem isolation. Destructive commands (`rm -rf /`, kernel exploits) are completely safe.
## The disposable Flag
| Setting | Behavior | Use Case |
| - | - | - |
| `true` (default) | Changes discarded | Tests, read-only operations |
| `false` | New image created | Installing packages, building |
**filesystem\_changed response field:**
* When `true`, `result_image` is a new UUID (changes were saved)
* When `false`, `result_image` equals input image (no snapshot created)
## Images
Every image is:
* **Immutable**: Once created, it never changes
* **Identified by UUID**: `abc123-def456-789012`
* **Optionally tagged**: Human-readable names like `python:3.11`
| Aspect | UUID | Tag |
| - | - | - |
| Immutable | Yes | Points to different UUIDs over time |
| When to use | Chaining, one-off operations | Frequently reused base images |
## Lineage
When you run with `disposable=false` and filesystem changes, Contree creates a parent-child relationship:
```
docker://alpine:latest (img-root)
└── apk add python3 (img-with-python)
├── pip install numpy (img-with-numpy)
└── pip install pandas (img-with-pandas)
```
**View lineage:**
```
contree://image/{uuid}/lineage
```
**Rollback:** Just use any ancestor UUID - no special command needed.
## Timeouts and Output
* **Default timeout**: 30 seconds (use `timeout` parameter for longer)
* **Default output limit**: 8000 bytes (\~2000 tokens)
* **Adjust with**: `truncate_output_at` parameter
# Concepts
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/concepts/index
Core ideas behind Contree MCP.
> [card] [Core Concepts](./core)
> [card] [Workflows](./workflows)
## Overview
| Concept | Description |
| - | - |
| **Core** | Execution model, images, lineage, isolation |
| **Workflows** | File sync (rsync), async execution |
## Quick Mental Model
```mermaid theme={null}
flowchart LR
A[import_image] --> B[Base Image]
B --> C[run
disposable=false]
C --> D[Child Image]
D --> E[Another run]
B --> F[Different branch]
```
Every image is immutable. `disposable=false` creates a new child image. Navigate and rollback using any ancestor UUID.
# Workflows
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/concepts/workflows
File sync and async execution patterns.
## File Sync
Two ways to inject files into containers:
| Method | Use Case | Caching |
| - | - | - |
| `rsync` | Directories, multiple files | Yes (3-tier) |
| `upload` | Single files, generated content | No |
### rsync (Preferred)
```json theme={null}
{"tool": "rsync", "args": {
"source": "/project",
"destination": "/app",
"exclude": ["__pycache__", ".git", ".venv", "node_modules"]
}}
```
Returns `directory_state_id` for use in `run`.
**Three-tier caching**: Local cache → Cache by hash → Server dedup → Upload. Most files resolve from cache.
**Reuse across runs**: The `directory_state_id` is valid for the session. Only re-sync when files change.
### upload (Single Files)
```json theme={null}
{"tool": "upload", "args": {"content": "print('hello')"}}
```
Reference in `run` via `files` parameter:
```json theme={null}
{"files": {"/app/script.py": "file-uuid"}}
```
## Async Execution
| Mode | Parameter | Behavior |
| - | - | - |
| Sync | `wait=true` (default) | Blocks until complete |
| Async | `wait=false` | Returns `operation_id` immediately |
### Parallel Pattern
```json theme={null}
// Launch async
{"command": "python exp_a.py", "wait": false} // Returns op-1
{"command": "python exp_b.py", "wait": false} // Returns op-2
{"command": "python exp_c.py", "wait": false} // Returns op-3
// Wait for all
{"tool": "wait_operations", "args": {"operation_ids": ["op-1", "op-2", "op-3"]}}
```
### wait\_operations Modes
* `"all"` - Wait for all operations to complete
* `"any"` - Return when first operation completes
### Operation States
| State | Description |
| - | - |
| `PENDING` | Queued, not started |
| `EXECUTING` | Running |
| `SUCCESS` | Completed successfully |
| `FAILED` | Completed with error |
| `CANCELLED` | Cancelled by user |
### When to Use Async
**Use `wait=false`** when:
* Running 2+ independent operations
* Operations are long-running (>10s)
**Use `wait=true`** when:
* Running a single operation
* Operations must be sequential
# Overview
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/index
[](https://pypi.org/project/contree-mcp/)
[](https://github.com/nebius/contree-mcp/actions/workflows/tests.yml)
[](https://github.com/nebius/contree-mcp/blob/master/LICENSE)
**Isolated cloud container execution for AI agents.**
Contree MCP is a Model Context Protocol server that gives AI agents secure sandboxed environments with full root access, network, and persistent images. Experiment fearlessly—every container is isolated, every image is immutable, mistakes are free.
> [card] [Quickstart](./quickstart)
>
> Run your first container in 5 minutes.
> [card] [Concepts](./concepts/index)
>
> Understand execution model, images, file sync.
> [card] [Tools](./tools/index)
>
> All 15 tools with parameters and examples.
> [card] [Patterns](./patterns)
>
> Common workflows and mistakes to avoid.
> [card] [Prompts](./prompts/index)
>
> 10 MCP prompts for common workflows.
## Why Contree?
* **Safe sandbox**: Run `rm -rf /`, kernel exploits—nothing escapes
* **Immutable images**: Every UUID is a snapshot, branching is cheap
* **Instant rollback**: Revert to any previous image at zero cost
## Quick Example
```json theme={null}
{"tool": "list_images", "args": {"tag_prefix": "python"}}
{"tool": "rsync", "args": {"source": "/project", "destination": "/app"}}
{"tool": "run", "args": {
"command": "python /app/main.py",
"image": "img-uuid",
"directory_state_id": "ds-uuid"
}}
```
## HTTP Mode
Run the MCP server with built-in interactive documentation:
```bash theme={null}
contree-mcp --mode http --http-port 9452
```
Visit `http://localhost:9452/` for setup guides, tool reference, and best practices.

The HTTP interface with Setup, Instructions, Tools, Resources, and Guides.
## Security
To report security issues, see [Security](./security).
## License
Licensed under the Apache License, Version 2.0. See LICENSE for details.
# Configuration
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/integration/configuration
Detailed configuration options for Contree MCP.
## Authentication
The MCP server supports both auth modes the Contree API exposes — the
same two `contree-cli` recognises:
* **IAM (recommended).** Token + Project header. Sends
`Authorization: Bearer ` and `Project: `.
Default URL: `https://api.tokenfactory.nebius.com/sandboxes`. Use this
for new deployments; the standard `NEBIUS_API_KEY` /
`NEBIUS_AI_PROJECT` env vars are honoured.
* **JWT (legacy).** Token only. Sends `Authorization: Bearer `.
Used by the `contree.dev` PoC deployment. No project required.
A profile’s `type = iam | jwt` line picks the scheme; the client class
that issues backend requests is wired accordingly at startup.
### Profile File (Recommended)
`contree-mcp` reads the same profile file that
[`contree-cli`](https://docs.contree.dev/cli/tutorial/installation.html)
writes, so a single login covers both tools. Install the CLI and run
`contree auth`:
```bash theme={null}
uv tool install contree-cli # or: pip install contree-cli
contree auth # interactive setup
```
This writes `~/.config/contree/auth.ini` with mode `0600`. Override
the directory with `CONTREE_HOME`.
The file is INI-format with one `[profile:]` section per
credential set and a `[DEFAULT] profile = ` line selecting the
active profile:
```ini theme={null}
[DEFAULT]
profile = default
[profile:default]
type = iam
url = https://api.tokenfactory.nebius.com/sandboxes
token =
project =
[profile:staging]
type = jwt
url = https://contree.dev
token =
```
Switch profiles persistently with `contree auth switch `, or
per-invocation with `--profile ` / `CONTREE_PROFILE=`.
`type = iam` requires `project`; `type = jwt` does not.
### Environment Variables (Per-Invocation Overrides)
For one-off overrides without touching the profile file:
```bash theme={null}
export CONTREE_TOKEN="your-token-here"
export CONTREE_URL="https://api.tokenfactory.nebius.com/sandboxes"
export CONTREE_PROJECT="your-nebius-project-id"
```
The standard Nebius IAM credentials are recognised too:
```bash theme={null}
export NEBIUS_API_KEY="your-iam-key"
export NEBIUS_AI_PROJECT="your-nebius-project-id"
```
#### Precedence (important)
Field-by-field, highest first:
1. **CLI flags** — `--token`, `--project`, `--url`, `--profile`.
2. **`CONTREE_*` env vars** — `CONTREE_TOKEN` / `CONTREE_PROJECT` /
`CONTREE_URL` / `CONTREE_PROFILE`. MCP-specific; always layered
on top of the profile.
3. **`NEBIUS_*` env vars** — `NEBIUS_API_KEY` + `NEBIUS_AI_PROJECT`,
recognised **only when both are set** (a complete IAM credential).
A lone `NEBIUS_API_KEY` set ambiently for the Nebius SDK or
terraform provider is **ignored**, and the MCP server logs an
`info` line explaining why.
4. **Active profile** from `auth.ini`. Picked by, in order, `--profile`
→ `CONTREE_PROFILE` → the file’s `[DEFAULT] profile = ...`.
Some practical implications:
* `contree-mcp` (no args) loads the active profile, even if your shell
has `NEBIUS_API_KEY` set for other tools.
* `CONTREE_TOKEN=NEW contree-mcp` rotates the token but reuses the
profile’s `project` and `url` — handy for short-lived tokens.
* `contree-mcp --token X --project Y` populates token + project from
the CLI; `url` and `auth_type` still come from the loaded profile
unless `--url` / `--auth-type` are also supplied.
* With no profile loaded and an incomplete `CONTREE_TOKEN` / `--token`,
the server stops with “No API token configured” rather than running
with half-set credentials.
Token resolution order, per field:
```
token --token > CONTREE_TOKEN > NEBIUS_API_KEY* > profile.token
project --project > CONTREE_PROJECT > NEBIUS_AI_PROJECT* > profile.project
url --url > CONTREE_URL > profile.url
> IAM default (IAM only)
```
`*` `NEBIUS_*` are read only when both are set.
Tokens passed via env may appear in process listings — prefer the
profile file for routine use.
## Server Options
| Option | Environment Variable | Default | Description |
| - | - | - | - |
| - | `CONTREE_HOME` | `$XDG_CONFIG_HOME/contree` (typically `~/.config/contree`) | Directory containing `auth.ini` and MCP state |
| `--profile` | `CONTREE_PROFILE` | active profile from `auth.ini` | Profile to use |
| `--token` | `CONTREE_TOKEN` | from profile | API token (overrides profile) |
| `--url` | `CONTREE_URL` | from profile | API base URL (overrides profile) |
| `--project` | `CONTREE_PROJECT` | from profile | Project ID for IAM auth |
| `--mode` | - | `stdio` | `stdio` or `http` |
| `--http-port` | - | `9452` | HTTP mode port |
| `--http-listen` | - | `127.0.0.1` | HTTP mode bind address |
| `--log-level` | - | `warning` | Logging level |
| `--version` / `-V` | - | - | Print the User-Agent the server emits and exit |
| - | `CONTREE_NO_UPDATE_CHECK` | unset | Disable the daily PyPI update check (set to any value) |
## Cache Configuration
| Option | Default |
| - | - |
| `--cache-files` | `$CONTREE_HOME/mcp/files.db` (typically `~/.config/contree/mcp/files.db`) |
| `--cache-general` | `$CONTREE_HOME/mcp/cache.db` (typically `~/.config/contree/mcp/cache.db`) |
| `--cache-prune-days` | `60` |
## Client Configuration Examples
With credentials stored in `~/.config/contree/auth.ini`, MCP client
configs are minimal:
### Claude Code
```bash theme={null}
claude mcp add --transport stdio contree -- $(which uvx) contree-mcp
```
### HTTP Mode
For network access from other machines:
```bash theme={null}
contree-mcp --mode http --http-port 9452 --http-listen 0.0.0.0
```
Visit `http://localhost:9452/` for interactive documentation with setup guides, tool reference, and best practices.

The HTTP interface showing Setup, Instructions, Tools, Resources, and Guides tabs.
## Manual Installation
```bash theme={null}
# Using uv
uv pip install contree-mcp
# Using pip
pip install contree-mcp
# Container environments (PEP 668)
pip install --break-system-packages contree-mcp
```
# Integration
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/integration/index
Setting up and configuring Contree MCP.
> [card] [Configuration](./configuration)
> [card] [Troubleshooting](./troubleshooting)
## Quick Setup
See the [Quickstart](../quickstart) for basic setup instructions.
## Configuration Options
Credentials live in a profile-based `auth.ini` shared with
[`contree-cli`](https://docs.contree.dev/cli/tutorial/installation.html);
install the CLI and run `contree auth` once to populate it. The MCP
server then reads the active profile automatically.
| Option | Environment Variable | Default |
| - | - | - |
| - | `CONTREE_HOME` | `$XDG_CONFIG_HOME/contree` (typically `~/.config/contree`) |
| `--profile` | `CONTREE_PROFILE` | active profile from `auth.ini` |
| `--token` | `CONTREE_TOKEN` | from profile |
| `--url` | `CONTREE_URL` | from profile |
| `--project` | `CONTREE_PROJECT` | from profile (IAM auth only) |
| `--mode` | - | `stdio` |
| `--http-port` | - | `9452` |
| `--log-level` | - | `warning` |
| `--version` / `-V` | - | print User-Agent and exit |
Resolution priority for credentials: \*\*CLI flag > environment variable
> stored profile\*\*.
## Supported Clients
* Claude Code
* Claude Desktop
* OpenAI Codex CLI
* Any MCP-compatible client
## See Also
* [Configuration](./configuration) - Detailed config options
* [Troubleshooting](./troubleshooting) - Common issues
# Troubleshooting
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/integration/troubleshooting
Common issues and solutions.
## Connection Issues
### “No API token configured” Error
**Cause**: No active profile in `auth.ini` and no `--token` /
`CONTREE_TOKEN` override.
**Solution (recommended):** install `contree-cli` and run `contree auth`:
```bash theme={null}
uv tool install contree-cli # or: pip install contree-cli
contree auth # interactive setup
```
This writes `~/.config/contree/auth.ini`. The MCP server reads it
automatically.
For a one-off override:
```bash theme={null}
export CONTREE_TOKEN="your-token"
export CONTREE_URL="https://api.tokenfactory.nebius.com/sandboxes"
export CONTREE_PROJECT="your-nebius-project-id" # only for IAM auth
```
### Server logs `Ignoring NEBIUS_API_KEY: NEBIUS_AI_PROJECT is not set`
**Cause**: Your shell has `NEBIUS_API_KEY` set (typically for the
Nebius SDK or terraform provider) but no `NEBIUS_AI_PROJECT`. The MCP
server treats this as an incomplete IAM credential and falls back to
the active profile from `auth.ini`. This is *not* an error — it’s a
deliberate guard against an ambient env var hijacking your saved
profile.
**Solution**: nothing to do if you wanted the profile to load. If you
*meant* to authenticate via env, also export `NEBIUS_AI_PROJECT` (or
use the MCP-specific `CONTREE_TOKEN` / `CONTREE_PROJECT`, which layer
per-field on top of the profile and don’t have this guard).
### “IAM auth requires a project ID” Error
**Cause**: The active profile (or the env/CLI overrides) is IAM-typed
but no project ID was supplied.
**Solution**: either add `project = ...` under the matching
`[profile:]` section, set `CONTREE_PROJECT`, or pass
`--project `. For legacy JWT deployments, set `type = jwt` in the
profile — projects aren’t needed there.
### “Connection refused” Error
**Cause**: Server not reachable or wrong URL.
**Solution**: Verify the URL in the active profile (or pass
`--url`/`CONTREE_URL`):
```bash theme={null}
export CONTREE_URL="https://api.tokenfactory.nebius.com/sandboxes"
```
### “Forbidden” / Missing Permissions
**Cause**: The active token doesn’t have the permission your call
needs (`spawn`, `import`, `set_image_tag`, `cancel`, …).
**Solution**: ask the `whoami` tool to enumerate what’s available:
```json theme={null}
{"tool": "whoami"}
```
If a permission is `false`, the only recourse is a token with
different grants — the MCP server cannot escalate.
## Tool Errors
### “Image not found”
**Cause**: Invalid image UUID or tag.
**Solutions**:
1. Check with `list_images`
2. Ensure the UUID is correct
3. For tags, use `tag:` prefix: `"image": "tag:python:3.11"`
### “Directory state not found”
**Cause**: Invalid `directory_state_id` or expired session.
**Solution**: Call `rsync` again to get a new `directory_state_id`.
### “Operation timed out”
**Cause**: Command exceeded timeout.
**Solution**: Increase the timeout:
```json theme={null}
{"tool": "run", "args": {
"command": "...",
"timeout": 600
}}
```
## Performance Issues
### Slow File Sync
**Cause**: Large files or too many files.
**Solutions**:
1. Use exclusions:
```json theme={null}
{"exclude": ["node_modules", ".git", "__pycache__", "*.log"]}
```
2. Sync only what you need
3. Use glob patterns for specific files
### Commands Taking Long to Start
**Cause**: VM startup time (\~2-5 seconds).
**Solutions**:
1. Batch operations when possible
2. Use async for parallel operations
3. Reuse images with dependencies pre-installed
## Debugging
### Enable Debug Logging
Pass `--log-level debug` to the server:
```bash theme={null}
contree-mcp --log-level debug ...
```
In an MCP client config that spawns the server, append the flag to
`args`:
```json theme={null}
{
"mcpServers": {
"contree": {
"command": "uvx",
"args": ["contree-mcp", "--log-level", "debug"]
}
}
}
```
### Confirm the Installed Version
`contree-mcp --version` (or `-V`) prints the User-Agent the server
emits on every backend call. Useful when triaging which build is
actually wired into your client:
```bash theme={null}
$ contree-mcp --version
contree-mcp/0.1.1 Python/3.13.0.final.0 Linux-6.5.0-arm64
```
### Check Operation Status
For async operations:
```json theme={null}
{"tool": "get_operation", "args": {"operation_id": "op-..."}}
```
### View Image Lineage
To understand how an image was created:
```
contree://image/your-image-uuid/lineage
```
## Getting Help
* [GitHub Issues](https://github.com/nebius/contree/issues)
* Check the [Concepts](../concepts/index) for understanding
* See [Patterns](../patterns) for best practices
# Patterns
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/patterns
Common workflows and mistakes to avoid.
## Run Python Script with Local Files
```json theme={null}
// 1. Check for image
{"tool": "list_images", "args": {"tag_prefix": "python"}}
// 2. Import if needed
{"tool": "import_image", "args": {"registry_url": "docker://python:3.11-slim"}}
// 3. Sync files
{"tool": "rsync", "args": {
"source": "/project", "destination": "/app",
"exclude": ["__pycache__", ".git", ".venv"]
}}
// 4. Run
{"tool": "run", "args": {
"command": "python /app/main.py",
"image": "img-uuid",
"directory_state_id": "ds-xxx"
}}
```
## Install Dependencies and Save
```json theme={null}
// Save changes with disposable=false
{"tool": "run", "args": {
"command": "pip install numpy pandas",
"image": "tag:python:3.11",
"disposable": false
}}
// Returns: {"result_image": "img-with-deps"}
// Use new image for subsequent runs
{"tool": "run", "args": {
"command": "python /app/train.py",
"image": "img-with-deps",
"directory_state_id": "ds-xxx"
}}
```
**Mistake**: Forgetting `disposable=false` means changes are discarded.
## Parallel Execution
```json theme={null}
// Launch async
{"tool": "run", "args": {"command": "python exp_a.py", "image": "img", "wait": false}}
{"tool": "run", "args": {"command": "python exp_b.py", "image": "img", "wait": false}}
// Wait for all
{"tool": "wait_operations", "args": {"operation_ids": ["op-1", "op-2"]}}
```
**Mistake**: Using `wait=false` for single operations adds unnecessary complexity.
## Build and Extract Artifact
```json theme={null}
// Build with disposable=false
{"tool": "run", "args": {
"command": "cargo build --release",
"image": "tag:rust:1.75",
"directory_state_id": "ds-project",
"disposable": false,
"timeout": 300
}}
// Download result
{"tool": "download", "args": {
"image": "img-built",
"path": "/app/target/release/myapp",
"destination": "./myapp",
"executable": true
}}
```
## Rollback After Failure
```
// View lineage
contree://image/broken-uuid/lineage
// Returns: {"parent": {"image": "working-parent-uuid"}}
// Continue from working state
{"tool": "run", "args": {
"command": "python fixed.py",
"image": "working-parent-uuid"
}}
```
***
## Common Mistakes
### Re-syncing unchanged files
**Wrong**: Calling `rsync` before every `run`
**Right**: Sync once, reuse `directory_state_id` for all runs. Re-sync only when files change.
### Importing without checking
**Wrong**: `import_image` immediately
**Right**: `list_images` first to check if image exists
### Chaining commands in one string
**Wrong**:
```json theme={null}
{"command": "apt update && apt install python && pip install numpy && python train.py"}
```
**Right**: Run each step separately with `disposable=false`. Enables rollback if later steps fail.
### Using tags for one-off images
**Wrong**: Creating tags for temporary experiments
**Right**: Use UUIDs directly. Tags are for frequently-reused images.
### Not excluding build artifacts
**Wrong**: rsync without exclusions
**Right**: Always exclude `__pycache__`, `.git`, `.venv`, `node_modules`, `target`, `dist`
### Ignoring filesystem\_changed
When `filesystem_changed: false`, `result_image` equals input image - no new snapshot was created.
# build-project
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/build-project
Build a project: install dependencies and run tests.
## Description
The `build-project` prompt provides instructions for a standard build workflow: sync files, install dependencies, and run tests.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `source` | string | Yes | - | Local directory path to sync |
| `install_cmd` | string | No | `pip install -e .` | Dependency installation command |
| `test_cmd` | string | No | `pytest` | Test execution command |
## Generated Instructions
When invoked with:
```json theme={null}
{
"source": "/home/user/myproject",
"install_cmd": "pip install -e '.[dev]'",
"test_cmd": "pytest -v tests/"
}
```
Returns:
```markdown theme={null}
Build and test the project:
1. Sync `/home/user/myproject` to `/app` using `rsync`
2. Import `python:3.11-slim` if needed
3. Install dependencies with `pip install -e '.[dev]'` (use `disposable=false`)
4. Run tests with `pytest -v tests/` on the result image
5. Report test results
```
## Example Usage
### Standard Python Project
```json theme={null}
{
"prompt": "build-project",
"args": {
"source": "/path/to/project"
}
}
```
### With Custom Commands
```json theme={null}
{
"prompt": "build-project",
"args": {
"source": "/path/to/project",
"install_cmd": "pip install -r requirements.txt",
"test_cmd": "python -m pytest --cov=src tests/"
}
}
```
### Poetry Project
```json theme={null}
{
"prompt": "build-project",
"args": {
"source": "/path/to/project",
"install_cmd": "pip install poetry && poetry install",
"test_cmd": "poetry run pytest"
}
}
```
## Implementation Notes
The agent should:
1. Sync files with `rsync`:
```json theme={null}
{
"source": "",
"destination": "/app",
"exclude": ["__pycache__", ".git", ".venv", "node_modules"]
}
```
2. Check for Python image, import if needed
3. Install dependencies with `run`:
```json theme={null}
{
"command": "",
"image": "tag:python:3.11-slim",
"directory_state_id": "",
"cwd": "/app",
"disposable": false
}
```
4. Run tests with `run`:
```json theme={null}
{
"command": "",
"image": "",
"directory_state_id": "",
"cwd": "/app"
}
```
5. Report test results (exit code, stdout, stderr)
## See Also
* [multi-stage-build](./multi-stage-build) - Complex builds with checkpoints
* [sync-and-run](./sync-and-run) - Simple file sync and execution
* [install-packages](./install-packages) - Just install packages
# debug-failure
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/debug-failure
Diagnose a failed command and suggest fixes.
## Description
The `debug-failure` prompt provides a systematic approach to diagnosing and fixing failed container operations.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `operation_id` | string | Yes | - | Operation ID to debug |
## Generated Instructions
When invoked with:
```json theme={null}
{
"operation_id": "op-abc-123-def"
}
```
Returns:
```markdown theme={null}
Debug the failed operation `op-abc-123-def`:
1. Use `get_operation` to retrieve the operation result
2. Analyze:
- `exit_code`: Non-zero indicates command failure
- `stderr`: Contains error messages and stack traces
- `stdout`: May contain partial output or clues
- `timed_out`: If true, command exceeded timeout
3. Common issues to check:
- Missing files (file not found errors)
- Missing dependencies (import errors, command not found)
- Permission issues (though commands run as root)
- Timeout exceeded (increase timeout or optimize command)
4. Suggest specific fixes based on the error
5. If needed, re-run with fixes applied
```
## Example Usage
### Debug Build Failure
```json theme={null}
{
"prompt": "debug-failure",
"args": {
"operation_id": "op-build-failed-123"
}
}
```
### Debug Test Failure
```json theme={null}
{
"prompt": "debug-failure",
"args": {
"operation_id": "op-test-run-456"
}
}
```
## Common Error Patterns
### Missing Dependencies
**Symptom:** `ModuleNotFoundError` or `command not found`
**Solution:** Install missing packages with `install-packages` or use a prepared environment.
### File Not Found
**Symptom:** `No such file or directory`
**Solution:** Verify path with `list_files`, ensure files are synced with `rsync`.
### Timeout
**Symptom:** `timed_out: true`
**Solution:** Increase `timeout` parameter or break into smaller operations.
### Permission Denied
**Symptom:** `Permission denied`
**Solution:** Commands run as root, so check if file exists and is accessible.
## Implementation Notes
The agent should:
1. Retrieve operation with `get_operation`:
```json theme={null}
{"operation_id": ""}
```
2. Analyze the result:
* Check `exit_code` (0 = success, non-zero = failure)
* Read `stderr` for error messages
* Check `timed_out` flag
* Review `stdout` for partial output
3. Diagnose based on error patterns:
* Import errors → missing packages
* File not found → path issues
* Timeout → need more time or optimization
4. Suggest and implement fixes
## See Also
* [inspect-image](./inspect-image) - Explore image contents
* [Error Handling Guide](../resources) - Common errors and solutions
* [build-project](./build-project) - Retry build after fix
# Prompts Reference
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/index
MCP prompts for common Contree workflows. Prompts provide structured instructions that guide AI agents through multi-step tasks.
> [card] [prepare-environment](./prepare-environment)
> [card] [run-python](./run-python)
> [card] [run-shell](./run-shell)
> [card] [sync-and-run](./sync-and-run)
> [card] [install-packages](./install-packages)
> [card] [parallel-tasks](./parallel-tasks)
> [card] [build-project](./build-project)
> [card] [debug-failure](./debug-failure)
> [card] [inspect-image](./inspect-image)
> [card] [multi-stage-build](./multi-stage-build)
## Quick Reference
| Prompt | Description | Key Parameters |
| - | - | - |
| [prepare-environment](./prepare-environment) | Prepare container environment with CHECK-PREPARE-EXECUTE flow | `task`, `base`, `project`, `packages` |
| [run-python](./run-python) | Run Python code in isolated container | `code` |
| [run-shell](./run-shell) | Run shell command in isolated container | `command`, `image` |
| [sync-and-run](./sync-and-run) | Sync local files and run command | `source`, `command`, `image` |
| [install-packages](./install-packages) | Install packages and create reusable image | `packages`, `image` |
| [parallel-tasks](./parallel-tasks) | Run multiple tasks in parallel | `tasks`, `image` |
| [build-project](./build-project) | Build project: install deps and run tests | `source`, `install_cmd`, `test_cmd` |
| [debug-failure](./debug-failure) | Diagnose failed operation | `operation_id` |
| [inspect-image](./inspect-image) | Explore container image contents | `image` |
| [multi-stage-build](./multi-stage-build) | Multi-stage build with rollback points | `source`, `install_cmd`, `build_cmd`, `test_cmd` |
## Using Prompts
### With MCP Clients
MCP-compatible clients can invoke prompts directly:
```json theme={null}
{
"prompt": "prepare-environment",
"args": {
"task": "Train ML model",
"base": "python:3.11-slim",
"packages": "numpy pandas scikit-learn"
}
}
```
### Prompt Output
Prompts return structured instructions that guide the agent through:
1. **Step-by-step workflows** - Ordered operations with clear dependencies
2. **Tool selection** - Which Contree tools to use and when
3. **Parameter guidance** - Correct values for each tool call
4. **Best practices** - Following the CHECK-PREPARE-EXECUTE pattern
## Categories
### Environment Setup
* [prepare-environment](./prepare-environment) - Full workflow with environment reuse
* [install-packages](./install-packages) - Install and tag for reuse
### Code Execution
* [run-python](./run-python) - Quick Python execution
* [run-shell](./run-shell) - Shell command execution
* [sync-and-run](./sync-and-run) - Local files + execution
### Building and Testing
* [build-project](./build-project) - Standard build + test workflow
* [multi-stage-build](./multi-stage-build) - Complex builds with checkpoints
### Operations
* [parallel-tasks](./parallel-tasks) - Concurrent execution
* [debug-failure](./debug-failure) - Error diagnosis
* [inspect-image](./inspect-image) - Image exploration
# inspect-image
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/inspect-image
Explore the contents of a container image.
## Description
The `inspect-image` prompt provides instructions for thoroughly examining a container image to understand its contents, installed software, and configuration.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or tag to inspect |
## Generated Instructions
When invoked with:
```json theme={null}
{
"image": "tag:python:3.11-slim"
}
```
Returns:
```markdown theme={null}
Inspect the container image `tag:python:3.11-slim`:
1. Use `run` with the image to explore:
- `ls -la /` - List root directory contents
- `cat /etc/os-release` - Check OS version
- `which python pip node` - Find installed tools
- `pip list` or `dpkg -l` - List installed packages
2. Report findings:
- Operating system and version
- Available languages/runtimes
- Key installed packages
- Notable files or directories
3. Use `disposable=true` (default) since we're just exploring
```
## Example Usage
### Explore Python Image
```json theme={null}
{
"prompt": "inspect-image",
"args": {
"image": "tag:python:3.11-slim"
}
}
```
### Explore Custom Image
```json theme={null}
{
"prompt": "inspect-image",
"args": {
"image": "abc123-def456-uuid"
}
}
```
### Explore Alpine
```json theme={null}
{
"prompt": "inspect-image",
"args": {
"image": "tag:alpine:latest"
}
}
```
## Implementation Notes
The agent should use the free inspection tools first, then `run` for dynamic queries:
1. **Use `list_files` first** (free, no VM):
```json theme={null}
{"image": "", "path": "/"}
{"image": "", "path": "/etc"}
{"image": "", "path": "/usr/local/bin"}
```
2. **Use `read_file` for config files** (free, no VM):
```json theme={null}
{"image": "", "path": "/etc/os-release"}
```
3. **Use `run` for dynamic queries** (spawns VM):
```json theme={null}
{"command": "pip list", "image": ""}
{"command": "which python pip node", "image": ""}
```
4. Report findings in a structured format:
* OS: Debian 12 / Alpine 3.18 / etc.
* Languages: Python 3.11, Node.js 20, etc.
* Key packages: numpy, flask, etc.
* Notable directories: /app, /data, etc.
## See Also
* [list\_files](../tools/list_files) - List directory contents (free)
* [read\_file](../tools/read_file) - Read file contents (free)
* [debug-failure](./debug-failure) - Debug after inspection
# install-packages
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/install-packages
Install packages and create a reusable image.
## Description
The `install-packages` prompt provides instructions for installing packages in a container and tagging the result for future reuse. It follows the prepare-and-tag pattern.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `packages` | string | Yes | - | Packages to install (space-separated) |
| `image` | string | No | `python:3.11-slim` | Base image to use |
## Generated Instructions
When invoked with:
```json theme={null}
{
"packages": "flask gunicorn",
"image": "python:3.11-slim"
}
```
Returns:
```markdown theme={null}
Install packages in a container:
1. Check if base image `tag:python:3.11-slim` exists with `list_images`
2. If not, import it with `import_image`
3. Run `pip install flask gunicorn` with `disposable=false` to save the image
4. Tag the result for reuse (e.g., `claude/common/python/custom-deps:3.11`)
The returned `result_image` can be used for subsequent commands.
```
## Example Usage
### Python Packages
```json theme={null}
{
"prompt": "install-packages",
"args": {
"packages": "numpy pandas matplotlib scikit-learn"
}
}
```
### Web Framework Stack
```json theme={null}
{
"prompt": "install-packages",
"args": {
"packages": "fastapi uvicorn sqlalchemy alembic"
}
}
```
### System Packages
For system packages, use a different base image and package manager:
```json theme={null}
{
"prompt": "install-packages",
"args": {
"packages": "curl wget git",
"image": "ubuntu:22.04"
}
}
```
Note: For Ubuntu, the agent should adapt to use `apt install` instead of `pip install`.
## Implementation Notes
The agent should:
1. Check if base image exists with `list_images`
2. Import if needed with `import_image`
3. Install packages with `run`:
```json theme={null}
{
"command": "pip install ",
"image": "tag:",
"disposable": false
}
```
4. Tag the result with `set_tag`:
```json theme={null}
{
"image_uuid": "",
"tag": "common//"
}
```
## See Also
* [prepare-environment](./prepare-environment) - Full environment preparation
* [build-project](./build-project) - Build with dependencies
* [multi-stage-build](./multi-stage-build) - Complex multi-stage builds
# multi-stage-build
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/multi-stage-build
Multi-stage build with rollback points.
## Description
The `multi-stage-build` prompt provides instructions for complex builds with multiple stages, each creating a checkpoint for potential rollback.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `source` | string | Yes | - | Local directory path to sync |
| `install_cmd` | string | No | `pip install -e .` | Dependency installation command |
| `build_cmd` | string | No | `python -m build` | Build command |
| `test_cmd` | string | No | `pytest` | Test command |
## Generated Instructions
When invoked with:
```json theme={null}
{
"source": "/home/user/project",
"install_cmd": "pip install -e '.[dev]'",
"build_cmd": "python -m build",
"test_cmd": "pytest -v"
}
```
Returns:
```markdown theme={null}
Execute a multi-stage build with rollback checkpoints:
Source: `/home/user/project`
**Stage 1: Setup Base**
1. Check if `tag:python:3.11-slim` exists, import if needed
2. Sync source files with `rsync`
**Stage 2: Install Dependencies** (checkpoint: `deps-installed`)
1. Run `pip install -e '.[dev]'` with `disposable=false`
2. Save `result_image` as rollback point
3. If this fails, report error and stop
**Stage 3: Build** (checkpoint: `build-complete`)
1. Run `python -m build` on deps image with `disposable=false`
2. Save `result_image` as rollback point
3. If this fails, can rollback to deps-installed image
**Stage 4: Test**
1. Run `pytest -v` on build image (disposable=true for tests)
2. Report test results
3. If tests fail, can rollback to build-complete or deps-installed
**Rollback Strategy:**
- Keep track of each stage's `result_image` UUID
- On failure, report which checkpoint to resume from
- Previous checkpoints remain valid for retry
```
## Example Usage
### Python Package Build
```json theme={null}
{
"prompt": "multi-stage-build",
"args": {
"source": "/path/to/package"
}
}
```
### Custom Build Pipeline
```json theme={null}
{
"prompt": "multi-stage-build",
"args": {
"source": "/path/to/project",
"install_cmd": "pip install poetry && poetry install",
"build_cmd": "poetry build",
"test_cmd": "poetry run pytest --cov"
}
}
```
### Rust Project
```json theme={null}
{
"prompt": "multi-stage-build",
"args": {
"source": "/path/to/rust-project",
"install_cmd": "cargo fetch",
"build_cmd": "cargo build --release",
"test_cmd": "cargo test"
}
}
```
## Stage Details
### Stage 1: Setup Base
* Ensures base image exists
* Syncs source files
* No checkpoint needed (base image is the checkpoint)
### Stage 2: Install Dependencies
* Runs install command with `disposable=false`
* Saves result as `deps-installed` checkpoint
* **Rollback target:** If install fails, fix and retry from base
### Stage 3: Build
* Runs build command with `disposable=false`
* Saves result as `build-complete` checkpoint
* **Rollback target:** If build fails, can retry from `deps-installed`
### Stage 4: Test
* Runs tests with `disposable=true` (no need to save test artifacts)
* Reports results
* **Rollback targets:** Can retry from `build-complete` or `deps-installed`
## Implementation Notes
The agent should track checkpoints:
```
base_image = "tag:python:3.11-slim"
|
v
deps_image = run(install_cmd, disposable=false).result_image
|
v
build_image = run(build_cmd, image=deps_image, disposable=false).result_image
|
v
test_result = run(test_cmd, image=build_image, disposable=true)
```
On failure at any stage, report:
* Which stage failed
* Available rollback points
* How to resume
## See Also
* [build-project](./build-project) - Simpler build workflow
* [debug-failure](./debug-failure) - Debug build failures
* [State Management Guide](../resources) - Rollback patterns
# parallel-tasks
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/parallel-tasks
Run multiple tasks in parallel.
## Description
The `parallel-tasks` prompt provides instructions for executing multiple independent tasks concurrently using Contree’s async execution capabilities.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `tasks` | string | Yes | - | Tasks to run (one per line) |
| `image` | string | No | `python:3.11-slim` | Base image to use |
## Generated Instructions
When invoked with:
```json theme={null}
{
"tasks": "python test_unit.py\npython test_integration.py\npython test_e2e.py",
"image": "python:3.11-slim"
}
```
Returns:
```markdown theme={null}
Run these tasks in parallel:
Tasks (one per line):
python test_unit.py
python test_integration.py
python test_e2e.py
Steps:
1. Ensure image `tag:python:3.11-slim` exists (import if needed)
2. Call `run` for each task with `wait=false` - make parallel tool calls
3. Collect all `operation_id` values
4. Use `wait_operations` to wait for all to complete
5. Report results from each task
```
## Example Usage
### Parallel Tests
```json theme={null}
{
"prompt": "parallel-tasks",
"args": {
"tasks": "pytest tests/unit/\npytest tests/integration/\npytest tests/e2e/"
}
}
```
### Multiple Experiments
```json theme={null}
{
"prompt": "parallel-tasks",
"args": {
"tasks": "python train.py --lr 0.001\npython train.py --lr 0.01\npython train.py --lr 0.1"
}
}
```
### Build Multiple Targets
```json theme={null}
{
"prompt": "parallel-tasks",
"args": {
"tasks": "cargo build --target x86_64-unknown-linux-gnu\ncargo build --target aarch64-unknown-linux-gnu",
"image": "rust:1.75"
}
}
```
## Implementation Notes
The agent should:
1. Ensure the image exists (check with `list_images`, import if needed)
2. Launch all tasks in parallel with `wait=false`:
```json theme={null}
// Make these calls in parallel
{"command": "python test_unit.py", "image": "tag:python:3.11-slim", "wait": false}
{"command": "python test_integration.py", "image": "tag:python:3.11-slim", "wait": false}
{"command": "python test_e2e.py", "image": "tag:python:3.11-slim", "wait": false}
```
3. Collect the returned `operation_id` values
4. Wait for all with `wait_operations`:
```json theme={null}
{"operation_ids": ["op-1", "op-2", "op-3"]}
```
5. Process and report results from each operation
## See Also
* [build-project](./build-project) - Sequential build workflow
* [debug-failure](./debug-failure) - Debug failed operations
* [Async Guide](../resources) - Async execution patterns
# prepare-environment
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/prepare-environment
Prepare a container environment for a task, checking for existing images first.
## Description
The `prepare-environment` prompt implements the recommended CHECK-PREPARE-EXECUTE workflow:
1. **CHECK** - Search for existing prepared environments
2. **PREPARE** - Import and configure if not found
3. **EXECUTE** - Run the task with the prepared environment
This ensures maximum reuse of prepared images and follows Contree best practices.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `task` | string | Yes | - | Description of the task to perform |
| `base` | string | No | `python:3.11-slim` | Base image to use |
| `project` | string | No | `None` | Project name for scoping (uses `common` if not set) |
| `packages` | string | No | `None` | Packages to install (space-separated) |
## Generated Instructions
When invoked with:
```json theme={null}
{
"task": "Train ML model",
"base": "python:3.11-slim",
"packages": "numpy pandas scikit-learn"
}
```
Returns instructions like:
````markdown theme={null}
Prepare an environment for: Train ML model
**Step 1: CHECK for Existing Environment**
Search for prepared environments:
```json
// list_images
{"tag_prefix": "common/"}
````
If a suitable environment exists (has required packages), skip to Step 3.
**Step 2: PREPARE Environment (if not found)**
2a. Import base image:
```json theme={null}
// import_image
{"registry_url": "docker://docker.io/python:3.11-slim"}
```
2b. Install dependencies with `disposable=false`:
```json theme={null}
// run
{
"command": "pip install numpy pandas scikit-learn",
"image": "",
"disposable": false
}
```
2c. Tag for reuse:
```json theme={null}
// set_tag
{"image_uuid": "", "tag": "common/numpy-env/python:3.11-slim"}
```
**Step 3: EXECUTE Task**
Use the prepared environment:
```json theme={null}
// run
{"command": "", "image": "tag:common/numpy-env/python:3.11-slim"}
```
```
## Tag Generation
The prompt automatically generates a tag following the convention:
```
\{scope}/\{purpose}/\{base}:\{tag}
````
- **scope**: Uses `project` parameter if provided, otherwise `common`
- **purpose**: Derived from first package name (e.g., `numpy-env`) or `custom-env`
- **base:tag**: From `base` parameter
## Example Usage
### ML Development Environment
```json
{
"prompt": "prepare-environment",
"args": {
"task": "Run data analysis notebook",
"packages": "jupyter pandas matplotlib seaborn"
}
}
````
### Project-Specific Environment
```json theme={null}
{
"prompt": "prepare-environment",
"args": {
"task": "Run API tests",
"project": "myproject",
"packages": "pytest requests httpx"
}
}
```
Generates tag: `myproject/pytest-env/python:3.11-slim`
### Custom Base Image
```json theme={null}
{
"prompt": "prepare-environment",
"args": {
"task": "Compile Rust project",
"base": "rust:1.75-slim"
}
}
```
## See Also
* [install-packages](./install-packages) - Simpler package installation
* [build-project](./build-project) - Full build workflow
* [Tagging Convention](../resources) - Tag naming guide
# run-python
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/run-python
Run Python code in an isolated container.
## Description
The `run-python` prompt provides a simple way to execute Python code in a container. It handles image selection and provides clear instructions for the execution.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `code` | string | Yes | - | Python code to execute |
## Generated Instructions
When invoked with:
```json theme={null}
{
"code": "import sys\nprint(f'Python {sys.version}')"
}
```
Returns:
````markdown theme={null}
Run this Python code in a container:
```python
import sys
print(f'Python {sys.version}')
````
Use `run` with `tag:python:3.11-slim` image. If the image doesn’t exist, import it first.
````
## Example Usage
### Simple Calculation
```json
{
"prompt": "run-python",
"args": {
"code": "print(sum(range(100)))"
}
}
````
### Multi-line Script
```json theme={null}
{
"prompt": "run-python",
"args": {
"code": "def factorial(n):\n return 1 if n <= 1 else n * factorial(n-1)\n\nfor i in range(10):\n print(f'{i}! = {factorial(i)}')"
}
}
```
### With Package Usage
```json theme={null}
{
"prompt": "run-python",
"args": {
"code": "import numpy as np\nprint(np.random.rand(5))"
}
}
```
Note: If the code requires packages not in the base image, you’ll need to install them first using `install-packages` or `prepare-environment`.
## Implementation Notes
The agent should:
1. Check if `tag:python:3.11-slim` exists with `list_images`
2. If not found, import it with `import_image`
3. Execute the code with `run`:
```json theme={null}
{
"command": "python -c ''",
"image": "tag:python:3.11-slim"
}
```
## See Also
* [run-shell](./run-shell) - Run shell commands
* [sync-and-run](./sync-and-run) - Run with local files
* [install-packages](./install-packages) - Install dependencies first
# run-shell
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/run-shell
Run a shell command in an isolated container.
## Description
The `run-shell` prompt provides a simple way to execute shell commands in a container with a specified base image.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `command` | string | Yes | - | Shell command to execute |
| `image` | string | No | `ubuntu:22.04` | Base image to use |
## Generated Instructions
When invoked with:
```json theme={null}
{
"command": "uname -a && cat /etc/os-release",
"image": "alpine:latest"
}
```
Returns:
````markdown theme={null}
Run this command in a container:
```bash
uname -a && cat /etc/os-release
````
Use image `tag:alpine:latest`. If the image doesn’t exist, import it first with `import_image`.
````
## Example Usage
### Basic Command
```json
{
"prompt": "run-shell",
"args": {
"command": "ls -la /etc"
}
}
````
### With Specific Image
```json theme={null}
{
"prompt": "run-shell",
"args": {
"command": "go version",
"image": "golang:1.21"
}
}
```
### System Information
```json theme={null}
{
"prompt": "run-shell",
"args": {
"command": "df -h && free -m && nproc"
}
}
```
## Implementation Notes
The agent should:
1. Check if the specified image exists with `list_images`
2. If not found, import it with `import_image`
3. Execute the command with `run`:
```json theme={null}
{
"command": "",
"image": "tag:"
}
```
## See Also
* [run-python](./run-python) - Run Python code
* [sync-and-run](./sync-and-run) - Run with local files
* [inspect-image](./inspect-image) - Explore image contents
# sync-and-run
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/prompts/sync-and-run
Sync local files to container and run a command.
## Description
The `sync-and-run` prompt provides instructions for syncing local project files to a container and executing a command. It handles the rsync workflow with proper exclusions.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `source` | string | Yes | - | Local directory path to sync |
| `command` | string | Yes | - | Command to run after syncing |
| `image` | string | No | `python:3.11-slim` | Base image to use |
## Generated Instructions
When invoked with:
```json theme={null}
{
"source": "/home/user/myproject",
"command": "python main.py",
"image": "python:3.11-slim"
}
```
Returns:
```markdown theme={null}
Sync files and run command:
1. Use `rsync` to sync `/home/user/myproject` to `/app` in the container
- Exclude: `__pycache__`, `.git`, `node_modules`, `.venv`
2. Use `run` with the returned `directory_state_id`
- Image: `tag:python:3.11-slim` (import if needed)
- Command: `python main.py`
- Working directory: `/app`
```
## Example Usage
### Python Project
```json theme={null}
{
"prompt": "sync-and-run",
"args": {
"source": "/path/to/project",
"command": "pytest tests/"
}
}
```
### Node.js Project
```json theme={null}
{
"prompt": "sync-and-run",
"args": {
"source": "/path/to/webapp",
"command": "npm test",
"image": "node:20-slim"
}
}
```
### Build and Run
```json theme={null}
{
"prompt": "sync-and-run",
"args": {
"source": "/path/to/rust-project",
"command": "cargo build --release && ./target/release/myapp",
"image": "rust:1.75"
}
}
```
## Implementation Notes
The agent should:
1. Use `rsync` to sync files:
```json theme={null}
{
"source": "",
"destination": "/app",
"exclude": ["__pycache__", ".git", "node_modules", ".venv"]
}
```
2. Check if the image exists, import if needed
3. Execute with `run`:
```json theme={null}
{
"command": "",
"image": "tag:",
"directory_state_id": "",
"cwd": "/app"
}
```
## See Also
* [build-project](./build-project) - Full build workflow
* [run-python](./run-python) - Simple Python execution
* [run-shell](./run-shell) - Simple shell execution
# Quickstart
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/quickstart
Run your first container in 5 minutes.
## Prerequisites
* An MCP-compatible client (Claude Code, Claude Desktop, or OpenAI Codex CLI)
* A Contree API token
### Getting an API Token
Contree is in **Early Access**. To get an API token, fill out the request form at [contree.dev](https://contree.dev).
## Installation
### Step 1: Authenticate
`contree-mcp` reads the same `auth.ini` that
[`contree-cli`](https://docs.contree.dev/cli/tutorial/installation.html)
writes, so a single login covers both tools.
**Recommended:** install `contree-cli` and run `contree auth`:
```bash theme={null}
uv tool install contree-cli # or: pip install contree-cli
contree auth # interactive setup
```
This writes `~/.config/contree/auth.ini` (mode `0600`). The MCP server
picks it up automatically.
If you prefer to write the file by hand:
```ini theme={null}
[DEFAULT]
profile = default
[profile:default]
type = iam
url = https://api.tokenfactory.nebius.com/sandboxes
token =
project =
```
For the legacy JWT flow (`contree.dev`), use:
```ini theme={null}
[profile:default]
type = jwt
url = https://contree.dev
token =
```
To switch between profiles later: `contree auth switch `, or
pass `--profile ` / `CONTREE_PROFILE=` to `contree-mcp`.
### Step 2: Configure Your MCP Client
> [tab] Claude Code
>
> ```bash theme={null}
> claude mcp add --transport stdio contree -- $(which uvx) contree-mcp
> ```
>
> Restart Claude Code or run `/mcp` to verify.
> [tab] Claude Desktop
>
> Add to config file:
>
> * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
> * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
>
> ```json theme={null}
> {
> "mcpServers": {
> "contree": {
> "command": "uvx",
> "args": ["contree-mcp"]
> }
> }
> }
> ```
> [tab] OpenAI Codex CLI
>
> Add to `~/.codex/config.toml`:
>
> ```toml theme={null}
> [mcp_servers.contree]
> command = "uvx"
> args = ["contree-mcp"]
> ```
> [!NOTE]
>
> You can also pass credentials via environment variables (`CONTREE_TOKEN`,
> `CONTREE_URL`, `CONTREE_PROJECT`, `CONTREE_PROFILE`) or CLI flags
> (`--token`, `--url`, `--project`, `--profile`). These are useful for
> ephemeral overrides — but tokens passed via env may show up in process
> listings, so for routine use prefer the `auth.ini` profile written by
> `contree auth`.
## Your First Container
### Step 1: Check Available Images
```json theme={null}
{"tool": "list_images", "args": {"tag_prefix": "python", "limit": 5}}
```
If you don’t have any Python images, import one:
```json theme={null}
{"tool": "import_image", "args": {"registry_url": "docker://python:3.11-slim"}}
```
Response:
```json theme={null}
{
"result_image": "abc123-def456-...",
"state": "SUCCESS"
}
```
### Step 2: Run a Command
```json theme={null}
{
"tool": "run",
"args": {
"command": "python -c \"print('Hello from Contree!')\"",
"image": "abc123-def456-..."
}
}
```
Response:
```json theme={null}
{
"exit_code": 0,
"stdout": "Hello from Contree!\n",
"state": "SUCCESS"
}
```
### Step 3: Run with Local Files
First, sync your files:
```json theme={null}
{
"tool": "rsync",
"args": {
"source": "/path/to/your/project",
"destination": "/app",
"exclude": ["__pycache__", ".git", ".venv"]
}
}
```
Response:
```json theme={null}
{
"directory_state_id": "ds_xyz789...",
"stats": {"uploaded": 5, "cached": 10}
}
```
Then run with the synced files:
```json theme={null}
{
"tool": "run",
"args": {
"command": "python /app/main.py",
"image": "abc123-def456-...",
"directory_state_id": "ds_xyz789..."
}
}
```
## What’s Next?
> [card] [Concepts](./concepts/index)
>
> Understand images, lineage, and async execution.
> [card] [Patterns](./patterns)
>
> Common workflows and best practices.
> [card] [Tool Reference](./tools/index)
>
> Detailed parameters for all 15 tools.
> [card] [Resources](./resources)
>
> MCP resources and guide sections.
# Glossary
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/reference/glossary
Terms and definitions used in Contree MCP.
## A
* **Async Execution** — Running operations without waiting for completion. Use `wait=false` and poll with `get_operation` or `wait_operations`.
## D
* **Directory State** — A snapshot of local files synced with `rsync`. Identified by `directory_state_id`.
* **Disposable** — When `disposable=true` (default), filesystem changes are discarded after command execution.
## I
* **Image** — An immutable filesystem snapshot. Identified by UUID.
* **Image Lineage** — The parent-child relationships between images. View with `contree://image/{uuid}/lineage`.
## M
* **MCP (Model Context Protocol)** — The protocol used for AI agent tool communication.
* **MicroVM** — A lightweight virtual machine used for isolated command execution.
## O
* **Operation** — A running or completed task (command execution or image import). Identified by `operation_id`.
## R
* **Result Image** — The image UUID returned when running with `disposable=false` and filesystem changes occur.
* **Root Image** — An image imported from a container registry, with no parent.
## T
* **Tag** — A human-readable name for an image (e.g., `python:3.11`). Tags can point to different UUIDs over time.
## U
* **UUID** — Universally Unique Identifier. The primary way to reference images and operations.
# Reference
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/reference/index
Additional reference materials.
> [card] [Glossary](./glossary)
## Quick Links
* [Glossary](./glossary) - Terms and definitions
# Resources
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/resources
MCP resource templates for reading files and metadata. No VM needed.
## image\_file
Read a file from a container image.
**URI**: `contree://image/{image}/read/{path}`
| Parameter | Description |
| - | - |
| `image` | Image UUID or `tag:name` |
| `path` | Path inside image (no leading slash) |
**Examples:**
```
contree://image/abc123-uuid/read/etc/passwd
contree://image/tag:alpine:latest/read/etc/os-release
contree://image/tag:python:3.11/read/usr/local/lib/python3.11/site-packages/pip/__init__.py
```
**Returns:** Text content or base64-encoded binary.
***
## image\_ls
List directory contents in a container image.
**URI**: `contree://image/{image}/ls/{path}`
| Parameter | Description |
| - | - |
| `image` | Image UUID or `tag:name` |
| `path` | Directory path (`.` for root) |
**Examples:**
```
contree://image/abc123-uuid/ls/.
contree://image/tag:python:3.11/ls/usr/local/lib
```
**Returns:** JSON with file listing (path, size, mode, is\_dir, mtime).
***
## image\_lineage
View image parent-child relationships and history.
**URI**: `contree://image/{image}/lineage`
| Parameter | Description |
| - | - |
| `image` | Image UUID |
**Example:**
```
contree://image/abc123-uuid/lineage
```
**Returns:**
```json theme={null}
{
"image": "abc123",
"parent": {"image": "parent-uuid", "command": "pip install numpy"},
"children": [],
"ancestors": [],
"root": {"image": "root-uuid", "registry_url": "docker://alpine:latest"},
"depth": 2
}
```
**Use for:** Rollback (use any ancestor UUID), understanding history.
***
## guide
Agent guides and best practices.
**URI**: `contree://guide/{section}`
| Section | Description |
| - | - |
| `workflow` | Complete workflow patterns with decision tree |
| `reference` | Tool reference and quick lookup |
| `quickstart` | Common workflows and best practices |
| `state` | Image state, rollback, disposable mode |
| `async` | Parallel execution patterns |
| `tagging` | Agent tagging conventions |
| `errors` | Error handling and debugging |
**Examples:**
```
contree://guide/workflow
contree://guide/quickstart
contree://guide/async
contree://guide/errors
```
***
## instance\_operation
Read instance (command execution) operation details from cache.
**URI**: `contree://operations/instance/{operation_id}`
| Parameter | Description |
| - | - |
| `operation_id` | Operation UUID from `run` with `wait=false` |
**Example:**
```
contree://operations/instance/op-abc-123-def
```
**Returns:**
```json theme={null}
{
"state": "SUCCESS",
"exit_code": 0,
"stdout": "Hello, World!",
"stderr": "",
"result_image": "uuid-of-result",
"resources": {"cpu_time_ms": 150, "memory_mb": 64}
}
```
**Use for:** Retrieving cached results of completed command executions.
***
## import\_operation
Read image import operation details from cache.
**URI**: `contree://operations/import/{operation_id}`
| Parameter | Description |
| - | - |
| `operation_id` | Operation UUID from `import_image` with `wait=false` |
**Example:**
```
contree://operations/import/op-xyz-789-abc
```
**Returns:**
```json theme={null}
{
"state": "SUCCESS",
"registry_url": "docker://python:3.11-slim",
"result_image": "uuid-of-imported-image",
"result_tag": "python:3.11-slim"
}
```
**Use for:** Retrieving cached results of completed image imports.
# Reporting Security Issues
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/security
The Nebius team take security bugs seriously. We appreciate your efforts to responsibly disclose your findings, and
will make every effort to acknowledge your contributions.
To report a security issue, please use the GitHub Security Advisory
[“Report a Vulnerability”](https://github.com/nebius/contree-mcp/security/advisories/new) tab.
The Nebius team will send a response indicating the next steps in handling your report. After the initial reply to your
report, the Nebius team will keep you informed of the progress towards a fix and full announcement, and may ask for
additional information or guidance.
## Learning More About Security in Nebius
To learn more about security in Nebius, please see [this page](https://nebius.ai/docs/security).
# cancel_operation
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/cancel_operation
Cancel a running operation.
## TL;DR
* **Use when**: Operation taking too long, no longer needed
* **Returns**: Cancellation status
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `operation_id` | string | Yes | - | Operation UUID to cancel |
## Response
```json theme={null}
{
"success": true,
"operation_id": "op-abc123"
}
```
## Examples
### Cancel Operation
```json theme={null}
{"tool": "cancel_operation", "args": {
"operation_id": "op-abc123"
}}
```
## See Also
* [get\_operation](./get_operation) - Check operation status
* [list\_operations](./list_operations) - Find operations
# download
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/download
Download a file from a container image to local filesystem.
## TL;DR
* **Use when**: Extracting build artifacts, logs, binaries
* **Returns**: Success status, file size, path
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or `tag:name` |
| `path` | string | Yes | - | Path inside container |
| `destination` | string | Yes | - | Absolute path on MCP host filesystem (`~` supported, parent dirs auto-created). This writes to the MCP server’s filesystem, not inside the container. |
| `executable` | boolean | No | `false` | Make file executable |
## Response
```json theme={null}
{
"success": true,
"size": 12345,
"size_human": "12.1 KB",
"destination": "/local/path/binary",
"source": {
"image": "img-build-result",
"path": "/app/dist/binary"
},
"executable": true
}
```
## Examples
### Download Build Artifact
```json theme={null}
{"tool": "download", "args": {
"image": "img-build-result",
"path": "/app/dist/binary",
"destination": "~/downloads/binary",
"executable": true
}}
```
### Download Log File
```json theme={null}
{"tool": "download", "args": {
"image": "img-uuid",
"path": "/var/log/app.log",
"destination": "~/downloads/debug.log"
}}
```
> **Note:** `destination` must be an absolute path on the MCP server’s host filesystem (not inside the container). Use `~` for home directory. Parent directories are created automatically.
## See Also
* [upload](./upload) - Upload files to Contree
* [rsync](./rsync) - Sync directories
# get_guide
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/get_guide
Get agent guide sections for Contree best practices.
## Overview
`get_guide` provides access to documentation and best practices for using Contree. This tool is an alternative to the `contree://guide/{section}` resource for agents that don’t support MCP resources.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `section` | string | Yes | - | Guide section name |
### Available Sections
| Section | Description |
| - | - |
| `workflow` | Complete workflow patterns with decision tree |
| `reference` | Tool reference with parameters and data flow |
| `quickstart` | Quick examples for common operations |
| `state` | State management and rollback patterns |
| `async` | Parallel execution patterns |
| `tagging` | Agent tagging conventions |
| `errors` | Error handling and debugging |
## Returns
| Field | Type | Description |
| - | - | - |
| `section` | string | Requested section name |
| `content` | string | Guide content in Markdown |
| `available_sections` | array | List of all available section names |
## Cost
**Free** - No VM spawned. Returns static documentation.
## Examples
### Get Workflow Guide
```json theme={null}
{
"tool": "get_guide",
"args": {
"section": "workflow"
}
}
```
Response:
```json theme={null}
{
"section": "workflow",
"content": "# Contree Workflow Guide\n\n## Decision Tree: Which Image to Use?\n...",
"available_sections": ["async", "errors", "quickstart", "reference", "state", "tagging", "workflow"]
}
```
### Get Error Handling Guide
```json theme={null}
{
"tool": "get_guide",
"args": {
"section": "errors"
}
}
```
### Get Tagging Convention
```json theme={null}
{
"tool": "get_guide",
"args": {
"section": "tagging"
}
}
```
## When to Use
Use `get_guide` when:
* Your agent runtime doesn’t support MCP resources
* You need documentation about Contree best practices
* You want to understand workflow patterns or error handling
If your agent supports MCP resources, prefer using the resource URI:
```
contree://guide/workflow
contree://guide/errors
```
## Guide Content Overview
### workflow
Decision trees for choosing images, complete examples for Python ML environments, anti-patterns to avoid, and project-specific environment guidance.
### reference
Quick reference table of all tools with parameters, returns, and costs. Detailed parameter documentation for key tools.
### quickstart
Basic command execution, file sync patterns, dependency chains, and best practices for UUIDs vs tags.
### state
Understanding immutable snapshots, disposable mode, rollback model with branching, and response fields.
### async
Sequential vs parallel patterns, launching multiple async operations, waiting for results, and operation states.
### tagging
Tag format convention `{scope}/{purpose}/{base}:{tag}`, when to tag as common vs project-specific, and common tags to search for.
### errors
Common error patterns (command failures, timeouts, missing images), solutions, and debugging workflow.
## See Also
* [Resources](../resources) - `contree://guide/{section}` resource alternative
* [list\_images](./list_images) - Find existing tagged images
* [set\_tag](./set_tag) - Tag images for reuse
# get_image
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/get_image
Get image details by UUID or tag.
## TL;DR
* **Use when**: Verifying an image exists, resolving tag to UUID
* **Returns**: Image UUID, tag, creation time
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or `tag:name` |
## Response
```json theme={null}
{
"uuid": "abc123-def456-...",
"tag": "python:3.11",
"created_at": "2024-01-15T10:30:00Z"
}
```
## Examples
### By UUID
```json theme={null}
{"tool": "get_image", "args": {"image": "abc123-def456-..."}}
```
### By Tag
```json theme={null}
{"tool": "get_image", "args": {"image": "tag:python:3.11"}}
```
## See Also
* [list\_images](./list_images) - List all images
* [set\_tag](./set_tag) - Assign a tag
# get_operation
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/get_operation
Get the status and result of an operation.
## TL;DR
* **Use when**: Checking async operation results
* **Returns**: Operation state, stdout/stderr, exit code
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `operation_id` | string | Yes | - | Operation UUID |
## Response
For instance (command) operations:
```json theme={null}
{
"operation_kind": "instance",
"state": "SUCCESS",
"exit_code": 0,
"stdout": "output here",
"stderr": null,
"result_image": "img-uuid",
"resources": {
"elapsed_time": 1.234
}
}
```
For import operations:
```json theme={null}
{
"operation_kind": "image_import",
"state": "SUCCESS",
"result_image": "img-uuid",
"result_tag": "python:3.11"
}
```
## Examples
### Check Status
```json theme={null}
{"tool": "get_operation", "args": {
"operation_id": "op-abc123"
}}
```
## Operation States
| State | Description |
| - | - |
| `PENDING` | Queued |
| `EXECUTING` | Running |
| `SUCCESS` | Completed successfully |
| `FAILED` | Completed with error |
| `CANCELLED` | Cancelled |
## See Also
* [wait\_operations](./wait_operations) - Wait for multiple ops
* [list\_operations](./list_operations) - List all operations
* [cancel\_operation](./cancel_operation) - Cancel running op
# grep
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/grep
Search file contents in a container image using ripgrep, without spawning a VM.
## Overview
`grep` runs a regex content search over an image’s persisted root filesystem, powered by ripgrep on the backend. Use it to find where a config key, symbol, or string lives before running commands — it’s instant and free, unlike `run("grep ...")` which needs a microVM.
Symlinks are never followed, hidden files are searched, `.gitignore`-style files inside the image are ignored, and binary files (containing a NUL byte) are skipped.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or `tag:name` |
| `pattern` | string | Yes | - | Rust-flavored regex to search for |
| `path` | string | No | rootfs root | File or directory to search inside the image |
| `glob` | string | No | - | Glob to filter files (ripgrep `-g` semantics, `!` negates) |
| `max_count` | integer | No | - | Maximum matches per file |
| `max_total` | integer | No | 1000 | Maximum total matches across all files |
| `case` | string | No | - | `sensitive`, `insensitive`, or `smart` |
## Returns
| Field | Type | Description |
| - | - | - |
| `path` | string | The path inside the image that was searched |
| `patterns` | array | The patterns that were searched for |
| `truncated` | boolean | True when `max_total` or the search deadline stopped the search early |
| `matches` | array | List of matching lines |
### Match Fields
| Field | Type | Description |
| - | - | - |
| `path` | string | File path relative to the image rootfs |
| `line_number` | integer | 1-based line number of the match |
| `line_text` | string | The matching line |
## Cost
**Free** - No VM spawned. Searches directly over the image filesystem.
## Examples
### Find a Config Setting
```json theme={null}
{
"tool": "grep",
"args": {
"image": "abc123-def456",
"pattern": "^PermitRootLogin",
"path": "/etc/ssh"
}
}
```
### Scope by File Type
```json theme={null}
{
"tool": "grep",
"args": {
"image": "tag:python:3.11-slim",
"pattern": "TODO",
"glob": "*.py"
}
}
```
### Case-Insensitive Search
```json theme={null}
{
"tool": "grep",
"args": {
"image": "img-uuid",
"pattern": "error",
"case": "insensitive"
}
}
```
## Best Practices
* **Prefer over `run("grep ...")`** - `grep` is instant and free
* **Narrow with `path` and `glob`** - avoid scanning the whole rootfs when you know roughly where to look
* **`pattern` is a regex, not a literal string** - escape special characters if you want an exact match
* **Combine with `list_files`** - list a directory first, then grep the files you find interesting
## See Also
* [list\_files](./list_files) - List files and directories without a VM
* [read\_file](./read_file) - Read a single file’s full contents without a VM
* [run](./run) - Execute commands (spawns VM), e.g. for tools ripgrep can’t replace
# import_image
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/import_image
Import OCI container image from registry. Spawns microVM.
**Check first**: Use `list_images` to see if already imported.
## Authentication
Before importing, authenticate with the registry:
1. Call `registry_token_obtain` to open browser for PAT creation
2. User creates read-only PAT in registry web UI
3. Call `registry_auth` to validate and store credentials
Anonymous access is possible but discouraged due to registry provider rate limits.
## Parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `registry_url` | string | required | Registry URL (e.g., `docker://python:3.11`) |
| `tag` | string | - | Tag to assign after import |
| `wait` | boolean | `true` | Wait for completion |
| `i_accept_that_anonymous_access_might_be_rate_limited` | boolean | `false` | Skip authentication (not recommended) |
## Examples
**Basic (requires prior authentication):**
```json theme={null}
{"registry_url": "docker://python:3.11-slim"}
```
**With tag:**
```json theme={null}
{"registry_url": "docker://alpine:latest", "tag": "alpine:latest"}
```
**Anonymous access (rate limited):**
```json theme={null}
{"registry_url": "docker://alpine:latest", "i_accept_that_anonymous_access_might_be_rate_limited": true}
```
**Async:**
```json theme={null}
{"registry_url": "docker://pytorch/pytorch:2.0-cuda11.7", "wait": false}
```
## Response
```json theme={null}
{"result_image": "abc123-uuid", "result_tag": "python:3.11", "state": "SUCCESS"}
```
With `wait=false`: `{"operation_id": "op-xxx"}`
## Common Base Images
| Registry URL | Use Case |
| - | - |
| `docker://python:3.11-slim` | Python |
| `docker://node:20-slim` | Node.js |
| `docker://alpine:latest` | Minimal Linux |
| `docker://ubuntu:22.04` | Full Linux |
| `docker://golang:1.21` | Go |
## Parallel Imports
```json theme={null}
{"registry_url": "docker://python:3.11", "wait": false}
{"registry_url": "docker://node:20", "wait": false}
{"tool": "wait_operations", "args": {"operation_ids": ["op-1", "op-2"]}}
```
# Tools Reference
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/index
All 18 tools for container execution, file management, and operations.
> [card] [run](./run)
> [card] [rsync](./rsync)
> [card] [import\_image](./import_image)
> [card] [registry\_token\_obtain](./registry_token_obtain)
> [card] [registry\_auth](./registry_auth)
> [card] [list\_images](./list_images)
> [card] [get\_image](./get_image)
> [card] [set\_tag](./set_tag)
> [card] [upload](./upload)
> [card] [download](./download)
> [card] [list\_files](./list_files)
> [card] [read\_file](./read_file)
> [card] [grep](./grep)
> [card] [get\_operation](./get_operation)
> [card] [list\_operations](./list_operations)
> [card] [wait\_operations](./wait_operations)
> [card] [cancel\_operation](./cancel_operation)
> [card] [get\_guide](./get_guide)
## Quick Reference
### Command Execution
| Tool | Description | Cost |
| - | - | - |
| [run](./run) | Execute command in container | Spawns microVM |
### File Transfer
| Tool | Description | Cost |
| - | - | - |
| [rsync](./rsync) | Sync local files with caching | No VM |
| [upload](./upload) | Upload single file | No VM |
| [download](./download) | Download file from image | No VM |
### Image Management
| Tool | Description | Cost |
| - | - | - |
| [import\_image](./import_image) | Import from registry | Spawns microVM |
| [registry\_token\_obtain](./registry_token_obtain) | Open browser for PAT creation | No VM |
| [registry\_auth](./registry_auth) | Validate and store credentials | No VM |
| [list\_images](./list_images) | List available images | No VM |
| [get\_image](./get_image) | Get image by UUID/tag | No VM |
| [set\_tag](./set_tag) | Set or remove tag | No VM |
### Image Inspection
| Tool | Description | Cost |
| - | - | - |
| [list\_files](./list_files) | List files in image | No VM |
| [read\_file](./read_file) | Read file from image | No VM |
| [grep](./grep) | Search file contents via ripgrep | No VM |
### Operations
| Tool | Description | Cost |
| - | - | - |
| [get\_operation](./get_operation) | Get operation status | No VM |
| [list\_operations](./list_operations) | List operations | No VM |
| [wait\_operations](./wait_operations) | Wait for multiple ops | No VM |
| [cancel\_operation](./cancel_operation) | Cancel operation | No VM |
### Documentation
| Tool | Description | Cost |
| - | - | - |
| [get\_guide](./get_guide) | Get guide sections | No VM |
## Common Patterns
### Basic Execution
```json theme={null}
{"tool": "run", "args": {"command": "python -c 'print(1)'", "image": "img-uuid"}}
```
### With Local Files
```json theme={null}
{"tool": "rsync", "args": {"source": "/project", "destination": "/app"}}
{"tool": "run", "args": {"command": "python /app/main.py", "image": "img-uuid", "directory_state_id": "ds-uuid"}}
```
### Parallel Execution
```json theme={null}
{"tool": "run", "args": {"command": "test1.py", "image": "img", "wait": false}}
{"tool": "run", "args": {"command": "test2.py", "image": "img", "wait": false}}
{"tool": "wait_operations", "args": {"operation_ids": ["op-1", "op-2"]}}
```
### Inspect Container (No VM)
```json theme={null}
{"tool": "list_files", "args": {"image": "img-uuid", "path": "/etc"}}
{"tool": "read_file", "args": {"image": "img-uuid", "path": "/etc/os-release"}}
```
# list_files
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/list_files
List files and directories in a container image without spawning a VM.
## Overview
`list_files` provides instant filesystem inspection without the overhead of starting a container. Use it to explore image contents, verify file existence, and check permissions before running commands.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or `tag:name` |
| `path` | string | No | `/` | Directory path to list |
## Returns
| Field | Type | Description |
| - | - | - |
| `path` | string | Normalized path that was listed |
| `count` | integer | Number of entries in listing |
| `files` | array | List of file entries |
### File Entry Fields
| Field | Type | Description |
| - | - | - |
| `name` | string | File or directory name |
| `path` | string | Full path within image |
| `type` | string | `file`, `directory`, or `symlink` |
| `size` | integer | Size in bytes |
| `mode` | string | Octal permission mode (e.g., `0o755`) |
| `target` | string | Symlink target (only for symlinks) |
## Cost
**Free** - No VM spawned. Reads directly from image filesystem.
## Examples
### List Root Directory
```json theme={null}
{
"tool": "list_files",
"args": {
"image": "abc123-def456",
"path": "/"
}
}
```
Response:
```json theme={null}
{
"path": "/",
"count": 15,
"files": [
{"name": "bin", "path": "/bin", "type": "symlink", "size": 0, "mode": "0o777", "target": "usr/bin"},
{"name": "etc", "path": "/etc", "type": "directory", "size": 4096, "mode": "0o755", "target": null},
{"name": "root", "path": "/root", "type": "directory", "size": 4096, "mode": "0o700", "target": null}
]
}
```
### List Specific Directory
```json theme={null}
{
"tool": "list_files",
"args": {
"image": "tag:python:3.11-slim",
"path": "/usr/local/lib/python3.11"
}
}
```
### Verify File Existence Before Running
```json theme={null}
// Check if expected file exists
{"tool": "list_files", "args": {"image": "img-uuid", "path": "/app"}}
// If found, run the command
{"tool": "run", "args": {"command": "python /app/main.py", "image": "img-uuid"}}
```
## Best Practices
* **Prefer over `run("ls")`** - `list_files` is instant and free
* **Verify paths before commands** - Check files exist to avoid errors
* **Explore unfamiliar images** - Understand structure before running code
* **Check permissions** - Verify executable bits and ownership
## See Also
* [read\_file](./read_file) - Read file contents without VM
* [grep](./grep) - Search file contents without VM
* [run](./run) - Execute commands (spawns VM)
* [Resources](../resources) - `contree://image/{image}/ls/{path}` resource alternative
# list_images
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/list_images
List available container images.
## TL;DR
* **Use when**: Finding images, checking before import
* **Returns**: List of images with UUID, tag, creation time
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `limit` | integer | No | `100` | Max images to return (1-1000) |
| `offset` | integer | No | `0` | Skip first N images |
| `tagged` | boolean | No | `null` | Only tagged images |
| `tag_prefix` | string | No | `null` | Filter by tag prefix |
| `since` | string | No | `null` | Created after (e.g., “1h”, “1d”) |
| `until` | string | No | `null` | Created before |
## Response
```json theme={null}
{
"images": [
{
"uuid": "abc123-def456-...",
"tag": "python:3.11",
"created_at": "2024-01-15T10:30:00Z"
},
{
"uuid": "xyz789-...",
"tag": null,
"created_at": "2024-01-15T09:00:00Z"
}
]
}
```
## Examples
### List All
```json theme={null}
{"tool": "list_images", "args": {}}
```
### Filter by Tag Prefix
```json theme={null}
{"tool": "list_images", "args": {"tag_prefix": "python"}}
```
### Only Tagged Images
```json theme={null}
{"tool": "list_images", "args": {"tagged": true}}
```
### Recent Images
```json theme={null}
{"tool": "list_images", "args": {"since": "1h"}}
```
### Pagination
```json theme={null}
{"tool": "list_images", "args": {"limit": 10, "offset": 20}}
```
## See Also
* [import\_image](./import_image) - Import new images
* [get\_image](./get_image) - Get single image details
# list_operations
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/list_operations
List operations (running or completed).
## TL;DR
* **Use when**: Finding operation IDs, monitoring
* **Returns**: List of operations with status
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `limit` | integer | No | `100` | Max operations to return |
| `status` | string | No | `null` | Filter by status |
| `kind` | string | No | `null` | Filter by kind |
| `since` | string | No | `null` | Created after |
## Response
```json theme={null}
{
"operations": [
{
"uuid": "op-abc123",
"kind": "instance",
"state": "SUCCESS",
"created_at": "2024-01-15T10:30:00Z"
}
]
}
```
## Examples
### List Running
```json theme={null}
{"tool": "list_operations", "args": {"status": "running"}}
```
### List by Kind
```json theme={null}
{"tool": "list_operations", "args": {"kind": "image_import"}}
```
## See Also
* [get\_operation](./get_operation) - Get single operation
* [cancel\_operation](./cancel_operation) - Cancel operation
# read_file
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/read_file
Read a file from a container image without spawning a VM.
## Overview
`read_file` provides instant file content access without the overhead of starting a container. Use it to inspect configuration files, review scripts, or check expected content before running commands.
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image` | string | Yes | - | Image UUID or `tag:name` |
| `path` | string | Yes | - | File path to read |
## Returns
| Field | Type | Description |
| - | - | - |
| `path` | string | Normalized path that was read |
| `content` | string | File contents (decoded or base64 encoded) |
| `bytes_size` | integer | Size in bytes |
| `encoding` | string | `"utf-8"` for text files, `"base64"` for binary |
## Cost
**Free** - No VM spawned. Reads directly from image filesystem.
## Text Detection
Files are automatically detected as text based on extension. Common text extensions include:
* Source code: `.py`, `.js`, `.ts`, `.go`, `.rs`, `.java`, `.c`, `.h`, `.cpp`
* Config: `.json`, `.yaml`, `.yml`, `.toml`, `.ini`, `.cfg`, `.conf`
* Scripts: `.sh`, `.bash`, `.zsh`
* Documentation: `.md`, `.rst`, `.txt`
* Web: `.html`, `.css`, `.xml`
Binary files are decoded with replacement characters for non-UTF8 bytes.
## Examples
### Read Configuration File
```json theme={null}
{
"tool": "read_file",
"args": {
"image": "abc123-def456",
"path": "/etc/os-release"
}
}
```
Response:
```json theme={null}
{
"path": "/etc/os-release",
"content": "PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\nNAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12\"\n...",
"bytes_size": 187,
"encoding": "utf-8"
}
```
### Check Python Package Version
```json theme={null}
{
"tool": "read_file",
"args": {
"image": "tag:python:3.11-slim",
"path": "/usr/local/lib/python3.11/site-packages/pip/__init__.py"
}
}
```
### Review Script Before Execution
```json theme={null}
// Read the script to understand what it does
{"tool": "read_file", "args": {"image": "img-uuid", "path": "/app/setup.sh"}}
// If safe, execute it
{"tool": "run", "args": {"command": "bash /app/setup.sh", "image": "img-uuid"}}
```
## Best Practices
* **Prefer over `run("cat")`** - `read_file` is instant and free
* **Review before executing** - Check scripts for safety before running
* **Inspect configurations** - Understand image setup without running commands
* **Verify expected content** - Check files contain what you expect
## See Also
* [list\_files](./list_files) - List directory contents without VM
* [grep](./grep) - Search file contents without VM
* [download](./download) - Download file to local filesystem
* [Resources](../resources) - `contree://image/{image}/read/{path}` resource alternative
# registry_auth
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/registry_auth
Authenticate with a container registry via Personal Access Token.
## Parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `registry_url` | string | required | Registry URL (e.g., `docker://ghcr.io/org/image`) |
| `username` | string | required | Registry username |
| `token` | string | required | Personal Access Token |
## URL Parsing
| Input | Registry |
| - | - |
| `docker://ghcr.io/org/image` | ghcr.io |
| `oci://registry.gitlab.com/org/image` | registry.gitlab.com |
| `alpine` or `library/alpine` | docker.io (implicit) |
## Examples
**Docker Hub:**
```json theme={null}
{"registry_url": "docker://docker.io/library/alpine", "username": "myuser", "token": "dckr_pat_xxx"}
```
**GitHub Container Registry:**
```json theme={null}
{"registry_url": "docker://ghcr.io/org/image", "username": "myuser", "token": "ghp_xxx"}
```
## Response
**Success:**
```json theme={null}
{
"status": "success",
"registry": "docker.io",
"message": "Authenticated with 'docker.io' as 'myuser' successfully."
}
```
**Invalid credentials:**
```json theme={null}
{
"status": "error",
"registry": "docker.io",
"message": "Invalid credentials for 'docker.io'. Please verify your username and PAT."
}
```
## Token Storage
* Credentials are validated via OCI /v2/ API before storage
* Stored in local cache and persisted across sessions
* Tokens are revalidated before each `import_image` call
* Expired tokens are automatically removed from cache
## Workflow
1. Call `registry_token_obtain` → opens browser
2. User creates read-only PAT in registry web UI
3. User provides username and token
4. Call `registry_auth` → validates and stores credentials
5. Call `import_image` to import images
# registry_token_obtain
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/registry_token_obtain
Open browser to create a Personal Access Token for a container registry.
## Parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `registry_url` | string | required | Registry URL (e.g., `docker://ghcr.io/org/image`) |
## Known Registries
| Registry | PAT Page |
| - | - |
| docker.io | Docker Hub PAT settings |
| ghcr.io | GitHub fine-grained tokens |
| registry.gitlab.com | GitLab PAT settings |
| gcr.io | Google Cloud credentials |
## Examples
**Docker Hub:**
```json theme={null}
{"registry_url": "docker://docker.io/library/alpine"}
```
**GitHub Container Registry:**
```json theme={null}
{"registry_url": "docker://ghcr.io/org/image"}
```
**Bare image name (defaults to docker.io):**
```json theme={null}
{"registry_url": "alpine"}
```
## Response
**Success:**
```json theme={null}
{
"status": "success",
"registry": "docker.io",
"url": "https://app.docker.com/settings/personal-access-tokens",
"message": "Browser opened to ... Create a read-only PAT, then provide your username and token.",
"agent_instruction": "STOP HERE. Wait for user to create PAT and provide the token."
}
```
**Unknown registry:**
```json theme={null}
{
"status": "error",
"registry": "unknown.example.com",
"message": "Unknown registry 'unknown.example.com'. Please consult the registry documentation for token creation."
}
```
## Workflow
1. Call `registry_token_obtain` → opens browser
2. User creates read-only PAT in registry web UI
3. User provides username and token
4. Call `registry_auth` to validate and store credentials
5. Call `import_image` to import images
# rsync
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/rsync
Sync local files to Contree with smart caching. No VM needed.
## Parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `source` | string | required | Local path or glob pattern |
| `destination` | string | required | Container target directory |
| `exclude` | array | `[]` | Patterns to exclude |
## Examples
**Basic:**
```json theme={null}
{"source": "/project", "destination": "/app"}
```
**With exclusions:**
```json theme={null}
{
"source": "/project",
"destination": "/app",
"exclude": ["__pycache__", "*.pyc", ".git", ".venv", "node_modules"]
}
```
**Glob pattern:**
```json theme={null}
{"source": "/project/**/*.py", "destination": "/app"}
```
## Response
Returns an integer `directory_state_id` for use with the `run` tool:
```json theme={null}
42
```
## Using with run
```json theme={null}
// 1. Sync
{"tool": "rsync", "args": {"source": "/project", "destination": "/app"}}
// Returns: 42
// 2. Run (reuse directory_state_id for multiple runs)
{"tool": "run", "args": {
"command": "python /app/main.py",
"image": "uuid",
"directory_state_id": 42
}}
```
## Caching
Three-tier: local cache → content hash → server dedup. Only changed files upload.
**Tip:** Reuse `directory_state_id` for the session. Re-sync only when files change.
## Recommended Exclusions
```json theme={null}
["__pycache__", "*.pyc", ".git", ".venv", "node_modules", "*.log", ".DS_Store"]
```
# run
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/run
Execute command in isolated container. Spawns microVM (\~2-5s startup).
## Parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `command` | string | required | Shell command to execute |
| `image` | string | required | Image UUID or `tag:name` |
| `shell` | boolean | `true` | Whether command is a shell expression |
| `disposable` | boolean | `true` | Discard changes after execution |
| `directory_state_id` | integer | - | Files from rsync |
| `files` | object | - | Map of container paths to upload UUIDs: `{"/path/in/container": "uuid"}` — key is destination, value is UUID |
| `wait` | boolean | `true` | Block until complete |
| `timeout` | integer | `30` | Max seconds |
| `env` | object | - | Environment variables |
| `cwd` | string | `/root` | Working directory |
| `stdin` | string | - | Input via stdin |
| `truncate_output_at` | integer | `8000` | Max bytes for output |
## Examples
**Basic:**
```json theme={null}
{"command": "python --version", "image": "tag:python:3.11"}
```
**With local files:**
```json theme={null}
{"command": "python /app/main.py", "image": "uuid", "directory_state_id": 42}
```
**Save changes:**
```json theme={null}
{"command": "pip install flask", "image": "uuid", "disposable": false}
```
Returns: `{"result_image": "new-uuid", "filesystem_changed": true}`
**Async:**
```json theme={null}
{"command": "python long_task.py", "image": "uuid", "wait": false}
```
Returns: `{"operation_id": "op-xxx"}`
**With uploaded files:**
```json theme={null}
// Step 1: Upload file
{"tool": "upload", "args": {"content": "print('hello')"}}
// Returns: {"uuid": "file-uuid-123"}
// Step 2: Inject into container and run
{"tool": "run", "args": {
"command": "python /app/script.py",
"image": "tag:python:3.11",
"files": {"/app/script.py": "file-uuid-123"}
}}
```
> **Common mistake:** The `files` key is the **container path** (destination), the value is the **UUID** (from upload). Not the other way around. One UUID can be mounted to multiple paths.
**Environment variables:**
```json theme={null}
{"command": "echo $MY_VAR", "image": "uuid", "env": {"MY_VAR": "hello"}}
```
## Response
```json theme={null}
{
"exit_code": 0,
"timed_out": false,
"state": "SUCCESS",
"result_image": "uuid-if-disposable-false",
"filesystem_changed": true,
"stdout": "output",
"stderr": null
}
```
## Errors
* **Image not found**: Use `list_images` to find valid UUIDs
* **Directory state not found**: Re-run `rsync`
* **timed\_out: true**: Increase `timeout` parameter
# set_tag
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/set_tag
Set or remove a tag for an image.
## TL;DR
* **Use when**: Naming frequently-used images
* **Returns**: Updated image details
* **Cost**: No VM needed
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `image_uuid` | string | Yes | - | Image UUID to tag |
| `tag` | string | No | `null` | Tag to assign (omit to remove) |
## Response
```json theme={null}
{
"uuid": "abc123-def456-...",
"tag": "my-image:v1",
"created_at": "2024-01-15T10:30:00Z"
}
```
## Examples
### Set Tag
```json theme={null}
{"tool": "set_tag", "args": {
"image_uuid": "abc123-def456-...",
"tag": "claude/project/python/dev-env:v1"
}}
```
### Remove Tag
```json theme={null}
{"tool": "set_tag", "args": {
"image_uuid": "abc123-def456-..."
}}
```
## Tagging Convention
For AI agents, use this pattern:
```
{agent}/{project}/{base}/{approach}:{version}
```
Examples:
* `claude/myproject/python/dev-env:v1`
* `claude/common/alpine/build-tools:latest`
## See Also
* [get\_image](./get_image) - Get image details
* [list\_images](./list_images) - Find images
# upload
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/upload
Upload a file to Contree.
## TL;DR
* **Use when**: Single file, generated content
* **Returns**: File UUID for use with `run`
* **Cost**: No VM needed
* **Prefer**: `rsync` for multiple files (has caching)
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `content` | string | No\* | - | Text content |
| `content_base64` | string | No\* | - | Base64-encoded binary |
| `path` | string | No\* | - | Absolute path to a file on **local filesystem** to read and upload. Not a destination name — files are content-addressable (UUID). To name the file in a container, use `run`’s `files` parameter. |
\*One of `content`, `content_base64`, or `path` is required.
## Response
```json theme={null}
{
"uuid": "file-uuid-123",
"sha256": "abc123..."
}
```
## Examples
### Text Content
```json theme={null}
{"tool": "upload", "args": {
"content": "print('hello world')"
}}
```
### Local File
```json theme={null}
{"tool": "upload", "args": {
"path": "/path/to/script.py"
}}
```
### Binary (Base64)
```json theme={null}
{"tool": "upload", "args": {
"content_base64": "SGVsbG8gV29ybGQ="
}}
```
## Using the Result
Pass the UUID to `run` via the `files` parameter:
```json theme={null}
// Step 1: Upload
{"tool": "upload", "args": {"content": "print('hello')"}}
// Returns: {"uuid": "file-uuid-123"}
// Step 2: Run
{"tool": "run", "args": {
"command": "python /app/script.py",
"image": "img-uuid",
"files": {"/app/script.py": "file-uuid-123"}
}}
```
## Common Mistake
`path` reads from the **local MCP-server filesystem** — it does not set the file’s name in storage. The uploaded file is content-addressable and identified only by UUID. To place it at a specific path inside a container, pass the UUID to `run`’s `files` parameter:
```json theme={null}
{"tool": "run", "args": {
"command": "python /app/script.py",
"image": "img-uuid",
"files": {"/app/script.py": "file-uuid-123"}
}}
```
## See Also
* [rsync](./rsync) - For multiple files (with caching)
* [run](./run) - Use uploaded files
* [download](./download) - Download from images
# wait_operations
Source: https://docs.tokenfactory.nebius.com/sandboxes/mcp/tools/wait_operations
Wait for multiple operations to complete.
## TL;DR
* **Use when**: Launched multiple async operations
* **Returns**: All operation results
* **Cost**: No VM needed (just waiting)
## Parameters
| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `operation_ids` | array | Yes | - | List of operation UUIDs |
| `mode` | string | No | `"all"` | `"all"` or `"any"` |
| `timeout` | number | No | `300` | Max wait time (seconds) |
## Response
```json theme={null}
{
"results": {
"op-1": {
"state": "SUCCESS",
"exit_code": 0,
"stdout": "..."
},
"op-2": {
"state": "SUCCESS",
"exit_code": 0,
"stdout": "..."
}
},
"completed": ["op-1", "op-2"],
"cancelled": [],
"timed_out": false
}
```
## Examples
### Wait for All
```json theme={null}
{"tool": "wait_operations", "args": {
"operation_ids": ["op-1", "op-2", "op-3"]
}}
```
### Wait for Any (First to Complete)
```json theme={null}
{"tool": "wait_operations", "args": {
"operation_ids": ["op-1", "op-2", "op-3"],
"mode": "any"
}}
```
### With Timeout
```json theme={null}
{"tool": "wait_operations", "args": {
"operation_ids": ["op-1", "op-2"],
"timeout": 600
}}
```
## Parallel Execution Pattern
```json theme={null}
// Launch async
{"tool": "run", "args": {"command": "test1.py", "wait": false}}
{"tool": "run", "args": {"command": "test2.py", "wait": false}}
{"tool": "run", "args": {"command": "test3.py", "wait": false}}
// Wait for all
{"tool": "wait_operations", "args": {
"operation_ids": ["op-1", "op-2", "op-3"]
}}
```
## See Also
* [get\_operation](./get_operation) - Check single operation
* [Async Guide](../resources#guide) - Parallel execution patterns
# Limits, retention, and usage
Source: https://docs.tokenfactory.nebius.com/sandboxes/operate/limits-retention-and-usage
Plan for service limits and retention, and inspect the fields available to your account.
Use the values below for initial planning, then inspect the limits returned for the authenticated account.
| Boundary | Behavior |
| - | - |
| Simultaneous operations | 50 during Beta; check the account-effective limit and contact the team to request a higher limit |
| Checkpoint images | Retained for 180 days; after that, untagged and unreferenced images may be deleted |
| Recorded stdin, stdout, stderr | Spawn default: 1 MiB per stream; maximum: 10 MiB per stream |
| Execution timeout | Request field is seconds; account-effective maximum is exposed in token limits |
| Networking | Enabled by default; `networking.enabled=false` starts the VM without a guest network interface |
Contact [contree@nebius.com](mailto:contree@nebius.com) before a workload depends on file-upload, download, total-image, start-rate, regional, or event-retention limits. Also confirm any required deletion behavior, cancellation retention, or retention treatment for tagged and referenced images. Use the same contact to request a higher simultaneous-operation limit.
## Inspect effective limits
Token information exposes a `limits` map for the authenticated principal. Treat those values as account-effective controls, because they may differ from the overview. The `statistics` field is reserved for future use and is not a usage report.
Complete [Set up access](/sandboxes/start/set-up-access) and install `curl` and `jq`. Run both examples in the same shell with `NEBIUS_API_KEY` and `NEBIUS_PROJECT_ID` from access setup. Use the base URL below unless your deployment requires a different documented URL.
```bash theme={null}
CONTREE_BASE_URL="https://api.tokenfactory.nebius.com/sandboxes"
curl --max-time 20 --fail-with-body -sS "$CONTREE_BASE_URL/v1/whoami" \
-H "Authorization: Bearer $NEBIUS_API_KEY" \
-H "Project: $NEBIUS_PROJECT_ID" |
jq '{permissions, limits}'
```
Each completed operation exposes raw resource fields including CPU, memory, I/O, process-switch, fault, signal, swap, `elapsed_time`, and `cost`. Use these fields for diagnostics only unless the Sandboxes team has confirmed their units and aggregation for the intended calculation. Use the operation-list `duration` field for elapsed seconds. Use billing records, rather than the operation `cost` field, for invoice reconciliation.
Replace `YOUR_OPERATION_UUID` with the accepted operation UUID from a completed run. [Run commands and handle results](/sandboxes/guides/run-commands-and-results#start-observe-and-finish) explains how to submit and observe one. Query its status, process state, captured streams, and raw resources:
```bash theme={null}
OPERATION_ID="YOUR_OPERATION_UUID"
curl --max-time 20 --fail-with-body -sS \
"$CONTREE_BASE_URL/v1/operations/$OPERATION_ID" \
-H "Authorization: Bearer $NEBIUS_API_KEY" \
-H "Project: $NEBIUS_PROJECT_ID" |
jq '{uuid,status,error,duration,image_uuid,result_image_uuid,
process:.metadata.result.state,resources:.metadata.result.resources}'
```
Use `GET /v1/operations` for operation history. Before comparing workloads with resource metrics, confirm the units and aggregation of every selected field.
## Persistence consequences
A retained operation can return `result_image_uuid`; a disposable operation cannot provide a continuation point. See [Interpret the result image](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image) for unchanged filesystems and interrupted or failed runs.
See [Troubleshooting](/sandboxes/operate/troubleshooting) and [Update images and clients](/sandboxes/operate/update-images-and-clients).
# Security and data handling
Source: https://docs.tokenfactory.nebius.com/sandboxes/operate/security-and-data-handling
Protect data and credentials across uploads, output, images, networking, and local downloads.
Sandboxes runs workloads in VM-level isolation. Treat the sandbox as a boundary for workload execution, while controlling which data and credentials enter it.
| Where data is stored | Behavior | Requirements to confirm before use |
| - | - | - |
| Uploaded inputs | Attached to an operation and available at specified guest paths | Retention, deletion, encryption at rest, size limits |
| stdout/stderr/stdin records | Capped per stream and returned with operation results/events | Event/log retention and diagnostic-log access |
| Result images | Filesystem continuation point when persistence produces one | Deletion, encryption, region, tagged/reference exceptions |
| Preserved environment | `preserve_env=true` writes merged environment values to image metadata | Retention and deletion behavior |
| Local downloads | Written to the caller's filesystem | Governed by the caller's storage controls |
## Network boundary
`networking.enabled=false` starts the VM without a guest network interface. The setting defaults to true and must be supplied on every relevant spawn. If a workload requires destination allowlists, private networking, ingress, specific DNS controls, or customer network logs, confirm support with the Sandboxes team before deployment.
## Handle credentials
Keep the Sandboxes API token outside guest code. Use short-lived, least-privilege workload credentials, pass them only when needed, and avoid retained files, preserved environment metadata, command lines, and output. Do not place registry passwords in Dockerfile build arguments or source.
A disposable filesystem result only prevents the run's filesystem changes from becoming a continuation image. It does not confirm deletion of uploads, operation records, or platform logs. Contact [contree@nebius.com](mailto:contree@nebius.com) before using data that requires a specific encryption-at-rest, residency, deletion, or retention guarantee.
For support, share operation and image UUIDs, timestamps, client versions, terminal status, and redacted errors. Remove tokens, customer files, environment values, and unredacted output.
# Troubleshooting
Source: https://docs.tokenfactory.nebius.com/sandboxes/operate/troubleshooting
Diagnose access, execution, output, state, subprocess, network, and concurrency failures.
Find your symptom below. The [support bundle](#support-bundle) lists the details to collect if you need help.
> [!WARNING]
>
> If a request was interrupted, check its operation ID before submitting the command again. Accepted work may still be running; resubmitting can run it twice. If no operation ID was returned, resolve the uncertain submission before retrying.
## Access and images
### 401 or invalid credential
Refresh or replace the credentials using [Set up access](/sandboxes/start/set-up-access). Check token expiry, configuration, and the current profile.
### 403
Select the intended project and confirm Sandboxes access. Inspect the project header and token permissions too: activation is not the only cause of a 403.
### Image or tag not found
Resolve the tag again or use a recorded immutable UUID. Check the project, literal tag, and UUID in the request.
### No result image
Check `disposable`, terminal status, and the result field. A disposable result cannot be reused. Retry from the input image only when execution is safe.
## Execution and output
### No output
Flush buffered output, check stderr, and inspect the final process state. Confirm that the command started, the intended stream was selected, and output was not truncated.
### Nonzero exit code
Correct the workload input or code using its exit code and output. A nonzero process exit is a workload result.
### Timed out or signaled
Inspect `timed_out`, the signal, and exit code. Classify this separately from test failure and retry from known state. See [Timeouts and disconnections](#timeouts-and-disconnections).
### Stream ended
Resume from the last processed event ID when supported, then query final operation status. Keep the event cursor and operation ID: ending the stream does not establish that execution ended.
## Subprocesses and input
### Stdin write timed out
Reconcile delivery using the child ID and last application sequence. The input may already have arrived; do not blindly replay the write.
### Child missing
Check parent status and the subprocess ID. A child cannot outlive a finalized parent; start a new operation.
## Service and networking
### Rate or service rejection
Inspect the HTTP status, response, and token limits. Back off only as instructed. An undocumented 503 does not establish a capacity problem.
### Network unavailable
Check the spawn request's `networking` field and guest interfaces. Enable networking when required, or keep verification offline.
## Timeouts and disconnections
### REST request or wait timeout
Query a known operation ID before resubmitting: accepted remote work may continue.
### SDK 0.3.6 wait timeout
Resolve the operation outcome. The client attempts best-effort cancellation, but that attempt does not establish that cancellation succeeded.
### Stream disconnect
Resume from the last fully processed event ID and inspect final status. Execution is independent of observation.
### Execution timeout
Inspect the terminal process result, including `timed_out`. Reuse a result image only when it is present and the workload validates it.
### Stdin write timeout
Reconcile with application sequence IDs and avoid automatic replay: the input may have been delivered.
### Image expiry
Recreate the image from pinned inputs and preparation steps. Its stored filesystem is no longer available.
## Support bundle
Send the operation UUID, input and result image UUIDs when available, client version, timestamp, terminal status, a minimal reproduction, and redacted status/output to [contree@nebius.com](mailto:contree@nebius.com). Do not send authorization headers, API keys, secrets, customer files, or complete unredacted logs.
# Update images and clients
Source: https://docs.tokenfactory.nebius.com/sandboxes/operate/update-images-and-clients
Refresh prepared images, pin immutable inputs, and validate client upgrades.
Treat a prepared image as a reproducible build output. Record its immutable UUID, base reference, dependency lock, setup revision, client version, and smoke-test result.
## Refresh an environment
1. Update the pinned base or dependency inputs.
2. Re-run the documented OCI import, setup operation, or `contree build` workflow.
3. Record the new result UUID.
4. Run a disposable smoke test from that UUID.
5. Move a development tag only after validation.
6. Keep the previous known-good UUID for rollback until retention policy permits removal.
A tag can resolve to a different image later. Reproducible evaluation and recovery should use UUIDs.
## Upgrade clients
The examples in this documentation target Python SDK 0.3.6 and CLI 0.9.4. Pin the exact line used in production, review the Sandboxes changelog and generated signatures, then run onboarding, state reuse, binary download, failure classification, and any streaming or subprocess checks used by the application.
Python SDK 0.3.6 starts work when a prepared run object is awaited; it does not expose a public detached-start operation handle. A wait timeout attempts best-effort cancellation. REST transport behavior and CLI session behavior are separate contracts.
Before upgrading, confirm that the Sandboxes service supports the intended backend, SDK, CLI, and MCP combination. Ask the Sandboxes team about deprecation timelines when an upgrade depends on a specific support window. Validate the exact versions against representative workload paths before moving production tags or clients.
If a refreshed environment fails, switch workloads back to the recorded prior UUID, inspect the failed build or operation, and rebuild from pinned inputs. A rollback starts a new operation from saved filesystem state; it does not restore memory or processes.
# Sandboxes overview
Source: https://docs.tokenfactory.nebius.com/sandboxes/overview
Give applications and AI agents an isolated environment to execute code, evaluate results, and work with files.
> [!NOTE]
>
> Sandboxes is in Beta, please [request access](https://tokenfactory.nebius.com/sandboxes/about) here. \
> Your feedback is welcome, please send it to [contree@nebius.com](mailto:contree@nebius.com) or [Discord](https://discord.com/channels/1222156136380235877/1476967257585221845). \
> See [Limits, retention, and usage](/sandboxes/operate/limits-retention-and-usage) before planning a workload.
Sandboxes gives applications and AI agents an isolated place to execute code. Use it when a task needs a runtime, tools, or dependencies to do work and return a result.
Running generated code or third-party tools inside your application gives that code access to the application's execution environment. A sandbox separates the workload from that environment: your application supplies inputs, starts the work, and collects its results. Choose which files, credentials, and network access to give the workload; see [Security and data handling](/sandboxes/operate/security-and-data-handling).
## When to use Sandboxes
* **Give agents a place to act.** Run generated code and command-line tools as part of an agent task. Return output and files so the agent can decide what to do next.
* **Test and evaluate code.** Run checks on proposed changes or evaluation cases in a controlled environment, then use the results to decide whether the work meets your criteria.
* **Process data and produce files.** Execute scripts that transform input files, compute results, or generate artifacts for your application to retrieve.
## Get started
> [card] [Start with Python](/sandboxes/start/python-quickstart)
>
> Run two operations with the SDK: save a file, then read it from the returned image.
> [card] [Start with the CLI](/sandboxes/start/cli-quickstart)
>
> Run the same save-and-reuse workflow from a terminal.
## How execution works
Each run in Sandboxes is an **operation**: it starts fresh compute from an image, runs your command, and returns its output and process result. An image supplies the starting filesystem, including the tools, dependencies, and input files prepared for the task. Choose whether to save changed files as an image for the next run.
A saved image contains filesystem state. It does not retain a running process, process memory, open file handles, network connections, or a live terminal. Read [Execution lifecycle](/sandboxes/concepts/execution-lifecycle) before building a long-running or interactive workflow.
Choose whether to save filesystem changes before submitting an operation. Every operation starts fresh compute, regardless of that choice. When saving, continue only from an image returned in the result. See [Execution lifecycle](/sandboxes/concepts/execution-lifecycle) for the complete state model.
```mermaid theme={null}
flowchart TD
A["Input image
Saved files"] --> B["Before execution
Choose save or discard"]
B --> C["Fresh operation
Run command"]
C --> D["Output and result
Optional saved image"]
```
## The first workflow
**1. Set up access and choose an image**
[Set up access](/sandboxes/start/set-up-access), then find an available base image.
**2. Choose whether to save changes**
Select **save** to request a reusable result image or **discard** for an operation whose filesystem changes can end with the run.
**3. Submit a command**
Run one command as an operation. The service starts fresh compute from the selected image.
**4. Check both results**
Check the operation outcome and the process exit state.
**5. Record saved state**
If the run saved state, record and inspect the returned image UUID before reusing it.
The persistence choice must be made before the operation is submitted. A disposable run can return output, but its filesystem changes are not a continuation point.
Use [Choose an interface](/sandboxes/start/choose-an-interface) for REST and MCP routes.
## Build your workflow
The following recipes show how to compose individual steps within those broader jobs.
> [card] [Compare two fixes](/sandboxes/cookbook/try-two-coding-fixes)
>
> Test two patches from the same starting image and continue from the passing version.
> [card] [Prepare once and reuse](/sandboxes/cookbook/prepare-once-reuse-safely)
>
> Save files and dependencies once, then use them in independent operations.
> [card] [Stream test progress](/sandboxes/cookbook/stream-a-build-or-test-run)
>
> Watch a build or test run, reconnect to its event stream, and check the final result.
> [card] [Download an artifact](/sandboxes/cookbook/generate-and-download-binary-artifact)
>
> Generate a binary file in an operation, download it, and verify its contents.
For interactive work, [start an additional process](/sandboxes/cookbook/interact-with-a-process) inside an active operation and send it input.
## What survives
| Item | After an operation ends |
| - | - |
| Stdout, stderr, and process state | Available through the operation result, subject to documented output and retention limits. |
| Filesystem changes | Reusable when the operation returns a saved image that you can read. |
| Environment values | Available to the current process. They persist only when the interface explicitly saves both the image and supported environment metadata. |
| Running processes and services | End with the operation. |
| Process memory, open file handles, and network connections | Do not carry into a later operation. |
| Client wait or event stream | Can end separately from remote execution. Inspect the operation before resubmitting. |
## Core identifiers
| Identifier | Identifies |
| - | - |
| Image UUID | An immutable stored filesystem state. |
| Operation ID | One asynchronous service operation. |
| Subprocess ID | A process inside one active operation. |
| Upload ID | Uploaded content that can be attached to an operation. |
| Tag | A mutable name that points to an image. |
| Client session name | Client-side workflow state, such as the CLI's selected image and history. |
These identifiers are not interchangeable. Record immutable image UUIDs and operation IDs in reproducible workflows.
## Continue
* [Set up access](/sandboxes/start/set-up-access)
* [Python quickstart](/sandboxes/start/python-quickstart)
* [CLI quickstart](/sandboxes/start/cli-quickstart)
* [Execution lifecycle](/sandboxes/concepts/execution-lifecycle)
* [Images, checkpoints, and branches](/sandboxes/concepts/images-checkpoints-and-branches)
* [Cookbook](/sandboxes/cookbook/index)
* [Reference map](/sandboxes/reference/index)
# Reference map and compatibility
Source: https://docs.tokenfactory.nebius.com/sandboxes/reference/index
Find REST endpoints, Python methods, CLI commands, and MCP tools for your workflow.
Task guides explain complete workflows. Use the interface reference for exact fields, defaults, response schemas, and errors.
## Choose a reference
The Python examples use `contree-sdk==0.3.6`; CLI examples use `contree-cli==0.9.4`. Keep these versions when following the examples.
| Interface | Use the reference for |
| - | - |
| Python SDK | Image objects, async and synchronous execution, file transfer, and sessions |
| CLI | Authentication profiles, image selection, commands, and local session management |
| REST | Request and response fields, operation status, SSE events, and subprocess control |
| MCP | Tools and resources available to an MCP client; check the tool list exposed by your connected server |
The REST base URL is `https://api.tokenfactory.nebius.com/sandboxes/v1`.
## REST operations
* [Spawn an operation](/api-reference/sandboxes/instances/spawn-a-new-container-instance)
* [List operations](/api-reference/sandboxes/operations/list-operations)
* [Get operation status](/api-reference/sandboxes/operations/get-an-operation-status)
* [Cancel an operation](/api-reference/sandboxes/operations/cancel-an-operation)
* [Stream operation events](/api-reference/sandboxes/operations/stream-the-operation-event-log-via-server-sent-events)
* [Spawn an additional subprocess](/api-reference/sandboxes/operation/spawn-an-additional-subprocess-inside-a-running-instance)
* [Get a subprocess result](/api-reference/sandboxes/operation/result-of-one-subprocess-reconstructed-from-its-events)
* [Signal a subprocess](/api-reference/sandboxes/operation/kill-one-subprocess)
* [Write to subprocess stdin](/api-reference/sandboxes/operation/write-to-a-subprocesss-stdin-andor-close-it)
## Images and files
* [List public images](/api-reference/sandboxes/images/list-publicly-available-images)
* [Import an OCI image](/api-reference/sandboxes/images/import-a-container-image-from-a-registry)
* [Inspect an image](/api-reference/sandboxes/inspect/inspect-an-image)
* [List files in an image](/api-reference/sandboxes/inspect/list-files-in-image)
* [Download a file](/api-reference/sandboxes/inspect/download-a-file-from-image)
* [Download a file or directory as an archive](/api-reference/sandboxes/inspect/download-a-file-or-a-directory-from-image-as-tar-archive)
## Python SDK
* [SDK overview](/sandboxes/sdk/index)
* [Getting started](/sandboxes/sdk/python_sdk/getting-started)
* [Running commands](/sandboxes/sdk/python_sdk/running-commands)
* [Python API reference](/sandboxes/sdk/python_sdk/reference/index)
* [Image reference](/sandboxes/sdk/python_sdk/reference/image)
* [Session reference](/sandboxes/sdk/python_sdk/reference/session)
* [Subprocess-style wrapper](/sandboxes/sdk/python_sdk/reference/subprocess)
## CLI
* [CLI overview](/sandboxes/cli/index)
* [Install and authenticate](/sandboxes/cli/tutorial/installation)
* [Tutorial](/sandboxes/cli/tutorial/index)
* [Command reference](/sandboxes/cli/commands/index)
* [Sessions, branches, and rollback](/sandboxes/cli/tutorial/sessions)
## MCP
* [MCP overview](/sandboxes/mcp/index)
* [Quickstart](/sandboxes/mcp/quickstart)
* [Tools reference](/sandboxes/mcp/tools/index)
* [Resources](/sandboxes/mcp/resources)
* [Configuration](/sandboxes/mcp/integration/configuration)
MCP provides tools for commands, images, files, and operation lookup, waiting, and cancellation. For SSE streaming or additional-process controls, use the REST endpoints above. Check your connected server's tool list before configuring an MCP workflow.
## Capability routes
| Task | Route |
| - | - |
| First stateful SDK run | [Python quickstart](/sandboxes/start/python-quickstart) |
| First stateful CLI run | [CLI quickstart](/sandboxes/start/cli-quickstart) |
| Persistence defaults and result identity | [Images, checkpoints, and branches](/sandboxes/concepts/images-checkpoints-and-branches) |
| Submit, poll, and inspect results | [Run commands and handle results](/sandboxes/guides/run-commands-and-results) |
| Stream and resume output | [Stream output and events](/sandboxes/guides/stream-output-and-events) |
| Control an additional process | [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input) |
| Diagnose a failed workflow | [Troubleshooting](/sandboxes/operate/troubleshooting) |
# Develop and test the documentation
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/contributing
User scenarios live in Markdown. `markdown-pytest` collects and executes those
blocks during the same pytest run as the SDK tests. Changes to an example therefore
change the tested program.
## Run the checks
From the repository root:
```bash theme={null}
uv sync --extra dev --extra docs
uv run pytest
make -C docs test
make -C docs check
```
The pytest command runs the standard suite, including documentation. The `test`
target selects Markdown scenarios. SDK e2e tests are outside the default suite;
transport e2e coverage belongs to `contree-client` and is not a gate for these guides.
From `docs/`, use `make html` to build HTML in `_build/html` or `make serve` to
preview it with live reload at [http://127.0.0.1:8000](http://127.0.0.1:8000). Use `make clean` to remove
build output, `make mintlify` for Mintlify output, and `make help` to list targets.
Use `make check` for an HTML build that treats Sphinx warnings as errors.
Set `BUILDDIR` to change the output directory, `SPHINXOPTS` to change Sphinx options,
or `HOST` and `PORT` to configure the preview server. For example:
```bash theme={null}
make -C docs html BUILDDIR=/tmp/contree-sdk-docs
make -C docs serve PORT=8080
```
Run Semgrep in its own tool environment, as the security workflow does. Its
dependencies conflict with the agent integration dependencies:
```bash theme={null}
uv tool run --from semgrep==1.168.0 semgrep ci
```
The fixtures replace client construction with `contree_client.testing` clients.
They provide explicit API outcomes; session logic, operation handling, memory stores,
and SQLite stores remain real. Check both user-visible results and transport calls.
These tests do not claim to execute a remote shell or verify server implementation.
## Add a scenario next to its explanation
Put a `name` comment directly above each Python fence. Keep the program visible,
including required imports. Related blocks can share a name and execution namespace.
Use `name: async test_example` for a block with top-level `await` or `async with`.
Request `doc_api` to get isolated clients, environment variables, and a temporary
working directory. Add the desired responses in a hidden block. Add assertions
in another hidden block with the same test name. Fixtures live in
`tests/docs_fixtures.py`.
Use a unique test name within the page unless blocks form one scenario. The
coverage check rejects uncollected Python fences and executable `literalinclude`
examples, so a new scenario cannot silently fall out of the regular suite.
Do not mark a scenario as skipped merely because its API response is inconvenient
to model. Optional integrations may request their availability fixture.
## Keep tests useful
For a saved run, verify the selected image and history in addition to output.
For a file upload, verify the source bytes, destination, and download image.
For error handling, inject the error and verify recovery or cleanup. A canned
response alone cannot show whether a command was sent correctly.
Build examples prepare files from the Dockerfile and text fences in
[Build a Docker image](./python_sdk/building-images), including scenarios on the advanced page.
Do not keep a second copy of the documented program in a Python test or example file.
Non-Python fences, such as installation commands and Dockerfile input, are explanatory
inputs; `markdown-pytest` itself executes Python fences only.
See the [markdown-pytest documentation](https://mosquito.github.io/markdown-pytest/)
for split blocks, fixtures, hidden code, async tests, and comment syntax.
## Maintain standalone examples
Keep complete scripts in `examples/sync/` and `examples/async/`, with the same
filename for each pair. Keep short API recipes in Markdown instead of copying them
into scripts.
Each script contains a `test_...` function. The examples collector includes all
Python scripts in the default pytest run and rejects scripts without tests.
The tests execute the script’s `__main__` entry point with the same offline client
fixture used by Markdown. Assert requests and observable results, including persisted
state when relevant. A new example must include its test before it can pass CI.
Run just the standalone examples with `uv run pytest examples`.
# ConTree SDK
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/index
Run commands in remote sandboxes, keep their filesystem changes, and try different
paths from the same saved state. Use Python for execution and session history;
ConTree stores the filesystem images on the server.
Start with [Your first sandbox](./python_sdk/getting-started). It covers credentials, a base image,
and a complete program that prints `Hello from ConTree!`. Then continue in order:
1. [Your first sandbox](./python_sdk/getting-started)
2. [Import a Docker image](./python_sdk/images)
3. [Build a Docker image](./python_sdk/building-images)
4. [Advanced usage](./python_sdk/advanced)
Your sandbox can keep more than its latest result. Save a checkpoint, try an
experiment on another branch, and return to the baseline without repeating setup.
Continue with [Work with a Session](./python_sdk/session-model) to learn how
snapshots, branches, rollback, and persistent history fit together.
## Choose your next task
| I want to… | Read |
| - | - |
| Understand sessions, snapshots, and branches | [Work with a Session](./python_sdk/session-model) |
| Select components and control their behavior | [Advanced usage](./python_sdk/advanced) |
| Upload inputs and download an output | [Work with sandbox files](./python_sdk/files) |
| Continue work after restarting Python | [Save and resume a session](./python_sdk/sessions) |
| Try a change and return to a checkpoint | [Branch, switch, and roll back](./python_sdk/branching) |
| Stream output or run several processes in one sandbox | [Advanced: control a running sandbox](./python_sdk/operation) |
| Import a Docker image | [Import a Docker image](./python_sdk/images) |
| Build a filesystem from a Dockerfile | [Build a Docker image](./python_sdk/building-images) |
| Give an agent access to a sandbox | [LangChain DeepAgents](./integrations/langchain) |
| Run Harbor tasks in a ConTree environment | [Run Harbor on ConTree](./integrations/harbor) |
| Change SDK policy or replace a component | [Customize the SDK](./python_sdk/customization) |
| Upgrade an existing application | [Upgrade to the 0.5 session API](./python_sdk/migration) |
## What persists?
The default sandbox reuses one VM between commands. Normal context exit and
explicit `snapshot()` save filesystem changes. An exception discards changes
since the last completed snapshot. The default policy also snapshots after 10
idle seconds. Snapshots are lightweight and can run after every command, but they
stop the VM. Processes and memory do not survive. An unchanged filesystem can
produce the same `image_uuid`; this is normal.
Select `session_type=ContreeSession` or `ContreeAsyncSession` to save each command
automatically in a separate VM. `disposable=True` leaves the session image
unchanged. See [Save after every command](./python_sdk/session-model#save-after-every-command).
History is in memory by default. Supply a SQLite store and a session ID to resume
after Python exits. The store keeps references; filesystem images remain on the
ConTree server. See [Save and resume a session](./python_sdk/sessions).
## Advanced control
Use [Advanced usage](./python_sdk/advanced) to select components, manage ownership,
and follow build events. [Advanced: assemble a sandbox yourself](./python_sdk/manual-sandbox) shows explicit assembly.
Use [Advanced: control a running sandbox](./python_sdk/operation) to manage subprocesses and their event stream.
# Run Harbor on ConTree
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/integrations/harbor
> [!NOTE]
>
> The integration currently supports the minimum features needed to run Terminal
> Bench 2.1 (TB2.1). Broader Harbor support is planned; other datasets have not
> been validated.
## Quick start
This integration requires Harbor 0.22.x and Python 3.12 or newer. Install with
`pip install 'contree-sdk[harbor]'` and configure your connection as described below.
```bash theme={null}
harbor run -t hello-world/hello-world -a oracle \
--env contree_sdk.harbor:ConTreeEnvironment
```
## Connection configuration
Use your saved default profile, or supply the connection through environment
variables:
```bash theme={null}
export CONTREE_URL="https://api.tokenfactory.nebius.com/sandboxes"
export CONTREE_TOKEN="your-api-key"
export CONTREE_PROJECT="your-ai-project"
```
| Variable | Purpose |
| - | - |
| `CONTREE_URL` | ConTree API endpoint. |
| `CONTREE_TOKEN` or `NEBIUS_API_KEY` | Authentication token. |
| `CONTREE_PROJECT` or `NEBIUS_AI_PROJECT` | AI project that runs the sandbox. |
| `CONTREE_PROFILE` | Saved profile name; otherwise, use the active profile from the configuration files. |
| `CONTREE_HOME` | Directory containing `cli.ini` and `auth.ini`. Defaults to `$XDG_CONFIG_HOME/contree`, or `~/.config/contree`. |
Environment credentials take priority when both URL and token are set;
otherwise, the client loads a saved profile. Use `CONTREE_PROFILE=work` to
select a saved profile when environment credentials are not set.
See [SDK connection configuration](../python_sdk/getting-started#connection-sources)
for more about credentials, saved profiles, and configuration files.
## Environment options
Pass ConTree-specific options with `--ek NAME=VALUE`, or through
`environment.kwargs` in a Harbor job configuration.
| Option | Default | Description |
| - | - | - |
| `snapshot_idle_sec` | `1200` (20 minutes) | Positive idle delay in seconds before saving a snapshot, for example `--ek snapshot_idle_sec=1800`. |
| `contree_client` | Created from the connection configuration | Python only: supply a configured async ConTree client. It remains caller-owned. |
The environment keeps one VM running across commands, so files and background
processes remain available until an idle snapshot. Background processes end at
a snapshot boundary and do not resume with the next command.
## Validated datasets
* Terminal Bench 2.1 (TB2.1)
## Current limitations
* Each task needs `[environment].docker_image` set to a prebuilt OCI registry
image containing Bash and `sleep`. Dockerfile builds are not supported.
* Commands use the image’s default user. Harbor can override it with `root` or
a numeric UID; other user names are not supported.
* Compose, GPUs, custom host mounts, and restricted networking are not supported.
* Operation resource settings and Docker inside the VM are not exposed by this
integration. These and other ConTree capabilities will be added and validated
as datasets require them.
* `--no-delete` currently behaves like `--delete`: stopping cancels the VM and
does not save a final image.
## Implementation
The adapter uses the SDK’s `AsyncLazySession` to run Harbor commands as
subprocesses in one ConTree VM. After an idle snapshot, the next command starts
a VM from the saved image.
# LangChain DeepAgents
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/integrations/langchain
The SDK provides deepagents `BaseSandbox` implementations for command execution
and file transfer. Use `ContreeSandbox` with a sync executor, or
`ContreeAsyncSandbox` with an async executor. A session implements the matching contract.
> [!NOTE]
>
> Async snippets with top-level `await` run inside an async function or a notebook
> that supports it. For a standalone script, use the `asyncio.run(main())` structure
> from [Your first sandbox](../python_sdk/getting-started).
The examples use the default sandbox from `create_sandbox_session`. Commands and
uploads use the same VM. Downloads automatically save its current filesystem
before reading; this stops the VM. The next command starts from the saved image.
The factory handles connection setup and cleanup.
## Install and test the backend
This integration requires Python 3.11 or newer. Install the development API from
the repository root, as in [Your first sandbox](../python_sdk/getting-started):
```bash theme={null}
pip install -e ".[langchain,async]"
```
The extra pins deepagents 0.7.10, the version tested with this SDK. Its async file
tools delegate to `aexecute` and `aupload_files`. Version 0.6.8 instead calls sync
methods from those tools and is incompatible with `ContreeAsyncSandbox`.
The sandbox image needs a POSIX shell, Python 3, and the file utilities used by
deepagents, including `grep` for search. Replace the example
`tag:python:3.12-alpine` with an image available on your endpoint.
Configure a connection as described in [Connection sources](../python_sdk/getting-started#sandbox-connection).
This example exercises the backend directly, so no model credentials are needed.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.langchain import ContreeSandbox
>
>
> with create_sandbox_session(image="tag:python:3.12-alpine") as session:
> sandbox = ContreeSandbox(session)
> result = sandbox.execute("echo hello")
> print(result.output)
> print("exit:", result.exit_code)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.langchain import ContreeAsyncSandbox
>
>
> async with create_sandbox_session(image="tag:python:3.12-alpine") as session:
> sandbox = ContreeAsyncSandbox(session)
> result = await sandbox.aexecute("echo hello")
> print(result.output)
> print("exit:", result.exit_code)
> ```
The adapter runs commands with `disposable=False`. Its next tool call sees the
filesystem changes. It does not close the session, client, or store. Use SQLite
when the agent needs to resume after a Python restart.
## Connect the backend to an agent
Pass the sandbox as `backend=` to `deepagents.create_deep_agent`. Supply the model
configured by your application. Keep the client open for the entire agent invocation.
The following function accepts that model and uses the connection configured in
[Connection sources](../python_sdk/getting-started#sandbox-connection):
> [tab] Sync
>
> ```python theme={null}
> from deepagents import create_deep_agent
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.langchain import ContreeSandbox
>
>
> def ask_agent(model):
> with create_sandbox_session(image="tag:python:3.12-alpine") as session:
> agent = create_deep_agent(model=model, backend=ContreeSandbox(session))
> request = {"messages": [{"role": "user", "content": "Create a calculator script and run it."}]}
> return agent.invoke(request)
> ```
> [tab] Async
>
> ```python theme={null}
> from deepagents import create_deep_agent
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.langchain import ContreeAsyncSandbox
>
>
> async def ask_agent(model):
> async with create_sandbox_session(image="tag:python:3.12-alpine") as session:
> agent = create_deep_agent(model=model, backend=ContreeAsyncSandbox(session))
> request = {"messages": [{"role": "user", "content": "Create a calculator script and run it."}]}
> return await agent.ainvoke(request)
> ```
Model-provider installation, credentials, and model selection belong to the agent
application. The SDK does not choose a provider or supply a model key.
## Advanced: file transfers and executor contracts
Uploads call `session.write_file(path, content)`. Its default implementation writes
binary stdin with `cat`, creates parent directories, and requests no snapshot.
Custom executors can override `write_file` without changing this adapter.
Downloads call `session.read_file()`. Lazy sessions read the active VM through
live inspect, so downloads preserve running processes and do not force a snapshot.
| Sync sandbox | Async sandbox |
| - | - |
| `execute(command)` | `await aexecute(command)` |
| `upload_files([(path, bytes)])` | `await aupload_files([(path, bytes)])` |
| `download_files([path])` | `await adownload_files([path])` |
File paths must be absolute. Transfers return per-file responses; inspect `error`
before reading their content. The async adapter’s synchronous methods raise
`NotImplementedError`. Each adapter serializes its own calls, but callers sharing
an executor must coordinate other mutations themselves.
To use another backend implementation, follow [Customize the SDK](../python_sdk/customization).
See [deepagents sandboxes](../python_sdk/reference/langchain) for API signatures.
# mini-swe-agent
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/integrations/mini-swe-agent
The `ContreeEnvironment` bundled with mini-swe-agent 2.4.6 uses the previous SDK
API, including `ContreeSync` and SDK image objects. Those imports are removed in
this release. That adapter cannot run with the new session API.
Installing `mini-swe-agent[contree]` does not by itself port the adapter.
Use [LangChain DeepAgents](./langchain) for a supported integration, or adapt the environment to
`ContreeSession` and its `run()` result. The public execution contracts are described
in [Customize the SDK](../python_sdk/customization).
This compatibility statement applies to the inspected 2.4.6 adapter. Check the
adapter shipped with another mini-swe-agent version before using it.
# Advanced usage
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/advanced
The sandbox and image helpers manage clients, stores, and cleanup.
Use the options below when you need to select components or control their behavior.
For basic workflows, start with [Your first sandbox](./getting-started), [Import a Docker image](./images), and
[Build a Docker image](./building-images). Connection settings remain in [Connection sources](./getting-started#sandbox-connection);
[Share one client](#shared-image-client) shows one client shared across all three workflows.
For the workflow itself, continue with [Work with a Session](./session-model):
save checkpoints, compare branches, roll back experiments, and resume saved work.
## What each component does
| Component | Purpose | Read more |
| - | - | - |
| **Store** (`store=` in helpers) | Keeps history, uploaded-file references, and imported images in typed trees. Supports resume and result reuse. | [Save and resume a session](./sessions) and [Tree stores](./reference/store) |
| **Client** (`client=`) | Sends requests to ConTree using your endpoint, credentials, and project. One client can serve import, build, and sandbox operations. | [Share one client](#shared-image-client) |
| **Session** | Tracks the current image and history. `ContreeSession` runs each command as a separate operation and can save its result. | [Work with a Session](./session-model) |
| **LazySession** | Keeps commands in one running VM until a snapshot. This is the default session behind `create_sandbox_session`. | [Work with a Session](./session-model) |
| **Operation** | Gives access to one remote operation: wait for completion, run subprocesses, read output, or stop it. | [Advanced: control a running sandbox](./operation) |
| **FileTransfer** (`file_transfer=`) | Prepares uploads and reads files from saved images. It does not access unsaved files inside a running VM. | [Work with sandbox files](./files) and [File transfer](./reference/files) |
| **Snapshot policy** | Decides when a lazy session saves filesystem changes and stops its VM. | [Sessions and operations](./reference/session) |
| **Commit policy** (`commit_policy=`) | Decides whether a completed operation’s result becomes part of session history. | [Select a commit policy](./customization#select-a-commit-policy) |
| **Docker builder** | Executes Dockerfile instructions and returns an image UUID. It uses Store trees for layer history and uploaded results. | [Build a Docker image](./building-images) and [Dockerfile builders](./reference/docker) |
A memory Store keeps history only for that store instance. A SQLite Store keeps
it across Python restarts. The filesystem images themselves remain on the ConTree
server. Deleting an upload-cache tree removes its reuse records without changing session history.
Sandbox history and upload reuse share a memory Store by default. The
import and build helpers use a persistent SQLite Store by default. See
[Advanced: assemble a sandbox yourself](./manual-sandbox) for component construction and ownership.
### Bring your own storage
Start with [Save and resume a session](./sessions) to choose memory or SQLite storage, save work, and
continue a previous session. For your own database or service, implement
`SyncStore` or `AsyncStore` and pass it through `store=`. See [Implement a custom Store](./custom-store)
in Advanced Usage for an example and the storage requirements.
## Share one client
For a workflow with several operations, initialize a client once. Pass it through
`client=` as a dependency to the import helper, build helper, and sandbox factory.
This reuses the connection and gives your application one place to configure it.
Each operation leaves this client open; the outer context closes it.
Use the `build-context` directory from
[Create a small build context](./building-images#create-a-small-build-context).
These programs import the base under the `alpine:latest` ConTree tag, build that
context, and read its result. The Dockerfile’s `FROM alpine:latest` resolves the
imported image.
> [tab] Sync
>
> ```python theme={null}
> """Reuse one client for import, build, and sandbox operations."""
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import create_sandbox_session, sync_build_image, sync_import_image
>
>
> def main() -> None:
> # Create one client for the full workflow.
> profile = profiles.from_env() or profiles.resolve_profile()
> with ContreeClient.from_profile(profile) as client:
> # Import the base and give it the tag used by FROM.
> sync_import_image(
> "docker://mirror.gcr.io/library/alpine:latest",
> tag="alpine:latest",
> client=client,
> )
>
> # Build with the same client, then read the resulting filesystem.
> image = sync_build_image("build-context", client=client)
> with create_sandbox_session(image=image, client=client) as sandbox:
> content = sandbox.read_file("/built.txt")
> print(content.decode())
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import create_sandbox_session, async_build_image, async_import_image
>
>
> async def main() -> None:
> # Create one client for the full workflow.
> profile = profiles.from_env() or profiles.resolve_profile()
> async with ContreeAsyncClient.from_profile(profile) as client:
> # Import the base and give it the tag used by FROM.
> await async_import_image(
> "docker://mirror.gcr.io/library/alpine:latest",
> tag="alpine:latest",
> client=client,
> )
>
> # Build with the same client, then read the resulting filesystem.
> image = await async_build_image("build-context", client=client)
> async with create_sandbox_session(image=image, client=client) as sandbox:
> content = await sandbox.read_file("/built.txt")
> print(content.decode())
>
>
> asyncio.run(main())
> ```
## Select the session class and components
Some async snippets use top-level `await`. Run them inside an async function or
a compatible notebook. Complete programs use `asyncio.run(main())`.
`session_type` accepts a class. Without it, the context selects `LazySession` or
`AsyncLazySession`. An explicitly selected class must match the context mode:
`session_type=AsyncLazySession` with a synchronous `with` raises `TypeError`
before creating a client. The same rule applies to `client_type` and supplied
store, file transfer, and client objects.
Lazy sessions accept `vm_timeout` (default `3600`) and `snapshot_timeout`
(default `30`) through `session_kwargs`. The VM timeout must exceed the snapshot
timeout and fit the server’s limit. The session records when VM startup begins.
After startup, it schedules a snapshot using the effective request timeout minus
`snapshot_timeout` and the elapsed startup time. When the timer expires, the session stops
accepting commands, drains active commands and inspections, and saves a snapshot.
This timer applies alongside the selected snapshot policy. Active commands must
finish before the server’s hard deadline; a snapshot cannot preserve running processes.
Subprocess `wait()` and `pipe_to()` assemble their result from the shared event
stream without an extra HTTP request. `resources.cost` is not populated because
the server calculates it separately. Use `client.operation_subprocess(operation.uuid, handle.spid)` for the full server result, with `await` for an async client.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import LazySession, create_sync_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
> from contree_sdk.store import SyncSQLiteStore
>
>
> with SyncSQLiteStore("sandbox.db") as store:
> with create_sync_sandbox_session(
> image="tag:alpine:latest",
> session_type=LazySession,
> session_id="work",
> store=store,
> cache_ttl=60,
> cwd="/",
> env={"LANG": "C.UTF-8"},
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(120), "snapshot_timeout": 30},
> ) as session:
> session.run("echo", args=["Saved on exit"])
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import AsyncLazySession, create_async_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async with AsyncSQLiteStore("sandbox.db") as store:
> async with create_async_sandbox_session(
> image="tag:alpine:latest",
> session_type=AsyncLazySession,
> session_id="work",
> store=store,
> cache_ttl=60,
> cwd="/",
> env={"LANG": "C.UTF-8"},
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(120), "snapshot_timeout": 30},
> ) as session:
> await session.run("echo", args=["Saved on exit"])
> ```
Custom classes implement `SyncExecutor` or `AsyncExecutor`. Lazy subclasses
receive an underlying `ContreeSession` or `ContreeAsyncSession`, plus
`session_kwargs`. Other classes receive the client and the standard Session
constructor arguments, plus `session_kwargs`. Subclass an existing session to
retain its execution and lifecycle rules. The factory never substitutes a
different class for an explicitly selected class.
Selecting `ContreeSession` or `ContreeAsyncSession` saves each command by default
and starts the next command in a separate VM. Use `disposable=True` to leave
the session image unchanged. See [Save after every command](./session-model#save-after-every-command).
Snapshots are lightweight; saving after every command is supported. A snapshot
stops the VM and can return the same image UUID if files have not changed.
| Argument | Purpose |
| - | - |
| `image`, `session_id` | Initial image or stored session to resume. At least one is required. |
| `node_id` | Select a saved node explicitly when resuming, including a tree with multiple continuations. |
| `store` | Session history store; defaults to a new memory store of the selected mode. |
| `cache_ttl` | Upload reuse through the shared Store expires after 60 seconds by default. Choose a TTL no longer than your server’s upload retention. |
| `cwd`, `env`, `commit_policy` | Configuration of the underlying session. |
| `file_transfer` | Replace file I/O; a cached transfer wraps it using the same Store. |
| `session_kwargs` | Additional constructor arguments for the selected session class, including lazy snapshot options. Factory-managed arguments take priority over duplicates in this mapping. |
| `client` | Borrow an already configured client. Cannot be combined with connection settings or `client_type`. |
| `client_type` | Select a contree-client class. Defaults are HTTPX for sync and aiohttp for async. |
| Other keyword arguments | Forwarded unchanged to the client constructor through `from_profile`, including `timeout`, `retry`, `identity`, TLS and backend-specific settings. Credentials follow [Connection sources](./getting-started#sandbox-connection); use `url`, not `base_url`. |
Sandbox, image import, and image build helpers use `contree_client.RetryPolicy()`
for clients they create. Pass `retry=RetryPolicy(...)` to customize the policy,
or `retry=None` to disable retries. A supplied `client=` keeps its configuration.
Retry decisions and delays remain the responsibility of contree-client.
Uploaded-file cache entries are separated by endpoint, project, and token. The
cache does not replace history storage or enable uploads to an already running
LazySession VM.
## Ownership and extension
Each context object permits one entry, including a failed entry. Re-entry,
nesting, and mixing sync/async entry on that object raise `RuntimeError`; call the
factory again to get a new context.
The factory closes resources it creates. Supplied clients, storage, and
file transfers remain caller-owned and must be ready for use. A session’s context
exit runs before the owned client closes. Async cleanup is joined even when the
caller cancels again; a body exception takes priority over cleanup errors.
All three factories call `session_maker(context_type, ...)` with their respective
context class. `SandboxSessionContext` composes `SyncSandboxSessionContext` and
`AsyncSandboxSessionContext`. For a custom context, supply a class accepting
`SandboxConfig` to `session_maker`. See [Sandbox factories](./reference/sandbox) for the shared
parameter signature and context contracts.
For complete sync and async examples of the component assembly behind this
factory, see [Advanced: assemble a sandbox yourself](./manual-sandbox).
## Tag a saved result
Run a setup command, save its result, and give that image a reusable name. This
example selects `ContreeSession` or `ContreeAsyncSession`, which saves each command
by default as an independent operation. The default lazy sandbox instead
saves at a snapshot boundary; see [Work with a Session](./session-model).
> [tab] Sync
>
> ```python theme={null}
> """Save a setup command as a reusable image."""
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> def main() -> None:
> profile = profiles.from_env() or profiles.resolve_profile()
> with ContreeClient.from_profile(profile) as client:
> with create_sandbox_session(image="tag:alpine:latest", session_type=ContreeSession, client=client) as sandbox:
> sandbox.run(shell="echo ready > /ready.txt")
> client.update_image_tag(sandbox.image_uuid, "prepared-base")
> print(sandbox.image_uuid)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async def main() -> None:
> profile = profiles.from_env() or profiles.resolve_profile()
> async with ContreeAsyncClient.from_profile(profile) as client:
> async with create_sandbox_session(
> image="tag:alpine:latest", session_type=ContreeAsyncSession, client=client
> ) as sandbox:
> await sandbox.run(shell="echo ready > /ready.txt")
> await client.update_image_tag(sandbox.image_uuid, "prepared-base")
> print(sandbox.image_uuid)
>
>
> asyncio.run(main())
> ```
Use `image="tag:prepared-base"` in another sandbox. The tag refers to the saved
filesystem; it does not copy session history, environment overrides, or defaults.
Assigning an existing tag moves it to the new image.
Image listing and tag removal are available through `list_images()` and
`delete_image_tag()` on the client. Closing a client or local store does not
delete server images. Deleting a server image can invalidate saved session history.
## Assemble the builder yourself
The helpers create a client and one SQLite Store for layer history and reusable uploads. They scope the build session to the context path and connection,
call the Docker builder, and close the resources they created.
Use the builder directly to manage these dependencies and their lifetime yourself.
The following example keeps a builder inside the client context and uses its
default memory Store. For persistence, pass `store=SyncSQLiteStore(...)` or its
async equivalent and close it yourself. Helpers accept the same dependency as `store=`.
Use `builder_type=` and `builder_kwargs=` to extend a builder through a helper.
### Rebuild a multi-stage image after changing inputs
This standalone example creates `multi-context` in the current directory. Its
first stage builds an output file. The second stage copies only that output with
`COPY --from`. Use a base image with `cat` and a POSIX shell.
The builder downloads regular files as bytes and attaches them at their final
paths to the next operation. The file specification carries permissions and
ownership, including explicit `--chown`/`--chmod` overrides.
For directory sources, the builder exports tar and asks the live API to unpack
it directly into the destination with merge enabled. This preserves existing
entries that are absent from the archive. The VM runs `sleep infinity` during
transfer. Explicit directory overrides run as subprocesses after unpacking and
before the builder signals the main process to save the layer. These commands
change only entries supplied by the archive. Directory copies require
`sleep infinity` and, for overrides, `chown` or `chmod`; they do not require `tar`.
Keep the same builder, store, and build session to observe layer reuse. Changing
an ignored file leaves the build inputs unchanged. Changing `message.txt`
invalidates the source RUN and the stage copy that depends on its output.
> [tab] Sync
>
> ```python theme={null}
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk.docker import ContreeDockerBuilder
>
>
> context = Path("multi-context")
> context.mkdir(exist_ok=True)
> (context / "Dockerfile").write_text(
> "ARG BASE_IMAGE\n"
> "FROM ${BASE_IMAGE} AS source\n"
> "COPY . /src/\n"
> "RUN cat /src/message.txt > /built.txt\n"
> "FROM ${BASE_IMAGE}\n"
> "COPY --from=source /built.txt /result.txt\n"
> )
> (context / ".dockerignore").write_text("ignored.txt\n")
> (context / "message.txt").write_text("one\n")
> (context / "ignored.txt").write_text("local notes\n")
>
> with ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> builder = ContreeDockerBuilder(client)
>
> def rebuild():
> events = []
> image = builder.build(
> context,
> build_args={"BASE_IMAGE": "tag:alpine:latest"},
> session_id="multi-stage-demo",
> on_event=events.append,
> )
> started = [event for event in events if event.type == "operation_started"]
> return image, started
>
> first_image, first_runs = rebuild()
> repeated_image, repeated_runs = rebuild()
> (context / "ignored.txt").write_text("changed local notes\n")
> ignored_image, ignored_runs = rebuild()
> (context / "message.txt").write_text("two\n")
> changed_image, changed_runs = rebuild()
>
> assert len(first_runs) == 2 # Source RUN and snapshot of the attached stage file.
> assert repeated_runs == ignored_runs == []
> assert first_image == repeated_image == ignored_image
> assert len(changed_runs) == 2
> ```
> [tab] Async
>
> ```python theme={null}
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk.docker import ContreeAsyncDockerBuilder
>
>
> context = Path("multi-context")
> context.mkdir(exist_ok=True)
> (context / "Dockerfile").write_text(
> "ARG BASE_IMAGE\n"
> "FROM ${BASE_IMAGE} AS source\n"
> "COPY . /src/\n"
> "RUN cat /src/message.txt > /built.txt\n"
> "FROM ${BASE_IMAGE}\n"
> "COPY --from=source /built.txt /result.txt\n"
> )
> (context / ".dockerignore").write_text("ignored.txt\n")
> (context / "message.txt").write_text("one\n")
> (context / "ignored.txt").write_text("local notes\n")
>
> async with ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> builder = ContreeAsyncDockerBuilder(client)
>
> async def rebuild():
> events = []
> image = await builder.build(
> context,
> build_args={"BASE_IMAGE": "tag:alpine:latest"},
> session_id="multi-stage-demo",
> on_event=events.append,
> )
> started = [event for event in events if event.type == "operation_started"]
> return image, started
>
> first_image, first_runs = await rebuild()
> repeated_image, repeated_runs = await rebuild()
> (context / "ignored.txt").write_text("changed local notes\n")
> ignored_image, ignored_runs = await rebuild()
> (context / "message.txt").write_text("two\n")
> changed_image, changed_runs = await rebuild()
>
> assert len(first_runs) == 2 # Source RUN and snapshot of the attached stage file.
> assert repeated_runs == ignored_runs == []
> assert first_image == repeated_image == ignored_image
> assert len(changed_runs) == 2
> ```
The cache comparison uses file content and execution inputs. It does not require
the server to return a different image UUID for every submission. To retain this
cache across Python restarts, supply a SQLite Store as above.
Source files and directory archives are keyed by immutable image UUID and source path, without a
client expiry. Before reuse, the builder checks the uploaded file with HEAD;
a missing upload is downloaded from the image and uploaded again. Cached layers also receive a
HEAD check, and missing images are rebuilt. Store retention still applies.
The live API restores regular-file permission bits from tar. Its current
implementation creates archive directories with mode `0755` and does not restore
ownership or timestamps. Explicit directory overrides apply after unpacking. File attachments retain
the source file mode and ownership unless COPY overrides them.
## Observe a live build
Use the `build-context` files from [Build a Docker image](./building-images) for these examples.
Pass `on_event=` to receive `BuildEvent` notifications while a build runs.
Output events arrive before RUN completes and carry raw `bytes`. Decode or format
them in your application. Each operation uses the same reader for output and its
final result.
| `event.type` | Meaning |
| - | - |
| `step_started` | A parsed or synthetic directive is about to execute. |
| `operation_started` | RUN submitted an operation; `operation_uuid` is available. |
| `stdout`, `stderr` | A chunk of live output is in `event.data`. |
| `cache_hit` | The directive reused an existing image without starting RUN. |
| `step_completed` | The directive completed, including any required history commit. |
| `step_failed` | The directive raised; `event.error` holds the original exception. |
`event.step.id` is unique within one build. `event.step.index` is the zero-based
parsed directive index, including ARG and metadata instructions. Synthetic steps
have `index=None`. A nested step has `parent_id` set to its enclosing step’s ID.
A final COPY/ADD flush appears as a synthetic `RUN :`; a stage flush appears as a
child of the next FROM. If a nested step fails, both it and its parent report the
same exception.
Events include elapsed step time, image IDs, and the operation UUID when available.
The terminal RUN event also contains its typed `InstanceResult`, including nonzero
exit codes. A cache hit emits no output and no new operation UUID.
> [tab] Sync
>
> ```python theme={null}
> import sys
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk.docker import BuildEvent, ContreeDockerBuilder
>
>
> def report(event: BuildEvent) -> None:
> if event.type == "stdout":
> sys.stdout.buffer.write(event.data)
> sys.stdout.buffer.flush()
> elif event.type == "stderr":
> sys.stderr.buffer.write(event.data)
> sys.stderr.buffer.flush()
> elif event.type == "step_started":
> print(f"Step {event.step.id}: {event.step.keyword}", flush=True)
>
>
> with ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> builder = ContreeDockerBuilder(client)
> image_uuid = builder.build(
> "build-context",
> on_event=report,
> )
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
> import sys
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk.docker import BuildEvent, ContreeAsyncDockerBuilder
>
>
> async def report(event: BuildEvent) -> None:
> if event.type in {"stdout", "stderr"}:
> stream = sys.stdout.buffer if event.type == "stdout" else sys.stderr.buffer
> await asyncio.to_thread(stream.write, event.data)
> await asyncio.to_thread(stream.flush)
> elif event.type == "step_started":
> await asyncio.to_thread(print, f"Step {event.step.id}: {event.step.keyword}", flush=True)
>
>
> async with ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> builder = ContreeAsyncDockerBuilder(client)
> image_uuid = await builder.build(
> "build-context",
> on_event=report,
> )
> ```
Callbacks run serially in the thread or task executing `build()`. The async builder
accepts both synchronous and awaitable callbacks. Keep callbacks short. The async
example offloads local output writes so they do not block the event loop. For a
live UI, a callback can also feed a bounded queue that another task consumes.
A callback error, including a closed output pipe, aborts the build and cancels its
active RUN operation. Async task cancellation and sync interruption follow the
same cleanup path. Error notifications cannot replace the original exception.
Callbacks do not roll back completed layers. File, parse, and final tag errors
raise directly; these do not create directive events outside a running step.
## Customize a build
Pass `on_step=` to receive a `BuildStepEvent` for each parsed directive. It includes
duration, cache-hit status, image IDs, and any error. Keep callbacks short; a callback
exception can stop the build. The async builder also accepts an awaitable callback.
Use `parser=`, `session_factory=`, or `execute_directive()` for custom behavior.
See [Customize the SDK](./customization) and [Dockerfile builders](./reference/docker).
## Upload cache lifetime and scope
COPY and ADD keep reusable upload records in the same Store as layer history.
Tree kinds separate these records. Namespaces and layer hashes include the
endpoint, project, and credential scope, so shared storage does not reuse another
server’s UUIDs.
Local paths and source URLs are retained through the public file-source registry.
See [Reuse uploads and retain their sources](./caching) for enumeration and invalidation.
The default upload lifetime is 90 days. Cache hits and URL responses with status
304 do not extend it. Override `create_context()` and set
`context.upload_cache_ttl` to choose a shorter lifetime for your server. Expiry
causes a new upload when the directive runs; it does not invalidate an existing
image layer. A 304 response without a live cached upload raises `DockerBuildError`.
Local COPY uses a temporary snapshot for its content hash and upload. Async COPY
limits concurrent snapshots and uploads through `context.upload_concurrency`
(default four). URL ADD streams into a temporary file before upload and closes the
response body, including conditional responses. These paths bound memory usage;
temporary disk space must hold the files currently being prepared.
## Assemble the sandbox yourself
The factory resolves a connection, creates a client and memory store, connects
file transfer to a base session, and wraps it in a lazy session.
See [Advanced: assemble a sandbox yourself](./manual-sandbox) for complete Sync/Async programs that assemble these
components and close them in the correct order.
> [card] [Advanced: assemble a sandbox yourself](./manual-sandbox)
# Branch, switch, and roll back
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/branching
With the default lazy session, call `snapshot()` before changing branches.
Snapshots are lightweight, so you can create a checkpoint after every command.
Each snapshot stops the VM; an unchanged filesystem can return the same
`image_uuid`. Rollback follows history entries, not distinct image UUIDs.
For automatic saving after each command, see
[Save after every command](./session-model#save-after-every-command).
Configure your connection as shown in [Your first sandbox](./getting-started).
Branches share one session’s history in its Store. To create an independent
session from any saved image, see
[Start a new session from a snapshot](./session-model#start-a-new-session-from-a-snapshot).
## Create a branch and switch back
Save a baseline on `main`, change a file on `experiment`, then read the original
file from `main`. Creating a branch does not select it: call `switch_branch()`.
> [tab] Sync
>
> ```python theme={null}
> """Compare a change with the saved baseline."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as session:
> # Save the baseline on main.
> session.run(shell="echo baseline > /choice.txt")
> session.snapshot()
>
> # Create a branch at that checkpoint, then select it.
> session.create_branch("experiment", from_branch="main")
> session.switch_branch("experiment")
>
> # Change the file and save the result on experiment only.
> session.run(shell="echo candidate > /choice.txt")
> session.snapshot()
> print("experiment:", session.read_file("/choice.txt").decode().strip())
>
> # Select main's saved image. Its file still contains baseline.
> session.switch_branch("main")
> print("main:", session.read_file("/choice.txt").decode().strip())
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as session:
> # Save the baseline on main.
> await session.run(shell="echo baseline > /choice.txt")
> await session.snapshot()
>
> # Create a branch at that checkpoint, then select it.
> await session.create_branch("experiment", from_branch="main")
> await session.switch_branch("experiment")
>
> # Change the file and save the result on experiment only.
> await session.run(shell="echo candidate > /choice.txt")
> await session.snapshot()
> print("experiment:", (await session.read_file("/choice.txt")).decode().strip())
>
> # Select main's saved image. Its file still contains baseline.
> await session.switch_branch("main")
> print("main:", (await session.read_file("/choice.txt")).decode().strip())
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
experiment: candidate
main: baseline
```
Omit `from_branch` to branch from the current checkpoint. Switching branches
selects saved files; it does not rerun commands or restore processes.
## Roll back and keep a way back to the result
`rollback()` moves the active branch back one saved entry. Keep the current
result under another name before rolling back if you want to return to it later.
> [tab] Sync
>
> ```python theme={null}
> """Roll back one checkpoint and revisit the saved candidate."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as session:
> # Save the first checkpoint on main.
> session.run(shell="echo baseline > /choice.txt")
> session.snapshot()
>
> # Save a second checkpoint with the changed file.
> session.run(shell="echo candidate > /choice.txt")
> session.snapshot()
>
> # Keep a name for the second checkpoint without switching branches.
> session.create_branch("saved-candidate")
>
> # Move main back one checkpoint and read the original file.
> session.rollback()
> print("after rollback:", session.read_file("/choice.txt").decode().strip())
>
> # Return to the second checkpoint through its saved branch name.
> session.switch_branch("saved-candidate")
> print("saved candidate:", session.read_file("/choice.txt").decode().strip())
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as session:
> # Save the first checkpoint on main.
> await session.run(shell="echo baseline > /choice.txt")
> await session.snapshot()
>
> # Save a second checkpoint with the changed file.
> await session.run(shell="echo candidate > /choice.txt")
> await session.snapshot()
>
> # Keep a name for the second checkpoint without switching branches.
> await session.create_branch("saved-candidate")
>
> # Move main back one checkpoint and read the original file.
> await session.rollback()
> print("after rollback:", (await session.read_file("/choice.txt")).decode().strip())
>
> # Return to the second checkpoint through its saved branch name.
> await session.switch_branch("saved-candidate")
> print("saved candidate:", (await session.read_file("/choice.txt")).decode().strip())
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
after rollback: baseline
saved candidate: candidate
```
Use `rollback(steps=2)` to move back two entries. A snapshot can contain several
commands. Rollback keeps later history and other branches; new work starts from
the selected image. It does not undo external side effects or session-wide
`cwd` and `env` overrides.
Branch changes while a VM is active raise `RuntimeError`: snapshot first.
Duplicate branch names, unknown branches, and rollback beyond the initial entry
raise `ValueError`.
## Concurrent callers
Each Session owns its position and branch names. Objects using the same Store
and `session_id` can select different nodes without affecting each other.
Concurrent operations from one parent create separate children. No result moves
another client’s position or overwrites its history.
Within one Session, a result advances the selected position only if that position
still matches its captured source and navigation has not changed. Late results
remain available by their entry IDs. Explicit `branch=` selects a local branch
for a normal commit. The SDK does not merge filesystem changes.
After restarting, select a saved `node_id`; a tree with multiple continuations
requires an explicit choice. `navigate_forward()` also requires a unique child.
See [Save and resume a session](./sessions) for persistence and [Tree stores](./reference/store) for the contract.
# Build a Docker image
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/building-images
Use `sync_build_image` or `async_build_image` when your setup lives in a Dockerfile.
You need a Dockerfile, any local files referenced by `COPY` or `ADD`, and a
configured ConTree connection. No Docker installation, Docker daemon, or Docker API
access is required.
The SDK translates supported Dockerfile instructions into ConTree image layers
and executes build commands on ConTree. The result is a ConTree filesystem image
UUID that you can pass to `create_sandbox_session`.
Use that image as a prepared baseline, then try changes on session branches.
[Work with a Session](./session-model) explains snapshots, rollback, and
resuming saved work without rebuilding the baseline.
Build caching is enabled by default. Later builds reuse layers whose instructions
and inputs have not changed. If you change an instruction, a source file, or the
base image, the SDK rebuilds the affected layers. You do not need to rebuild
unchanged layers each time you start your application.
## Create a small build context
Configure a connection as described in [Connection sources](./getting-started#sandbox-connection). For
`FROM alpine:latest`, the builder first resolves the image in ConTree. If it is
missing, the builder imports it from Docker Hub. This fallback belongs to
Dockerfile builds; `create_sandbox_session` requires an existing ConTree image.
Create `build-context/Dockerfile`:
```dockerfile theme={null}
FROM alpine:latest
COPY message.txt /message.txt
RUN cat /message.txt > /built.txt
```
Create `build-context/message.txt` with this content and a final newline:
```text theme={null}
Hello from a built image!
```
## Build and read the result
Run this code from the directory containing `build-context`. Build history and
file uploads are cached on disk by default.
> [tab] Sync
>
> ```python theme={null}
> """Build an image and read its output in a sandbox."""
>
> from contree_sdk import create_sandbox_session, sync_build_image
>
>
> def main() -> None:
> image = sync_build_image("build-context")
> with create_sandbox_session(image=image) as sandbox:
> content = sandbox.read_file("/built.txt")
> print(content.decode())
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session, async_build_image
>
>
> async def main() -> None:
> image = await async_build_image("build-context")
> async with create_sandbox_session(image=image) as sandbox:
> content = await sandbox.read_file("/built.txt")
> print(content.decode())
>
>
> asyncio.run(main())
> ```
The output is `Hello from a built image!`. Changing `message.txt` changes the input
hash and invalidates the dependent layer. The build result is a ConTree filesystem
image. Dockerfile support is a subset listed below; this does not create a local
Docker image.
## Supported Dockerfile behavior
`FROM`, `RUN`, `COPY`, `ADD`, `WORKDIR`, `ENV`, `ARG`, and `USER` are implemented.
The builder supports multiple stages, `COPY --from`, `.dockerignore`, and build
arguments. It interprets a subset of Dockerfile syntax, not the complete Docker build specification.
`CMD`, `ENTRYPOINT`, `LABEL`, `EXPOSE`, `VOLUME`, `STOPSIGNAL`, `MAINTAINER`,
`HEALTHCHECK`, `ONBUILD`, and `SHELL` are accepted but have no effect.
Unknown instructions raise `ValueError`. A nonzero `RUN` exit raises `DockerBuildError`.
The output is a filesystem image. Startup instructions and Docker configuration
are not reproduced. `ENV`, `WORKDIR`, and `USER` guide build steps; pass the desired
runtime environment and working directory when executing the resulting image.
`WORKDIR` sets a command’s directory; ensure the directory exists in the image.
## Configuration
### Persistent cache
`session_id` selects the build’s cached layer history in the Store. Within that
history, each layer is identified by a hash of its instruction, inputs, and
preceding state. Reusing a session ID lets later builds find matching layers;
changing it starts a separate build history.
The default ID derives from the context path and connection scope. Supply a
stable `session_id=` to keep the same build history after moving the context.
Concurrent builds retain separate continuations in the same tree.
The `store=` argument supplies one Store for build history, uploaded files,
and URL-download metadata. Tree kinds separate these records.
The helpers use `$XDG_CACHE_HOME/contree/images.sqlite3` by default, with
`~/.cache/contree/images.sqlite3` as the fallback. Import and build results share
this database. Set `cache_dir=` to change the directory.
Keep referenced images and uploaded files
available on the server. `no_cache=True` disables layer reuse; it does not force
identical file content to be uploaded again.
For a workflow that imports, builds, and runs with one connection, see
[Share one client](./advanced#shared-image-client) in [Advanced usage](./advanced).
Continue with [Advanced usage](./advanced) to select components, manage them directly,
or observe individual build steps.
# Reuse uploads and retain their sources
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/caching
Use `CachedFileTransfer` or `AsyncCachedFileTransfer` to reuse uploads by content.
Pass an explicit lifetime in seconds. A cache hit does not extend that lifetime.
Choose a lifetime shorter than the server’s upload retention period. The cache
cannot detect uploads removed from the server before expiry; invalidate them
explicitly when necessary.
## Reuse uploads through the factory
The sandbox factory reuses uploads through its Store. These examples select `ContreeSession` or
`ContreeAsyncSession` because startup `files=` attachments need independent
operations. The factory constructs the cached transfer and its connection scope.
For the default lazy sandbox, see [Work with sandbox files](./files) for writing files through stdin.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
> from contree_sdk.store import SyncMemoryStore
>
>
> with SyncMemoryStore() as store:
> with create_sandbox_session(image="tag:alpine:latest", session_type=ContreeSession, store=store) as sandbox:
> sandbox.run("cat", args=["/input.txt"], files={"/input.txt": b"hello"})
> sandbox.run("wc", args=["-c", "/input.txt"], files={"/input.txt": b"hello"})
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
> from contree_sdk.store import AsyncMemoryStore
>
>
> async with AsyncMemoryStore() as store:
> async with create_sandbox_session(
> image="tag:alpine:latest", session_type=ContreeAsyncSession, store=store
> ) as sandbox:
> await sandbox.run("cat", args=["/input.txt"], files={"/input.txt": b"hello"})
> await sandbox.run("wc", args=["-c", "/input.txt"], files={"/input.txt": b"hello"})
> ```
The factory’s default `cache_ttl` is 60 seconds. The caller owns the supplied Store.
Use a SQLite Store to retain history and reusable results across Python restarts.
## Advanced: construct a cached transfer
The transfer creates a temporary copy while hashing a local file in chunks. It
uploads that copy, so later changes to the source cannot change the bytes associated
with the fingerprint. Temporary copies are removed after success, failure, or
cancellation. Concurrent misses can upload the same content more than once.
This example attaches the same local input to two commands. The second command
reuses its uploaded UUID. Each request still supplies its own destination and
permissions. Configure a connection as described in [Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.store import SyncSQLiteStore
> from contree_sdk.scope import StoreScope
> from contree_sdk.files import ClientFileTransfer
> from contree_sdk.upload_cache import CachedFileTransfer
>
>
> Path("input.txt").write_text("hello")
> with (
> ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> SyncSQLiteStore("uploads.db") as store,
> ):
> scope = StoreScope.from_client(client, profile="work")
> transfer = CachedFileTransfer(ClientFileTransfer(client), store, scope=scope, ttl=3600)
> session = ContreeSession(client, image="tag:alpine:latest", store=store, file_transfer=transfer)
> session.run("cat", args=["/input"], files={"/input": Path("input.txt")})
> session.run("wc", args=["-c", "/input"], files={"/input": Path("input.txt")})
>
> uploads = transfer.store.list_sessions(kind="upload-cache").items
> assert len(uploads) == 1
> assert uploads[0].expires_at is not None
> sources = transfer.sources.sources()
> assert sources[0].source == str(Path("input.txt").resolve())
>
> assert transfer.store.delete_session(uploads[0].session_id)
> assert transfer.sources.sources() == sources
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.store import AsyncSQLiteStore
> from contree_sdk.scope import StoreScope
> from contree_sdk.files import AsyncClientFileTransfer
> from contree_sdk.upload_cache import AsyncCachedFileTransfer
>
>
> await asyncio.to_thread(Path("input.txt").write_text, "hello")
> async with (
> ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> AsyncSQLiteStore("uploads.db") as store,
> ):
> scope = StoreScope.from_client(client, profile="work")
> transfer = AsyncCachedFileTransfer(AsyncClientFileTransfer(client), store, scope=scope, ttl=3600)
> session = ContreeAsyncSession(client, image="tag:alpine:latest", store=store, file_transfer=transfer)
> await session.run("cat", args=["/input"], files={"/input": Path("input.txt")})
> await session.run("wc", args=["-c", "/input"], files={"/input": Path("input.txt")})
>
> uploads = (await transfer.store.list_sessions(kind="upload-cache")).items
> assert len(uploads) == 1
> sources = await transfer.sources.sources()
> assert sources[0].source == str(Path("input.txt").resolve())
> assert await transfer.store.delete_session(uploads[0].session_id)
> assert await transfer.sources.sources() == sources
> ```
`StoreScope.from_client()` separates the endpoint, project, credential, and optional
profile name. It stores a digest, not the credential. Credential rotation creates
a new scope. Construct the transfer again when switching connection settings.
The caller owns the client, underlying transfer, and Store.
`SyncFileSources` and `AsyncFileSources` also provide `record()`, `sources()`, and
`forget()`. Records can identify local paths or URLs (`kind="url"`). Multiple
sources can refer to the same UUID. They use separate typed trees. Source records
describe provenance; they do not prove that a remote upload still exists or that
the local file still contains those bytes.
## Enumerate retained trees
Upload reuse uses trees with `kind="upload-cache"`. Call
`store.list_sessions(kind="upload-cache", limit=100)` and follow `next_cursor`
to enumerate them. `delete_session(tree.session_id)` invalidates one tree.
Source records use separate `file-sources` trees, so deleting reusable upload
results preserves provenance. Retention for source trees follows the Store’s
policy for `ttl=None`; it is not a universal promise of permanent storage.
The same Store can hold user sessions, builds, and upload results. Select
`kind="session"` when listing user sessions. See [Tree stores](./reference/store) for
sync/async examples, pagination, immutable nodes, and TTL semantics.
# Implement a custom Store
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/custom-store
Use your own Store when session history must live in your database or service.
Inherit `SyncStore` or `AsyncStore` from `contree_sdk.store`, implement its methods,
and pass an instance through `store=`. The session uses the same interface to save
history and resume work, regardless of the storage backend.
Start with [Save and resume a session](./sessions) for memory and SQLite examples. This page covers
extension points and the guarantees a custom implementation must preserve.
## Extend an existing implementation
If you only need different defaults, subclass a supplied Store. This example
gives newly created trees a seven-day lifetime unless the caller supplies a TTL.
SQLite still handles persistence, atomic writes, and pagination.
The program saves a file, closes the Store, and opens the same session through a
new Store instance. It prints `saved`. Configure a connection as described in
[Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SessionInfo, SyncSQLiteStore
>
>
> class RetainedSQLiteStore(SyncSQLiteStore):
> def create_session(self, session_id: str, *, kind: str = "session", ttl: float | None = None) -> SessionInfo:
> lifetime = 7 * 24 * 60 * 60 if ttl is None else ttl
> return super().create_session(session_id, kind=kind, ttl=lifetime)
>
>
> with RetainedSQLiteStore("history.db") as store:
> with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="my-project") as session:
> session.run(shell="echo saved > /saved.txt")
>
> with RetainedSQLiteStore("history.db") as store:
> with create_sandbox_session(store=store, session_id="my-project") as session:
> content = session.read_file("/saved.txt")
> print(content.decode())
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncSQLiteStore, SessionInfo
>
>
> class RetainedSQLiteStore(AsyncSQLiteStore):
> async def create_session(self, session_id: str, *, kind: str = "session", ttl: float | None = None) -> SessionInfo:
> lifetime = 7 * 24 * 60 * 60 if ttl is None else ttl
> return await super().create_session(session_id, kind=kind, ttl=lifetime)
>
>
> async with RetainedSQLiteStore("history.db") as store:
> async with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="my-project") as session:
> await session.run(shell="echo saved > /saved.txt")
>
> async with RetainedSQLiteStore("history.db") as store:
> async with create_sandbox_session(store=store, session_id="my-project") as session:
> content = await session.read_file("/saved.txt")
> print(content.decode())
> ```
Run the async example inside an async function or a notebook that supports
top-level `await`. The supplied Store stays open after the session context exits.
The outer Store context closes it.
Reopening a tree does not renew its expiry. Use `set_session_ttl()` to change an
existing tree’s lifetime. Expiry makes its history unavailable; it does not delete
server images or stop running operations. The example changes the default for
tree creation only. Other methods retain the supplied SQLite behavior.
## Implement storage in another database
For a different backend, inherit `SyncStore` or `AsyncStore` directly. Implement
every abstract method below with your database client. PostgreSQL and Redis are
possible application backends; the SDK does not include implementations for them.
| Methods | Responsibility |
| - | - |
| `create_session()`, `get_session()` | Create or read a tree’s identity, kind, and expiry. |
| `set_session_ttl()`, `delete_session()` | Change retention or remove the whole tree. |
| `list_sessions()` | Filter and page through stored trees. |
| `append()` | Atomically add an immutable node with its explicit parent. |
| `get_node()`, `get_nodes()` | Read one node or an atomic batch of known identities. |
| `list_nodes()`, `list_children()` | Filter and page through nodes or direct children. |
| `list_history()` | Follow parents from a selected node toward the root. |
| `close()` | Release connections and resources owned by the Store. |
The async interface has the same methods and results, with `async def` and
`await`. Use an async database client or explicitly offload blocking I/O. The base
classes supply the matching context-manager methods through `close()`.
Store preserves `Node.id`, `parent_id`, `kind`, and JSON-object `data`. A tree also
has a `kind`: sessions, builds, and upload reuse can share a backend. Your Store
must preserve their data without interpreting session commands or Docker hashes.
Use [Tree stores](./reference/store) for exact signatures, limits, and error behavior.
## Preserve the storage guarantees
* Make each call atomic across all clients, including separate processes and
database connections. A lock in one Python object is insufficient.
* Require a live tree and an existing parent in that tree for `append()`. Allow
only one root. A late append must not recreate a deleted or expired tree.
* Accept an identical repeated node without duplication. Raise
`NodeConflictError` if the same identity has different contents or a second root
is inserted. Do not overwrite saved nodes.
* Return independent JSON values. Changes to a caller’s dictionary must not
change stored data. Preserve atomic batch reads in `get_nodes()`.
* Apply filters before pagination. Order identity-based lists by ID and history
by ancestry. Return opaque continuation cursors; pages need not share a snapshot.
* Apply TTL to the whole tree. Reads and appends must not extend its lifetime.
Define the backend policy for `ttl=None` and preserve the contract’s expiry errors.
Test retries, conflicting inserts, pagination, expiry, and deletion through
separate connections before using a new backend. Also test saving a session and
resuming it through a new Store instance. The [Store contract](./reference/store#contract)
defines the complete requirements.
Store saves history and references to remote images. Session controls execution,
the selected node, and local branch names. A custom Store does not need to run
commands or choose a shared current position. Pass it through `store=` to sessions
or helpers, and close it after all users finish.
# Customize the SDK
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/customization
Subclass a session to change command defaults, image resolution, or operation
handling. To replace storage or file transfer, implement the matching sync or
async interface and pass it to the sandbox factory. See [Advanced: assemble a sandbox yourself](./manual-sandbox)
if you also need to manage component construction and cleanup.
## Customize command policy and operations
`RunRequest` is a frozen configuration value. Its argument tuple and environment
mapping are copied at construction. Files and stdin remain caller-owned resources.
Use `dataclasses.replace()` to apply policy without mutating the caller’s request.
This example rejects shell commands, applies a default timeout, and counts waits.
Configure a connection as described in [Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> from dataclasses import replace
>
> from contree_client.models import InstanceResult, InstanceSpawnResponse
>
> from contree_sdk import ContreeSession, OperationContext, RunRequest, create_sandbox_session
> from contree_sdk.session import Operation, OperationContract
>
>
> class AuditedOperation(Operation):
> waits = 0
>
> def wait(self, *, timeout: float | None = None) -> InstanceResult:
> self.waits += 1
> return super().wait(timeout=timeout)
>
>
> class PolicySession(ContreeSession):
> def prepare_request(self, request: RunRequest) -> RunRequest:
> request = super().prepare_request(request)
> if request.shell is not None:
> raise ValueError("this session only accepts commands with explicit arguments")
> return replace(request, timeout=request.timeout or 30, env={**(request.env or {}), "APP_MODE": "test"})
>
> def create_operation(self, response: InstanceSpawnResponse, context: OperationContext) -> OperationContract:
> if not isinstance(response.uuid, str):
> raise TypeError("missing operation UUID")
> return AuditedOperation(self.client, response.uuid, timeout=context.request.timeout_seconds, context=context)
>
>
> with create_sandbox_session(session_type=PolicySession, image="tag:alpine:latest") as session:
> with session.spawn("echo", args=["hello"]) as operation:
> result = operation.wait()
> session.commit_result(operation)
> assert isinstance(operation, AuditedOperation)
> print(operation.waits)
> ```
> [tab] Async
>
> ```python theme={null}
> from dataclasses import replace
>
> from contree_client.models import InstanceResult, InstanceSpawnResponse
>
> from contree_sdk import ContreeAsyncSession, OperationContext, RunRequest, create_sandbox_session
> from contree_sdk.session import AsyncOperation, AsyncOperationContract
>
>
> class AuditedAsyncOperation(AsyncOperation):
> waits = 0
>
> async def wait(self, *, timeout: float | None = None) -> InstanceResult:
> self.waits += 1
> return await super().wait(timeout=timeout)
>
>
> class PolicySession(ContreeAsyncSession):
> def prepare_request(self, request: RunRequest) -> RunRequest:
> request = super().prepare_request(request)
> if request.shell is not None:
> raise ValueError("this session only accepts commands with explicit arguments")
> return replace(request, timeout=request.timeout or 30, env={**(request.env or {}), "APP_MODE": "test"})
>
> def create_operation(self, response: InstanceSpawnResponse, context: OperationContext) -> AsyncOperationContract:
> if not isinstance(response.uuid, str):
> raise TypeError("missing operation UUID")
> return AuditedAsyncOperation(
> self.client, response.uuid, timeout=context.request.timeout_seconds, context=context
> )
>
>
> async with create_sandbox_session(session_type=PolicySession, image="tag:alpine:latest") as session:
> async with await session.spawn("echo", args=["hello"]) as operation:
> result = await operation.wait()
> await session.commit_result(operation)
> assert isinstance(operation, AuditedAsyncOperation)
> print(operation.waits)
> ```
The session calls `prepare_request()` before uploading files or submitting work.
It passes the prepared inputs to `submit_request()`, then constructs the handle
through `create_operation()`. The `OperationContext` holds the effective request
and the source image, history entry, and branch used for the eventual commit.
If operation construction fails after submission, the session attempts remote
cancellation and preserves the factory error.
`create_store()` and `create_file_transfer()` supply defaults only when no component
was passed explicitly. Constructor-time factories must not depend on attributes
that a subclass initializes after `super().__init__()`.
## Choose what to override
| Requirement | Extension boundary |
| - | - |
| Add command defaults or reject commands | Override `prepare_request(RunRequest)` |
| Resolve images from another naming scheme | Override `resolve_image(image)` |
| Modify transport submission | Override `submit_request(...)` |
| Instrument or replace operation lifecycle | Override `create_operation(response, context)` |
| Replace subprocess handles | Override `Operation.create_subprocess(spid, queue)` |
| Replace the event source | Override `Operation.open_event_stream()` |
| Observe operation events | Register `add_observer()` before starting the reader |
| Upload from another storage service | Implement `SyncFileTransfer` or `AsyncFileTransfer` |
| Store history remotely | Implement `SyncStore` or `AsyncStore` |
| Replace build caching | Implement `SyncStore` or `AsyncStore` |
| Add or replace Dockerfile instructions | Register a `DockerKeyword` with `DockerfileParser` |
| Use a session subclass inside builds | Pass `session_factory=` |
| Add per-build state | Set `context_class` or override `create_context(BuildRequest)` |
| Audit or restrict build instructions | Override `execute_directive(directive, context)` |
| Use another execution engine in deepagents | Implement `SyncExecutor` or `AsyncExecutor` |
Use native async I/O in async overrides; offload blocking work explicitly.
## Implement file transfer
Inherit `SyncFileTransfer` or `AsyncFileTransfer` and implement:
* `upload(UploadFileSpec) -> FileSpec`: return a file identifier valid on the session’s server.
* `read_file(image_uuid, path) -> bytes`: return exact bytes from the specified image.
The default `prepare_files()` expands directories, rejects destination conflicts,
and calls `upload()` with a bounded worker count. Set `max_concurrency` on a custom
transfer to select that limit. Override `iter_file()` to yield chunks and release
its reader when the generator closes. Its default implementation buffers through
`read_file()`. The inherited `download_file()` writes those chunks atomically.
See [Work with sandbox files](./files) for tree preparation, callbacks, cancellation, and ownership.
The async implementation cancels and joins sibling uploads if one fails. Override
this method for batching or bounded concurrency. Override `read_stdin()` to support
additional input handling. Never close a caller-owned input stream.
Inject a component with `file_transfer=`. `ClientFileTransfer` and
`AsyncClientFileTransfer` provide the standard implementations and can also be
subclassed. Import `UploadFileSpec`, `UploadedFile`, `InputSource`, and the readable
protocols from `contree_sdk.files`.
## Implement history storage
Inherit `SyncStore` or `AsyncStore` to keep history in your own database or service.
Pass the implementation through `store=`. See [Implement a custom Store](./custom-store) for executable
extension examples, required methods, and storage guarantees. For standard memory
and SQLite usage, start with [Save and resume a session](./sessions).
## Store reusable results
The same Store holds history and reusable results. Implement its contract with
Redis or PostgreSQL and supply it through `store=` in helpers and
direct constructors. Tree `kind` distinguishes purposes; the backend does not
interpret user JSON.
Stores expose `close()` and a matching context manager. Sessions and builders
leave caller-supplied stores open. See [Reuse uploads and retain their sources](./caching) for upload reuse and
[Advanced: resume a background operation](./detached-operations) for operation recovery.
## Replace an integration backend
The framework adapters depend only on `SyncExecutor` or `AsyncExecutor`:
* `session_id` identifies the execution context.
* `execute(RunRequest)` returns `contree_client.models.InstanceResult`.
* `write_file(path, content)` writes bytes and returns `None` after application.
* `read_file(path)` returns bytes; use client `NotFoundError` or
`UnprocessableEntityError` for missing or invalid paths.
A nonzero process exit code belongs in the result. Operation-level failure is an
exception. Preserve cancellation and timeout errors. An executor used by the
sandbox must retain filesystem changes when `disposable=False`; the adapter uses
this for commands and uploads. It serializes its own mutating calls, but callers
sharing the same executor must coordinate any additional concurrent mutations.
The adapters never access a concrete session’s client, store, or history internals.
They do not close the executor. The async adapter requires native async methods;
its sync entry points raise `NotImplementedError`.
`write_file()` has a default implementation using shell execution and binary
`RunRequest.stdin`. Existing executors inherit it. Override this method to replace
the transfer mechanism; adapters do not construct upload commands themselves.
A failed write raises `FileWriteError(path, message)`. Transport errors, timeouts,
and cancellation must propagate unchanged.
A write must apply the content before returning. Uploading a blob or staging files
for a later command is not sufficient. A native transfer implementation must also
coordinate with VM startup, active commands, and snapshots. Keep the VM selected
for the transfer until the backend confirms application.
Blob upload and application to a VM are separate operations. A future backend
implementation can reuse uploaded blobs here without changing framework calls.
Archive extraction needs explicit extraction semantics; `write_file` always means
writing the supplied bytes, even when those bytes contain an archive.
See [File transfers and executor contracts](../integrations/langchain#advanced-file-transfers-and-executor-contracts).
## Extend Dockerfile builds
The same directive class supports both builders through `execute()` and
`execute_async()`. Create a parser per dialect, then register your directive:
```python theme={null}
"""Register a Dockerfile directive without changing the SDK's global registry."""
from dataclasses import dataclass
from typing import ClassVar
from contree_sdk.docker import AsyncBuildContext, BuildContext, DockerfileParser, DockerKeyword
@dataclass(frozen=True, repr=False)
class BuildMode(DockerKeyword):
NAME: ClassVar[str] = "BUILDMODE"
value: str = ""
@classmethod
def parse(cls, args_text: str) -> "BuildMode":
if args_text not in {"test", "release"}:
raise ValueError("BUILDMODE requires test or release")
return cls(value=args_text)
def serialize(self) -> str:
return f"BUILDMODE {self.value}"
def execute(self, ctx: BuildContext) -> None:
ctx.env["BUILD_MODE"] = self.value
async def execute_async(self, ctx: AsyncBuildContext) -> None:
ctx.env["BUILD_MODE"] = self.value
def make_parser() -> DockerfileParser:
parser = DockerfileParser()
parser.register(BuildMode)
return parser
parser = make_parser()
print(parser.parse("BUILDMODE test"))
```
Pass the parser with `parser=make_parser()` to either builder. Registration copies
no state into the module registry and cannot change another builder’s dialect.
`execute()` and `execute_async()` define the instruction’s sync and async behavior.
Implement both if the dialect supports both builders.
The `session_factory` receives `client` as its first positional argument, then
`session_id`, `store`, `image`, `node_id`, and `tree_kind` as keyword arguments. It returns a `ContreeSession` or `ContreeAsyncSession` implementation.
Both fresh layers and cache hits use this factory. Set `context_class` to a
`BuildContext` or `AsyncBuildContext` subclass when only additional methods or state
are needed. Override `create_context(BuildRequest)` for a different construction
policy. `execute_directive()` intercepts normal steps, stage sealing, and final file materialization.
Custom directives that execute nested directives must call `context.execute_directive()`.
A custom `create_context()` must pass `directive_executor=self.run_step`
to preserve event reporting and policy dispatch for nested steps.
`run_step()` wraps `execute_directive()` with step notifications.
Override `BuildContext.run_operation(request, branch=...)` or its async equivalent
to customize RUN orchestration. The default uses session `spawn_request()`,
operation `events()`/`wait()`, and session `commit_result()`. It applies
`prepare_request()` and the session operation factory through these public hooks.
A custom directive must include every input that affects a layer in the context’s
cache state or its hash contribution. Changing the implementation of an instruction
can invalidate previous cached layers; use a new session/cache namespace or disable
cache reuse. A parser extension alone does not automatically version existing caches.
## Operation contract obligations
`OperationContract` and `AsyncOperationContract` expose status, events, waiting,
stdin, signals, cancellation, context management, and subprocess creation. A
session-created operation has an `OperationContext`. A reattached UUID-only handle
may have no context and cannot be committed to session history.
`wait()` must store the final `OperationResponse` before returning its
`InstanceResult`. Cancellation and cleanup must preserve the primary exception.
Use `SubprocessContract` or `AsyncSubprocessContract` when replacing subprocess
handles. Iteration followed by `wait()` must not wait for a second exit event.
A stream failure must reach its consumer instead of appearing as successful EOF.
The built-in operations own one unfiltered reader per handle. Override
`open_event_stream()` to replace its source. Calling `events()` creates a local
subscription; overriding it does not replace the source used by `wait()` or
subprocesses. Register observers before entering the context or first consuming
`events()` or `wait()`. Sync observers return directly; async observers are awaited.
They receive `(event, None)` for events and `(None, error)` at EOF. Keep them short;
do not wait for the operation from its own observer. Observer errors fail the reader.
`LazySession` requires `add_observer()` support from a custom operation contract.
It delegates request policy and operation creation to the wrapped session. Override
`keepalive_request()` on the lazy wrapper to use another main process. See
[Sessions and operations](./reference/session) for the public snapshot-policy interface.
## Resolve application-specific image names
A sync override runs during session construction. An async override runs during
`ensure_ready()` or the first operation. Return a valid UUID for the selected server;
the example uses a mapping that your application supplies.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> class NamedImageSession(ContreeSession):
> def resolve_image(self, image: str) -> str:
> return {"test-base": "8a0269a2-7720-4daa-aa96-dca93b20bb33"}[image]
>
>
> with create_sandbox_session(session_type=NamedImageSession, image="test-base") as session:
> print(session.image_uuid)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> class NamedAsyncImageSession(ContreeAsyncSession):
> async def resolve_image(self, image: str) -> str:
> return {"test-base": "8a0269a2-7720-4daa-aa96-dca93b20bb33"}[image]
>
>
> async with create_sandbox_session(session_type=NamedAsyncImageSession, image="test-base") as session:
> print(session.image_uuid)
> ```
## Select a commit policy
`ApiSuccessCommitPolicy` is the default for both session implementations. It
retains successful API results from non-disposable commands, including nonzero
and unknown process exit codes. API failure and cancellation raise errors and
never change history.
Pass `commit_policy=ZeroExitCommitPolicy()` to retain only results with an explicit
zero exit code. A rejected result is still returned to the caller. Rejection does
not change the session image, branches, or pending files. `commit_result()` uses
the same policy after an explicit `spawn()` and `wait()`; it returns `None` when
it skips the commit. Disposable requests cannot create history entries through
`commit_result()`, even if the server returns an image.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
> from contree_sdk.session import ZeroExitCommitPolicy
>
>
> with create_sandbox_session(
> session_type=ContreeSession, image="tag:alpine:latest", commit_policy=ZeroExitCommitPolicy()
> ) as session:
> original_image = session.image_uuid
> result = session.run(shell="exit 7")
> assert result.state.exit_code == 7
> assert session.image_uuid == original_image
> operation = session.spawn(shell="exit 7")
> result = operation.wait()
> entry = session.commit_result(operation)
> assert result.state.exit_code == 7
> assert entry is None
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
> from contree_sdk.session import ZeroExitCommitPolicy
>
>
> async with create_sandbox_session(
> session_type=ContreeAsyncSession, image="tag:alpine:latest", commit_policy=ZeroExitCommitPolicy()
> ) as session:
> original_image = session.image_uuid
> result = await session.run(shell="exit 7")
> assert result.state.exit_code == 7
> assert session.image_uuid == original_image
> operation = await session.spawn(shell="exit 7")
> result = await operation.wait()
> entry = await session.commit_result(operation)
> assert result.state.exit_code == 7
> assert entry is None
> ```
For an application-specific rule, inherit `AbstractCommitPolicy` and implement
`should_commit(context: OperationContext, result: InstanceResult) -> bool`. The
session passes the effective request and its original history position. The
method must not perform blocking I/O. The session validates API success before
calling it and requires a result image before committing an accepted result.
Policies are session components; pass the same policy when resuming a session.
Session commands save by default; `disposable=True` opts out. Snapshots are
lightweight and can run after every command, but stop the VM. An unchanged
filesystem can return the same image UUID; policies must not require a new UUID.
A `LazySession` snapshot also uses the underlying session’s commit policy. If the
policy rejects that snapshot, the lazy session fails and leaves history unchanged.
It cannot restart from the previous image while claiming that changes were saved.
The policy sees the keepalive process result, not individual subprocess results.
Use the default policy to preserve snapshots after terminating the keepalive.
# Advanced: resume a background operation
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/detached-operations
For ordinary commands, start with [Your first sandbox](./getting-started) and its sandbox factory.
This guide exposes lower-level controls. See [Advanced: assemble a sandbox yourself](./manual-sandbox) for manual
component assembly and resource ownership.
Use `spawn_detached()` when a command must continue after the current Python
process exits. The session records its UUID, source image, parent entry, branch,
command options, and uploaded attachment metadata. It does not start an event
reader. The server still applies the operation’s configured timeout.
Use a SQLite store for persistence across processes. Memory stores implement the
same API but retain records only while that store instance exists. Keep the same
session ID, database, and endpoint when resuming.
## Submit work
The first block submits work and closes the local store and client. It leaves the
remote operation running. Store the operation UUID in your application or retrieve
it through `session.list_operations()` after restarting Python.
The async variant uses native transport and storage. No event loop or background
reader must remain running between submission and collection. Run async blocks
inside an async function or a compatible notebook.
> [tab] Sync
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.store import SyncSQLiteStore
>
>
> with (
> ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> SyncSQLiteStore("session.db") as store,
> ):
> session = ContreeSession(client, image="tag:alpine:latest", session_id="background", store=store)
> record = session.spawn_detached(shell="printf saved > /result.txt; cat /result.txt")
> operation_uuid = record.uuid
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async with (
> ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> AsyncSQLiteStore("async.db") as store,
> ):
> session = ContreeAsyncSession(client, image="tag:alpine:latest", session_id="background", store=store)
> record = await session.spawn_detached(shell="printf saved > /result.txt; cat /result.txt")
> operation_uuid = record.uuid
> ```
## Collect the result
Run the next block in the process that collects the result. `wait_operation()`
uses the session’s commit policy and records completion atomically with history.
It returns the process result, including a nonzero exit code. The consumer needs
the same working directory and connection profile. It obtains the UUID from
the store, so no Python variables from the submitting process are needed. This
example has exactly one pending operation; applications with several operations
must select the intended record or accept a UUID as an argument.
> [tab] Sync
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.store import SyncSQLiteStore
>
>
> with (
> ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> SyncSQLiteStore("session.db") as store,
> ):
> session = ContreeSession(client, session_id="background", store=store)
> pending = session.list_operations()
> (record,) = pending
> operation_uuid = record.uuid
> result = session.wait_operation(operation_uuid)
> repeated_result = session.wait_operation(operation_uuid)
> assert result == repeated_result
> assert session.list_operations() == ()
> assert len(session.history()[0]) == 2
> assert session.list_operations(pending_only=False)[0].history_id is not None
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async with (
> ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client,
> AsyncSQLiteStore("async.db") as store,
> ):
> session = ContreeAsyncSession(client, session_id="background", store=store)
> pending = await session.list_operations()
> (record,) = pending
> operation_uuid = record.uuid
> result = await session.wait_operation(operation_uuid)
> repeated_result = await session.wait_operation(operation_uuid)
> assert result == repeated_result
> assert await session.list_operations() == ()
> assert len((await session.history())[0]) == 2
> assert (await session.list_operations(pending_only=False))[0].history_id is not None
> ```
## Branches and commit policy
Completion keeps the parent captured at spawn time. Switching branches or
continuing other work does not redirect or reject the result. The completed
entry is another child of its original parent. Obtain its ID from
`session.get_operation(uuid).history_id` and use `navigate()` to select it.
Waiting can advance the local position when it still matches the source;
replaying an already completed result does not undo a later rollback.
The default `ApiSuccessCommitPolicy` retains every successful non-disposable
result, including nonzero exit codes. Pass `commit_policy=ZeroExitCommitPolicy()`
when resuming to retain only exit code zero. See [Customize the SDK](./customization) for custom
policies. Concurrent completion calls share the first stored decision. A later
policy change or rollback cannot cause a second commit.
Disposable and policy-rejected results remain readable without a history entry.
Final API failures and cancellation remain readable as the same exceptions.
Completed `wait_operation()` calls use the stored response without remote I/O.
Transport errors remain pending. A timeout or cancellation of a live wait follows
`Operation.wait()` semantics and requests remote cancellation; it does not merely
stop observing the operation.
`wait_operation()` closes its internal handle before returning or raising. Async
cleanup completes even after repeated caller cancellation. Synchronous cleanup
uses a bounded reader join; a blocked transport can keep its reader thread alive
until the stream releases it. See [Advanced: control a running sandbox](./operation) for lifecycle details.
## Control and inspect registered work
`detach(operation)` registers an existing session operation without closing its
handle. `restore_operation(uuid)` reconstructs a handle through `create_operation()`
with the original context. Override `create_operation_record()` and
`restore_operation_context()` together to persist application-specific request
fields. Both restoration and commit policies use these hooks. Use that handle to send signals, cancel the operation,
or read events. After `wait()`, `commit_result()` on a restored handle uses the
same atomic completion path. Use `wait_operation()` to replay a stored response.
`list_operations()` returns pending records. Set `pending_only=False` to include
completed records. `OperationRecord.history_id` identifies a retained result;
`response` stores the final API response as a JSON object. Records include the effective
command environment and output, but not client credentials. A different client
endpoint is rejected before the UUID is used.
Local file and stdin sources are not serialized or reopened. Attachments retain
their uploaded UUIDs and destination permissions. Restored `OperationContext`
values have `request.files=None` and `request.stdin=None`; inspect `attachments`
and `files` for the submitted inputs. Commit policies must use this persisted
context, rather than source objects. Detached titles and file metadata are fixed
at registration; `commit_result()` cannot override them.
## Failure boundaries and custom stores
Remote submission and local registration are separate operations. If registration
raises normally, `spawn_detached()` requests cancellation and preserves the
registration error. A process crash between remote submission and registration
can leave an unregistered remote operation. Registration does not promise exactly
one remote submission. Retrying submission can start another operation.
A pending node stores the original context and the identity reserved for its
result. Completion appends one immutable node containing the final response and
optional retained image. An identical write can be retried. If concurrent
collectors disagree on commit policy, the first saved completion is retained.
Deleting the tree removes both records; it does not cancel the remote operation.
Custom stores need only the tree contract, including atomic and idempotent
`append()`. They do not implement a second operation registry API. See
[Tree stores](./reference/store) for the guarantees required across processes.
# Work with sandbox files
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/files
Use `write_file(path, content)` to write bytes into the sandbox. It creates parent
directories and returns after the write completes. `read_file()` reads the active
VM without taking a snapshot. The next command reuses that VM, including its
running processes. A cold session reads its saved image; pending staged files
start a VM so reads include those inputs.
Use `session.list_dir(path)` for directory entries and `session.grep(pattern, ...)`
to search file contents. These methods use the same current filesystem as
`read_file()`. Both synchronous and asynchronous sessions provide all four methods.
This example writes `/input.txt`, runs a command to copy it to `/output.txt`,
and reads the result back as bytes.
Configure a connection as described in [Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> """Write and read files in one sandbox session."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as session:
> session.write_file("/input.txt", b"Hello from a file!\n")
> session.run(shell="cat /input.txt > /output.txt")
> content = session.read_file("/output.txt")
> print(content.decode())
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as session:
> await session.write_file("/input.txt", b"Hello from a file!\n")
> await session.run(shell="cat /input.txt > /output.txt")
> content = await session.read_file("/output.txt")
> print(content.decode())
>
>
> asyncio.run(main())
> ```
Both programs print `Hello from a file!`.
`read_file()` sees both writes without stopping the VM. Normal context exit saves them.
With `ContreeSession`, each command saves by default; `disposable=True` leaves
the previous image selected.
> [!NOTE]
>
> Async snippets with top-level `await` run inside an async function or a notebook
> that supports it. For a standalone script, use the `asyncio.run(main())` structure
> from [Your first sandbox](./getting-started).
Use `run(files={"/input.txt": Path("local.txt")}, command="cat", args=["/input.txt"])`
to make a local file available before the command starts. A `LazySession` applies
the file to its running VM, including on the first call; a `ContreeSession`
attaches it at operation startup. Directory sources expand into individual files
on both paths, so empty directories are omitted. Live placement uses mode `0644`
and the VM runtime user; explicit non-default `UploadFileSpec` ownership or mode
is rejected for `LazySession`.
## List directories and search files
Use `list_dir()` and `grep()` directly on the session. Both return structured
results that you can print directly. Directory listings default to a
detailed format like `ls -l`.
Paths start at the filesystem root, independently of the command working directory.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
>
>
> with create_sandbox_session(image="tag:alpine:latest") as sandbox_session:
> sandbox_session.write_file("/work/message.txt", b"Hello from ConTree!\n")
>
> directory = sandbox_session.list_dir("/work")
> print(directory)
>
> matches = sandbox_session.grep("Hello", path="/work/message.txt", max_total=20)
> print(matches)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
>
>
> async with create_sandbox_session(image="tag:alpine:latest") as sandbox_session:
> await sandbox_session.write_file("/work/message.txt", b"Hello from ConTree!\n")
>
> directory = await sandbox_session.list_dir("/work")
> print(directory)
>
> matches = await sandbox_session.grep("Hello", path="/work/message.txt", max_total=20)
> print(matches)
> ```
`matches.matches` contains the structured matches. Check `matches.truncated`
when a search must be complete. Use `glob`, `case`, `before`, and `after` to
select files and include context lines.
## Advanced: choose a file source
| Input | Meaning |
| - | - |
| `files={"/input.txt": b"content"}` | Upload bytes directly. |
| `files={"/input.txt": "local.txt"}` | Read a local file; the string is a path, not file content. |
| `files={"/input.txt": Path("local.txt")}` | Read a local file using a path object. |
| `files=["local.txt"]` | Upload the file to `/local.txt`. |
| `files={"/tool.sh": UploadFileSpec(...)}` | Set ownership and mode for startup attachments. |
Destination paths refer to the remote filesystem. Source paths refer to your local
machine. A duplicate destination in a list raises `ValueError` before execution.
The standard transfer component uses the client’s `ensure_file()` to reuse uploads
by content. A saved upload does not by itself change a session image.
See [Customize the SDK](./customization) to replace file transfer.
## Advanced: upload an executable script
Use `UploadFileSpec` to set a mode. This example runs the uploaded script directly.
Its output is `script output`. It is disposable because the script is not needed
by a later command.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
> from contree_sdk.files import UploadFileSpec
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> script = UploadFileSpec(source=b"#!/bin/sh\necho 'script output'\n", mode=0o755)
> result = session.run("/tool.sh", files={"/tool.sh": script}, disposable=True)
> print(result.stdout)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
> from contree_sdk.files import UploadFileSpec
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> script = UploadFileSpec(source=b"#!/bin/sh\necho 'script output'\n", mode=0o755)
> result = await session.run("/tool.sh", files={"/tool.sh": script}, disposable=True)
> print(result.stdout)
> ```
## Advanced: stage files for a later command
`stage_files()` uploads content and appends a `stage` history entry. It does not
start a VM or change the image. `pending_files()` returns the uploaded UUID,
destination path, and permissions for each pending attachment.
Use a SQLite store to keep staging between processes. The next `run()` or `spawn()`
attaches pending files from its source history entry. Local sources are no longer
needed after staging succeeds.
This example stages a configuration file, closes the store, and resumes the session.
A committed run consumes the attachment. Rolling back that run restores the pending
attachment with its original permissions.
> [tab] Sync
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.files import UploadFileSpec
> from contree_sdk.store import SyncSQLiteStore
>
>
> with ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> with SyncSQLiteStore("staging.db") as store:
> session = ContreeSession(client, image="tag:alpine:latest", session_id="edit-demo", store=store)
> config_file = UploadFileSpec(source=b"mode=test\n", uid=1000, gid=1000, mode=0o640)
> staged = session.stage_files({"/work/config.ini": config_file})
> pending = session.pending_files()
> assert pending[0].mode == 0o640
>
> with SyncSQLiteStore("staging.db") as store:
> session = ContreeSession(client, session_id="edit-demo", store=store)
> assert session.pending_files() == pending
> session.run(shell="cat /work/config.ini")
> assert session.pending_files() == ()
> session.rollback()
> assert session.tip_id == staged.id
> assert session.pending_files() == pending
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.files import UploadFileSpec
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async with ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> async with AsyncSQLiteStore("staging-async.db") as store:
> session = ContreeAsyncSession(client, image="tag:alpine:latest", session_id="edit-demo", store=store)
> config_file = UploadFileSpec(source=b"mode=test\n", uid=1000, gid=1000, mode=0o640)
> staged = await session.stage_files({"/work/config.ini": config_file})
> pending = await session.pending_files()
> assert pending[0].mode == 0o640
>
> async with AsyncSQLiteStore("staging-async.db") as store:
> session = ContreeAsyncSession(client, session_id="edit-demo", store=store)
> assert await session.pending_files() == pending
> await session.run(shell="cat /work/config.ini")
> assert await session.pending_files() == ()
> await session.rollback()
> assert session.tip_id == staged.id
> assert await session.pending_files() == pending
> ```
Staging follows history ancestry. A new branch inherits the pending files at its
starting entry. Staging another version of the same path changes only that branch.
Rolling back a staging entry restores the previous version, if one exists.
Explicit `run(files=...)` attachments take precedence over pending files with the
same destination. A committed result records all attached paths as applied, including
those explicit replacements. A disposable run, failed operation, cancelled operation,
or failed commit leaves the source staging available. Nonzero command exit codes
follow the session’s normal commit behavior.
Concurrent operations retain their original parent. Their results become siblings;
a late result does not replace a newer local selection. Use
`commit_result(operation, branch="result")` to select its result explicitly.
`read_file()` reads the current image; staged attachments appear there only after a
committed run. For `LazySession`, pending attachments enter the VM at startup and
are consumed when its snapshot commits. Stage inputs before starting that VM.
Staging and pending-file resolution belong to Session. Store persists their nodes
without interpreting file attachments. Rollback changes only the local selection;
pass `node_id=staged.id` to resume that position in another process. Stored file
references do not guarantee that the uploaded UUID still exists on the server.
## Advanced: prepare directory trees and stream large files
Directory sources expand into regular-file attachments. For example,
`files={"/app": Path("project")}` uploads the contents of `project` under `/app`.
Use `prepare_file_tree()` for exclusions and ownership. It returns ordinary
`UploadFileSpec` objects that can be passed to a session or a transfer component.
Patterns match relative POSIX paths. Patterns without `/` also match basenames
at any depth; matching directories are excluded with their contents. Permission
bits are preserved unless `mode=` is supplied. Ownership defaults to uid=gid=0.
Symlinks and special files raise `ValueError`; empty directories are omitted because
spawn attachments represent files. Normalized destination conflicts are rejected
before uploads start, including a file that would be another file’s parent.
Client-backed transfers send local files as binary streams. Keep source files
unchanged until the upload completes, or use [Reuse uploads and retain their sources](./caching) for a stable temporary
snapshot. Bytes inputs are already in memory. `read_file()` still returns the
whole file; use `iter_file()` or `download_file()` for large results.
The examples upload a directory with an exclusion, then stream a result into a
local file. Configure a connection as described in [Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.files import ClientFileTransfer, prepare_file_tree
>
>
> Path("project").mkdir()
> Path("project/input.txt").write_text("hello\n")
> Path("project/ignored.tmp").write_text("excluded")
> files = prepare_file_tree("project", "/app", exclude=("*.tmp",), mode=0o640)
> progress = []
> with ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> transfer = ClientFileTransfer(client, max_concurrency=2, on_progress=progress.append)
> session = ContreeSession(client, image="tag:alpine:latest", file_transfer=transfer)
> session.run(shell="cat /app/input.txt > /result.txt", files=files)
> count = transfer.download_file(session.image_uuid, "/result.txt", "result.txt")
> assert count == 6
> assert Path("result.txt").read_bytes() == b"hello\n"
> assert progress[-1].direction == "download"
> assert progress[-1].bytes_transferred == 6
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
> from functools import partial
> from pathlib import Path
>
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.files import AsyncClientFileTransfer, prepare_file_tree
>
>
> await asyncio.to_thread(Path("project").mkdir)
> await asyncio.to_thread(Path("project/input.txt").write_text, "hello\n")
> await asyncio.to_thread(Path("project/ignored.tmp").write_text, "excluded")
> files = await asyncio.to_thread(partial(prepare_file_tree, "project", "/app", exclude=("*.tmp",), mode=0o640))
> progress = []
> async with ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> transfer = AsyncClientFileTransfer(client, max_concurrency=2, on_progress=progress.append)
> session = ContreeAsyncSession(client, image="tag:alpine:latest", file_transfer=transfer)
> await session.run(shell="cat /app/input.txt > /result.txt", files=files)
> count = await transfer.download_file(session.image_uuid, "/result.txt", "result.txt")
> assert count == 6
> assert await asyncio.to_thread(Path("result.txt").read_bytes) == b"hello\n"
> assert progress[-1].bytes_transferred == 6
> ```
`max_concurrency` limits uploads within each `prepare_files()` call. Sync defaults
to one worker; async defaults to four. Sync callbacks run in upload worker threads
when concurrency exceeds one, so callbacks and custom clients must support that
usage. Async callbacks run on the event loop and must not block it. Upload events
report a completed file’s size, including server deduplication. Download events
report cumulative bytes received for one file. Callbacks are synchronous and their
exceptions propagate.
An upload failure cancels queued work and joins active workers. Async cancellation
also joins local file I/O before closing files. Uploads already accepted by the
server are not undone. Concurrent calls have separate worker limits.
`download_file()` writes a temporary sibling, flushes it, and replaces the destination
only after the stream completes. Failure, cancellation, or a progress callback error
preserves the previous destination and removes the temporary file. The parent
directory must exist. The replacement uses private temporary-file permissions;
it does not retain the destination’s previous mode. If you iterate `iter_file()`
directly, close it on early exit with `contextlib.closing()` or `aclosing()`.
`write_download()` and `write_download_async()` provide the same atomic local writer
for other byte iterables. These helpers do not own their input streams; the caller
must close them. Custom transfer backends can override `iter_file()`; its default
implementation buffers through `read_file()`.
## Inspect the active VM without stopping it
`LazySession.inspect()` returns a view of the current session. Each file request
selects the active VM or, when the session is cold, its saved image. Retaining the
view does not keep a VM running. Pending staged files start a VM before reading.
The view provides `list`, `grep`, `file_exists`, `archive_exists`, `read_file`,
`iter_file`, `download_file`, and `archive`. Paths use the filesystem root rather
than the command’s working directory. File contents bypass the operation event log.
`download_file` replaces the local destination only after the complete transfer.
> [tab] Sync
>
> ```python theme={null}
> from contextlib import closing
>
> from contree_sdk import create_sandbox_session
>
>
> with create_sandbox_session(image="tag:alpine:latest") as session:
> session.write_file("/result.txt", b"result\n")
> view = session.inspect()
> with closing(view.iter_file("/result.txt")) as chunks:
> content = b"".join(chunks)
> assert content == b"result\n"
> assert session.phase == "running"
> saved = session.inspect_snapshot()
> assert session.phase == "cold"
> image_uuid = saved.image_uuid
> ```
> [tab] Async
>
> ```python theme={null}
> from contextlib import aclosing
>
> from contree_sdk import create_sandbox_session
>
>
> async with create_sandbox_session(image="tag:alpine:latest") as session:
> await session.write_file("/result.txt", b"result\n")
> view = await session.inspect()
> async with aclosing(view.iter_file("/result.txt")) as chunks:
> content = b"".join([chunk async for chunk in chunks])
> assert content == b"result\n"
> assert session.phase == "running"
> saved = await session.inspect_snapshot()
> assert session.phase == "cold"
> image_uuid = saved.image_uuid
> ```
Close streams when iteration stops early. Snapshot and normal session close wait
for accepted live requests, including their streams. File requests count as idle
activity; they do not increase `CommandCountSnapshotPolicy`’s command count.
Requests arriving during a snapshot wait for it to finish. `inspect(timeout=...)`
limits that admission and startup wait; client settings control HTTP timeouts.
Live errors propagate without reading an older image as a fallback.
Live reads can observe concurrent writes. They are not filesystem snapshots.
Live grep also differs from image grep in regex support, encoding, ignore rules,
and highlight spans. Unsupported patterns raise an error; check `truncated` on
successful results. The live API limits transfers to 300 seconds and directory
listings to 10,000 entries. Use `inspect_snapshot()` for a stable image view;
its `image_uuid` remains fixed across later commands. Image metadata through
`view.info()` requires this same snapshot and stops the VM.
# Your first sandbox
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/getting-started
A `sandbox_session` gives you five tools: `run`, `read_file`, `write_file`,
`grep`, and `list_dir`. Use them together to run code and work with files.
The SDK loads your connection from environment variables or a saved profile.
## Use the five tools
Save either program as `sandbox_tools.py`. It writes a file, runs `cat`, reads
the file, finds a matching line, and lists the directory in the same session.
> [tab] Sync
>
> ```python theme={null}
> """Use the five sandbox tools in one session."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as sandbox_session:
> # Write a file in the sandbox.
> sandbox_session.write_file("/work/message.txt", b"Hello from ConTree!\n")
>
> # Run a command and print its output.
> result = sandbox_session.run("cat", args=["/work/message.txt"])
> print(result.stdout)
>
> # Read the file as bytes.
> content = sandbox_session.read_file("/work/message.txt")
> print(content.decode())
>
> # Search file contents.
> matches = sandbox_session.grep("Hello", path="/work/message.txt")
> print(matches)
>
> # List the directory with file metadata.
> directory = sandbox_session.list_dir("/work")
> print(directory)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as sandbox_session:
> # Write a file in the sandbox.
> await sandbox_session.write_file("/work/message.txt", b"Hello from ConTree!\n")
>
> # Run a command and print its output.
> result = await sandbox_session.run("cat", args=["/work/message.txt"])
> print(result.stdout)
>
> # Read the file as bytes.
> content = await sandbox_session.read_file("/work/message.txt")
> print(content.decode())
>
> # Search file contents.
> matches = await sandbox_session.grep("Hello", path="/work/message.txt")
> print(matches)
>
> # List the directory with file metadata.
> directory = await sandbox_session.list_dir("/work")
> print(directory)
>
>
> asyncio.run(main())
> ```
Both programs print the command output, file contents, search matches, and file metadata.
`run()` returns stdout, stderr, and process status. `read_file()` returns bytes;
`write_file()` accepts bytes and creates parent directories. `grep()` and
`list_dir()` return structured results that you can print directly.
Use `print(directory)` for a detailed listing, or `directory.as_text(short=True)` for names only.
### What the default lazy session does
Without `session_type`, the factory selects `LazySession` for Sync and
`AsyncLazySession` for Async. Both have the same behavior. “Lazy” means the VM
starts when needed, and several commands can share one snapshot.
```mermaid theme={null}
sequenceDiagram
participant S as SDK
participant V1 as MicroVM 1
participant V2 as MicroVM 2
S->>V1: Run commands
Note over S,V1: 10 s idle
S->>V1: Save and stop
S->>V2: Start from saved files
```
Select the lazy type explicitly and call `uptime` twice. Both calls use the same
MicroVM. These examples use your configured connection; add `profile="work"`
or the [token arguments below](#create-a-session-from-a-token) when needed.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import LazySession, create_sandbox_session
>
>
> with create_sandbox_session(
> image="tag:alpine:latest",
> session_type=LazySession,
> ) as session:
> print(session.run("uptime").stdout)
> print(session.run("uptime").stdout)
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import AsyncLazySession, create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(
> image="tag:alpine:latest",
> session_type=AsyncLazySession,
> ) as session:
> print((await session.run("uptime")).stdout)
> print((await session.run("uptime")).stdout)
>
>
> asyncio.run(main())
> ```
Creating the session or entering its context does not start a VM. The first
`run()` or `write_file()` starts it. Later commands reuse that VM, so installed
packages, files, and running processes remain available until a snapshot.
After the last command or file request finishes, the default idle timer waits
10 seconds. It then saves the filesystem as an image and stops the VM in the
background, without another call from your code. The next command starts a new
VM from that saved image automatically. Reads, searches, and directory listings
can use the saved image without starting a VM.
A snapshot preserves files, including installed packages, but loses processes
and memory. For example, a file remains after an idle pause; a background web
server must be started again. Each VM also has a lifetime limit; see
[VM lifetime settings](./advanced#select-the-session-class-and-components).
Normal context exit saves pending changes. An exception discards changes since
the last completed snapshot. To save after every command instead, select the
[session type shown below](#save-after-every-command).
The image tag must exist on your endpoint and provide `sleep`, `sh`, `mkdir`, and
`cat`. Replace `tag:alpine:latest` with an available image, or use [Import a Docker image](./images)
to prepare one. Configure credentials in [Connection sources](#sandbox-connection).
## Install the SDK
These guides describe the breaking **0.5 development API** and require Python
3.10–3.14. Run the installation command from this repository checkout; the
published 0.4 package does not provide the new API.
```bash theme={null}
pip install -e ".[async]"
```
For synchronous programs only, `pip install -e .` is sufficient.
## Initialize a session
Choose one connection source: pass a token and AI project, or select a saved
profile. Both paths return the same session with all five tools. The SDK creates
and closes the client for you; retries are enabled by default.
### Create a session from a token
Replace `your-token` and `your-ai-project` with your credentials. Without `url`,
the SDK uses `https://api.tokenfactory.nebius.com/sandboxes`. Pass `url=...` when
using another deployment.
> [tab] Sync
>
> ```python theme={null}
> """Create a sandbox session from a token."""
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
>
>
> def main() -> None:
> with create_sandbox_session(
> image="tag:alpine:latest",
> token="your-token",
> project="your-ai-project",
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(60)},
> ) as sandbox_session:
> result = sandbox_session.run("echo", args=["Hello from ConTree!"])
> print(result.stdout)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
>
>
> async def main() -> None:
> async with create_sandbox_session(
> image="tag:alpine:latest",
> token="your-token",
> project="your-ai-project",
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(60)},
> ) as sandbox_session:
> result = await sandbox_session.run("echo", args=["Hello from ConTree!"])
> print(result.stdout)
>
>
> asyncio.run(main())
> ```
### Create a session from a saved profile
Save this file as `contree.ini` in the directory where you run the program.
Replace the token and AI project values with your credentials:
```ini theme={null}
[DEFAULT]
profile = work
[profile:work]
type = iam
url = https://api.tokenfactory.nebius.com/sandboxes
token = your-token
project = your-ai-project
```
The program selects `work` from this file:
> [tab] Sync
>
> ```python theme={null}
> """Create a sandbox session from a saved profile."""
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
>
>
> def main() -> None:
> with create_sandbox_session(
> image="tag:alpine:latest",
> profile="work",
> config_path="contree.ini",
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(60)},
> ) as sandbox_session:
> result = sandbox_session.run("echo", args=["Hello from ConTree!"])
> print(result.stdout)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.session import IdleSnapshotPolicy
>
>
> async def main() -> None:
> async with create_sandbox_session(
> image="tag:alpine:latest",
> profile="work",
> config_path="contree.ini",
> session_kwargs={"snapshot_policy": IdleSnapshotPolicy(60)},
> ) as sandbox_session:
> result = await sandbox_session.run("echo", args=["Hello from ConTree!"])
> print(result.stdout)
>
>
> asyncio.run(main())
> ```
If the profile already exists in the client’s standard configuration, pass only
`profile="work"` and omit `config_path`. Do not combine `profile` with `token`,
`project`, or `url`; put those values in the profile instead.
### Session options and defaults
Both examples use `session_kwargs` to set a 60-second idle interval. Omit that
argument to use the default of 10 seconds. Session constructor options belong
inside `session_kwargs`; client options such as `retry` and `timeout` belong
on the factory call.
The factory selects `LazySession` for `with` and `AsyncLazySession` for
`async with`. Set `session_type` only when selecting another class or a subclass.
Use `create_sync_sandbox_session()` or `create_async_sandbox_session()` if you
want to select the context protocol explicitly; they accept the same arguments.
Creating the context opens no connection. Entering it prepares the session;
the first command starts the VM. Normal exit saves pending file changes and
closes owned resources. An exception discards changes since the last snapshot.
SDK-created clients use `contree_client.RetryPolicy()` by default. Pass
`retry=RetryPolicy(...)` to customize it, or `retry=None` to disable retries.
A client supplied through `client=` keeps its existing retry configuration.
See [Advanced usage](./advanced) for more session options and component ownership.
### Save after every command
Select `ContreeSession` for Sync or `ContreeAsyncSession` for Async. These classes
start a separate VM for each `run()` and save its filesystem before returning.
The next command uses that saved image. You do not call `snapshot()` or wait for
an idle timeout.
```mermaid theme={null}
sequenceDiagram
participant S as SDK
participant V1 as MicroVM 1
participant V2 as MicroVM 2
S->>V1: Run, save, stop
S->>V2: Run from saved files, save, stop
```
Call `uptime` twice with the regular session type. Each call starts a new
MicroVM; the second uses the filesystem saved by the first. Connection arguments
are the same as in the lazy example.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(
> image="tag:alpine:latest",
> session_type=ContreeSession,
> ) as session:
> print(session.run("uptime").stdout)
> print(session.run("uptime").stdout)
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(
> image="tag:alpine:latest",
> session_type=ContreeAsyncSession,
> ) as session:
> print((await session.run("uptime")).stdout)
> print((await session.run("uptime")).stdout)
>
>
> asyncio.run(main())
> ```
In the lazy example, both commands share a running VM. In this example,
the VM restarts between commands. `uptime` output is rounded, so two immediate
calls can print similar values in either mode. Files survive the restart;
processes and memory do not.
`disposable=False` is the default. Passing `disposable=True` to a command skips
saving its changes. By default, a completed operation is saved even if its
process exits with a nonzero code. Failed or cancelled operations do not advance
the session history. See [Work with a Session](./session-model) for checkpoint and error behavior.
### Connection sources
Configure the endpoint URL, token, and AI project for your deployment. The
project identifies where the sandbox runs; omitting it is not a complete working
configuration.
| Setting | Environment | Profile / INI | Direct factory argument |
| - | - | - | - |
| Endpoint | `CONTREE_URL` | `url` | `url` |
| Token | `CONTREE_TOKEN` or `NEBIUS_API_KEY` | `token` | `token` |
| AI project | `CONTREE_PROJECT` or `NEBIUS_AI_PROJECT` | `project` | `project` |
The SDK delegates environment parsing to contree-client.
Use exactly one explicit source:
| Source | Arguments | Behavior |
| - | - | - |
| Direct credentials | `url`, `project`, `token` | Build a regular client `Profile`. Token is required. An omitted URL uses the client’s default endpoint. |
| Profile object | `profile=profile` | Use that exact profile. Do not combine it with direct credentials or `config_path`. |
| Named profile | `profile="work"`, optional `config_path` | Resolve that name through contree-client. |
| Explicit INI | `config_path="config.ini"` | Resolve the file’s active profile, or the name selected by `CONTREE_PROFILE`. |
| Automatic | Omit all source arguments | Use `contree_client.profiles.from_env()`, then the client’s default profile resolution. |
Direct credentials cannot be combined with `profile` or `config_path`.
Incomplete explicit credentials raise an error rather than falling back to ENV.
An explicit source takes priority over ENV. Without one, the environment needs
both `CONTREE_URL` and `CONTREE_TOKEN` (or `NEBIUS_API_KEY`). Provide the project
through `CONTREE_PROJECT` (or `NEBIUS_AI_PROJECT`).
For INI resolution, contree-client uses an explicit profile name, then
`CONTREE_PROFILE`, then the active profile in the file. Its default files are
`cli.ini` and `auth.ini` under `CONTREE_HOME`; `auth.ini` takes priority. Without
`CONTREE_HOME`, the client uses its XDG configuration directory. A supplied
`config_path` replaces the auth file path and can be named `config.ini`; the
client also reads `cli.ini` from the same directory.
The SDK uses credentials from the selected profile; it does not acquire or
refresh credentials itself. For a profile constructed in Python, pass a
`contree_client.profiles.Profile` as `profile=...`. The `profile_from_args()`
helper constructs this object without writing a configuration file.
Continue with [Import a Docker image](./images) to import a Docker image for your sandbox.
# Import a Docker image
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/images
Use `sync_import_image` or `async_import_image` to import a registry image.
Each helper waits for completion and returns an image UUID for the sandbox factory.
An imported image can be the common starting point for several experiments.
[Work with a Session](./session-model) explains how to save changes, branch
from a checkpoint, and return to an earlier state.
Configure the endpoint, token, and AI project as described in
[Connection sources](./getting-started#sandbox-connection). The registry must be reachable from the ConTree server.
The example imports Alpine through a Docker Hub mirror and assigns the ConTree
tag `alpine:latest`. Replace the registry URL with one available to your server.
## Import and run a command
Save either program as `import_image.py` and run it with Python. Both programs
wait for the import to finish, open a sandbox, and print `Hello from an imported image!`.
The helpers use the same connection configuration as the sandbox factory.
> [tab] Sync
>
> ```python theme={null}
> """Import a registry image and run a command in a sandbox."""
>
> from contree_sdk import create_sandbox_session, sync_import_image
>
>
> def main() -> None:
> image = sync_import_image("docker://mirror.gcr.io/library/alpine:latest", tag="alpine:latest")
> with create_sandbox_session(image=image) as sandbox:
> result = sandbox.run("echo", args=["Hello from an imported image!"])
> print(result.stdout)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session, async_import_image
>
>
> async def main() -> None:
> image = await async_import_image("docker://mirror.gcr.io/library/alpine:latest", tag="alpine:latest")
> async with create_sandbox_session(image=image) as sandbox:
> result = await sandbox.run("echo", args=["Hello from an imported image!"])
> print(result.stdout)
>
>
> asyncio.run(main())
> ```
The helpers return only after a successful import. A failed import raises
`FailedOperationError`. Assigning an existing ConTree tag moves it to the imported image.
The import supplies a filesystem. It does not start the registry image’s `CMD`
or `ENTRYPOINT`, and it does not apply its `WORKDIR`. Select the command and
working directory when running the sandbox.
## Write a Docker URL
Pass the registry source as the first argument to `sync_import_image` or
`async_import_image`. A full URL has this form:
```text theme={null}
docker://[:]/:
```
Replace the angle-bracket placeholders; the port is optional. The repository
includes its namespace, such as `library/alpine` or `my-team/my-app`.
| Source URL | Meaning |
| - | - |
| `docker://docker.io/library/alpine:latest` | Official Alpine image on Docker Hub. |
| `docker://mirror.gcr.io/library/alpine:latest` | The mirror used in the example above. |
| `docker://ghcr.io/my-team/my-app:v1` | An organization’s image on GitHub Container Registry. |
| `docker://registry.example.com:5000/my-team/my-app:v1` | A registry with an explicit port. Replace the host and repository. |
For Docker Hub official images, use the `library/` namespace. Keep the
`docker://` prefix when writing a full source URL; do not replace it with
`https://` or a registry’s web page URL.
To select an exact registry manifest, replace `:` with
`@sha256:<64-hex-digit-digest>`. Copy the complete digest from the registry.
See the [Docker transport reference](https://github.com/containers/image/blob/main/docs/containers-transports.5.md#dockerdocker-reference)
for the underlying syntax.
String arguments also accept short names. The SDK expands `alpine` to
`docker://docker.io/library/alpine:latest`, `alpine:3.22` to
`docker://docker.io/library/alpine:3.22`, and `my-team/my-app:v1` to
`docker://docker.io/my-team/my-app:v1`. A string that starts with `docker://`
is passed through unchanged, so use the complete form shown above.
The source tag selects the registry image to import. The helper’s `tag=` argument
assigns a separate ConTree tag to the result; these names can differ.
For private registries, pass credentials through `ImageImportRegistry` as
described under Configuration below.
## Reuse the imported image
Pass either of these references to `create_sandbox_session(image=...)`:
| Reference | Use |
| - | - |
| `tag:alpine:latest` | ConTree tag passed to the sandbox factory. |
| The returned image UUID | The specific imported filesystem, even if its tag later moves. |
The factory does not import missing images; an unknown tag raises `NotFoundError`.
Dockerfile `FROM` has separate behavior: the builder imports a missing base image
from its registry. See [Build a Docker image](./building-images).
## Configuration
The import cache maps a registry source to its imported ConTree image UUID.
A repeated call with the same source, requested ConTree tag, and credentials
returns that UUID without another registry import. If `tag=` is supplied, the
helper reapplies it to the cached image. The image itself stays on the ConTree
server; the local cache contains only its UUID.
Records expire after one hour by default. Until then, a moved registry tag still
returns the cached image. Pass `no_cache=True` to import it again and refresh the
record. Keep cached images available on the server.
Records are stored in `$XDG_CACHE_HOME/contree/images.sqlite3`, or
`~/.cache/contree/images.sqlite3` when XDG is unset. Connections and registry
credentials have separate cache keys. Credentials are hashed, not stored in plaintext.
Use `cache_ttl=` to change the lifetime or `cache_dir=` to choose another directory.
For several operations, initialize a client once and pass it through `client=`.
The client is a shared dependency for import, build, and sandbox operations.
See the complete Sync/Async example in [Share one client](./advanced#shared-image-client).
The caller closes a supplied client. Helpers close clients they create themselves.
Pass an `ImageImportRegistry` object instead of a string when the registry needs
credentials. Pass `store=` to use your own Store for import results.
See [Image helpers](./reference/images) for connection and retention parameters.
Continue with [Build a Docker image](./building-images) to build a Docker image from a Dockerfile.
# Advanced: assemble a sandbox yourself
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/manual-sandbox
`create_sandbox_session` connects the SDK components into a familiar sandbox
interface. ConTree executes from filesystem images; a long-lived, mutable VM is
not its persistence model. The default `LazySession` provides continuity between
commands, then saves files at a snapshot boundary.
Use the factory for normal application code. Build the components directly when
you need to control their construction, share them, or replace their behavior.
These examples show the components behind the default sandbox and their cleanup
order. Configure a connection as described in [Connection sources](./getting-started#sandbox-connection) and use
an available image with `sleep`, a POSIX shell, and `cat`.
## What the factory supplies
| Component | Factory default | Your control |
| - | - | - |
| Connection | Resolve a Profile from explicit arguments, ENV, or INI. | Supply a Profile or an already configured client. |
| Client | HTTPX for sync; aiohttp for async. | Select a client class or manage the connection yourself. |
| Store | A memory Store for history and reusable uploads. | Supply SQLite or your own Store implementation. |
| File transfer | A cached client transfer for uploads and saved-image reads. | Customize the underlying transfer; reuse uses the same Store. |
| Base session | `ContreeSession` or `ContreeAsyncSession`. | Extend request preparation, commits, or operation creation. |
| Lazy session | Reuse one VM; snapshot after 10 idle seconds. | Select a policy or subclass the lazy session. |
| Cleanup | Finish the session, then close owned storage and the client. | Manage component lifetimes explicitly; borrowed objects remain yours. |
The factory reuses uploads through the same Store, with `cache_ttl=60` by default.
See [Reuse uploads and retain their sources](./caching) for lifetime and connection-scope details.
## Build the default components explicitly
Both programs write a file, read it in the same VM, and print
`Hello from ConTree!`. Normal exit saves pending filesystem changes. An exception
inside the lazy context discards changes since its last completed snapshot.
> [tab] Sync
>
> ```python theme={null}
> """Assemble a sandbox and run two commands."""
>
> from contree_client import profiles
> from contree_client.httpx import ContreeClient
>
> from contree_sdk import ContreeSession, LazySession
> from contree_sdk.files import ClientFileTransfer
> from contree_sdk.session import IdleSnapshotPolicy
> from contree_sdk.store import SyncMemoryStore
> from contree_sdk.scope import StoreScope
> from contree_sdk.upload_cache import CachedFileTransfer
>
>
> def main() -> None:
> profile = profiles.from_env() or profiles.resolve_profile()
> with ContreeClient.from_profile(profile) as client:
> with SyncMemoryStore() as store:
> transfer = CachedFileTransfer(
> ClientFileTransfer(client), store, scope=StoreScope.from_client(client), ttl=60
> )
> base = ContreeSession(client, image="tag:alpine:latest", store=store, file_transfer=transfer)
> policy = IdleSnapshotPolicy(10)
> with LazySession(base, snapshot_policy=policy) as sandbox:
> sandbox.run(shell="echo 'Hello from ConTree!' > /message.txt")
> result = sandbox.run("cat", args=["/message.txt"])
> print(result.stdout)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_client import profiles
> from contree_client.aiohttp import ContreeAsyncClient
>
> from contree_sdk import AsyncLazySession, ContreeAsyncSession
> from contree_sdk.files import AsyncClientFileTransfer
> from contree_sdk.session import IdleSnapshotPolicy
> from contree_sdk.store import AsyncMemoryStore
> from contree_sdk.scope import StoreScope
> from contree_sdk.upload_cache import AsyncCachedFileTransfer
>
>
> async def main() -> None:
> profile = profiles.from_env() or profiles.resolve_profile()
> async with ContreeAsyncClient.from_profile(profile) as client:
> async with AsyncMemoryStore() as store:
> transfer = AsyncCachedFileTransfer(
> AsyncClientFileTransfer(client), store, scope=StoreScope.from_client(client), ttl=60
> )
> base = ContreeAsyncSession(client, image="tag:alpine:latest", store=store, file_transfer=transfer)
> await base.ensure_ready()
> policy = IdleSnapshotPolicy(10)
> async with AsyncLazySession(base, snapshot_policy=policy) as sandbox:
> await sandbox.run(shell="echo 'Hello from ConTree!' > /message.txt")
> result = await sandbox.run("cat", args=["/message.txt"])
> print(result.stdout)
>
>
> asyncio.run(main())
> ```
`ensure_ready()` resolves the initial image and history; it does not start a VM.
The first lazy command starts the VM. The lazy context exits before the store and
client contexts, so saving can still use both components.
These programs show ordinary component assembly. The factory also handles partial
entry failures, preserves a body exception if cleanup fails, and joins async
cleanup under repeated cancellation. Reuse its context implementation when those
guarantees are needed in a custom factory; see [Sandbox factories](./reference/sandbox).
## Change one component without rebuilding everything
The factory accepts the same extension points. This selects a custom base session
that adds a default command timeout. Each command uses an independent operation.
> [tab] Sync
>
> ```python theme={null}
> from dataclasses import replace
>
> from contree_sdk import ContreeSession, RunRequest, create_sync_sandbox_session
>
>
> class TimedSession(ContreeSession):
> def prepare_request(self, request: RunRequest) -> RunRequest:
> request = super().prepare_request(request)
> return replace(request, timeout=30 if request.timeout is None else request.timeout)
>
>
> with create_sync_sandbox_session(image="tag:alpine:latest", session_type=TimedSession) as session:
> session.run("echo", args=["Custom request policy"])
> ```
> [tab] Async
>
> ```python theme={null}
> from dataclasses import replace
>
> from contree_sdk import ContreeAsyncSession, RunRequest, create_async_sandbox_session
>
>
> class TimedAsyncSession(ContreeAsyncSession):
> def prepare_request(self, request: RunRequest) -> RunRequest:
> request = super().prepare_request(request)
> return replace(request, timeout=30 if request.timeout is None else request.timeout)
>
>
> async with create_async_sandbox_session(image="tag:alpine:latest", session_type=TimedAsyncSession) as session:
> await session.run("echo", args=["Custom request policy"])
> ```
Selecting `ContreeSession` or `ContreeAsyncSession` saves each command by default
in a separate VM. Use `disposable=True` to leave the session image unchanged.
Selecting a lazy subclass retains a shared VM until a snapshot. Snapshots are
lightweight and can run after every command, but they stop the VM. An unchanged
filesystem can produce the same image UUID. `session_kwargs`
configures the selected class; `store`, `file_transfer`, and `commit_policy`
configure its underlying base session. To supply a custom base session inside a
lazy wrapper, assemble them directly as above.
Continue with [Customize the SDK](./customization) for public hooks and component contracts,
and [Sessions and operations](./reference/session) for snapshot policies. Snapshots
preserve files, not processes, memory, or sockets.
# Upgrade to the 0.5 session API
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/migration
Version 0.5 removes the previous SDK API without compatibility aliases.
Update imports, execution, and result handling as follows.
| Previous API | Replacement |
| - | - |
| `Contree` / `ContreeSync` | `create_sandbox_session` with `with` or `async with`. |
| SDK image and file managers | [Image import](./images), [build helpers](./building-images), and [session file operations](./files). Use the client for image listing and tags. |
| Image objects and `ContreeSessionSync` | An image UUID or tag passed to the factory; select a class with `session_type=` if needed. |
| `.run(...).wait().result` | `session.run(...)` returns `InstanceResult`; await it in async code. |
| SDK result wrappers | `result.state.exit_code`, `result.stdout.as_text()`, and `result.stderr.as_bytes()`. Optional API fields can be `Ellipsis`. |
| `.popen()` | [Operation subprocesses](./operation), created through `session.spawn()`. |
| SDK auth/configuration | `contree_client` profiles and transports; see [Connection sources](./getting-started#sandbox-connection). |
## Choose when to save
The factory defaults to `LazySession` or `AsyncLazySession`. Commands share a VM.
Normal context exit saves pending files; an exception discards changes since the
last snapshot. File requests through `inspect()` and `read_file()` now read the
active VM without saving or stopping it. This requires `contree-client>=0.5.1`
and a server runtime with live inspection support.
`inspect()` returns a session-bound view that selects the current source on each
request. Use `inspect_snapshot()` for a stable image view and its `image_uuid`.
Image metadata through `inspect().info()` also requires a snapshot and stops the
VM. Close file and archive streams when stopping iteration early; snapshot waits
for accepted live requests to finish.
Call `snapshot()` before switching branches or rolling back.
Select `session_type=ContreeSession` or `ContreeAsyncSession` for a separate VM
per command. `run()`, `spawn()`, `spawn_detached()`, and `RunRequest` now default
to `disposable=False`. `run()` and `execute()` commit completed results; after
`spawn()`, wait and call `commit_result()` explicitly. Pass `disposable=True`
to leave history unchanged.
Snapshots are lightweight and can run after every command. They stop the VM;
processes and memory do not survive. Unchanged files can produce the same image
UUID. See [Work with a Session](./session-model) for sync and async examples.
## Check command results
An API-successful operation can return a nonzero process exit code. The default
`ApiSuccessCommitPolicy` still commits its image. Use `ZeroExitCommitPolicy`
to save only results with exit code zero; see
[Select a commit policy](./customization#select-a-commit-policy).
Cancellation raises `InterruptedError`; operation failure raises
`FailedOperationError`. Neither advances history. A `PendingRun` returned by
async `run()` can be consumed once. See [Handle failures and unexpected state](./troubleshooting) for handling errors.
## Preserve history and manage resources
The factory closes the client and memory store it creates. Close components you
supply with `with` or `async with`; use matching sync or async implementations.
Install `contree-sdk[async]` for async transport and SQLite dependencies.
To resume after Python exits, supply a SQLite store and the same `session_id`.
History stores image references; the images must remain available on the server.
See [Save and resume a session](./sessions) and [Advanced: assemble a sandbox yourself](./manual-sandbox).
Commits preserve the parent selected when the operation started. Concurrent
results form sibling nodes; they do not replace each other. Branch names and the
selected node belong to each Session instance. Pass `node_id` to resume a specific
position. See [Select a late result](./troubleshooting#advanced-select-a-late-result)
for selecting a completed result without rerunning the command.
## Update integrations and extensions
Use `ContreeSandbox` for sync executors and `ContreeAsyncSandbox` for async
executors. See [LangChain DeepAgents](../integrations/langchain). The mini-swe-agent 2.4.6 adapter
still uses the removed API; see [mini-swe-agent](../integrations/mini-swe-agent).
For Dockerfile builds, use [Build a Docker image](./building-images). Direct builder classes and
custom directives are covered in [Advanced usage](./advanced) and [Customize the SDK](./customization).
Move session overrides to `prepare_request()`, `submit_request()`, or
`create_operation()`. Inject file I/O with `file_transfer=`. The operation’s
source history position is available through `operation.context`.
# Advanced: control a running sandbox
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/operation
For ordinary commands, start with [Your first sandbox](./getting-started) and its sandbox factory.
This guide exposes lower-level controls. See [Advanced: assemble a sandbox yourself](./manual-sandbox) for manual
component assembly and resource ownership.
Use `run()` when you only need a completed result. Use `spawn()` to obtain an
operation handle immediately, stream output, send input, or cancel work.
Enter an operation context to start additional processes in the same running sandbox.
Use [Advanced: resume a background operation](./detached-operations) to save its context and collect the result after
restarting Python.
> [!NOTE]
>
> Async snippets with top-level `await` run inside an async function or a notebook
> that supports it. For a standalone script, use the `asyncio.run(main())` structure
> from [Your first sandbox](./getting-started).
## Run an additional process
This program keeps a sandbox alive with `sleep`, runs `echo` inside it, and streams
the output locally. Configure a connection as described in [Connection sources](./getting-started#sandbox-connection).
> [tab] Sync
>
> ```python theme={null}
> """Run a subprocess inside an operation."""
>
> import sys
>
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> operation = session.spawn(shell="sleep 300", timeout=60)
> with operation:
> process = operation.run("echo", args=["Hello from a subprocess!"])
> process.pipe_to(stdout=sys.stdout, stderr=sys.stderr)
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
> import sys
>
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> operation = await session.spawn(shell="sleep 300", timeout=60)
> async with operation:
> process = await operation.run("echo", args=["Hello from a subprocess!"])
> await process.pipe_to(stdout=sys.stdout, stderr=sys.stderr)
>
>
> asyncio.run(main())
> ```
On context exit, the SDK signals the main process, waits for shutdown, and attempts
cancellation if it does not stop. This happens even when the block raises an exception.
The subprocess shares the operation’s live filesystem. It has its own `spid` and
result, but no separate session-history entry.
To place already-uploaded files in a running operation, pass the prepared
path-to-`FileSpec` mapping to `operation.apply_files()` (await it for an async
operation). For example, `operation.apply_files(session.file_transfer.prepare_files({"/input": b"data"}) or {})`.
The call replaces existing files by default. Live upload uses the VM runtime user
and mode `0644`; non-default `FileSpec` ownership or mode is rejected. Each file
is applied separately, so a later failure does not undo earlier attachments.
## Choose the right handle
| Call | What you receive |
| - | - |
| `session.run(...)` | A completed `InstanceResult`. |
| `session.spawn(...)` | An `OperationContract` for the main process. |
| `operation.run(...)` inside a context | A `SubprocessContract` for an additional process. |
| `await session.run(...)` | A completed `InstanceResult` in async code. |
| `await session.spawn(...)` | An `AsyncOperationContract`. |
| `await operation.run(...)` inside `async with` | An `AsyncSubprocessContract`. |
Async `session.run()` also supports `async with`. Its pending call can be consumed
once. A sync `run()` returns a result and cannot be used as an operation context.
## Stream the main process
Iterate `operation.events()` when you need live output without additional processes.
Print stream payloads directly; `print()` adds a newline after each payload.
> [tab] Sync
>
> ```python theme={null}
> from contree_client.models import EventDataStream
>
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> operation = session.spawn(shell="echo hello")
> for event in operation.events():
> if event.type in {"stdout", "stderr"} and isinstance(event.data, EventDataStream):
> print(event.data)
> operation.wait()
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_client.models import EventDataStream
>
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> operation = await session.spawn(shell="echo hello")
> async for event in operation.events():
> if event.type in {"stdout", "stderr"} and isinstance(event.data, EventDataStream):
> print(event.data)
> await operation.wait()
> ```
## One reader per operation handle
`events()`, `wait()`, and subprocess handles share one unfiltered SSE reader.
It starts when the context is entered or when the first event iterator or wait is
consumed. A sync operation uses one reader thread; an async operation uses one task.
Transport reconnection remains the responsibility of `contree-client`.
Each `events()` iterator has an independent cursor. Events are retained in memory
for the lifetime of the handle, so a late subscriber can replay them without another
network stream. `since=N` selects event IDs greater than `N`; `spid=N` selects that
process. A process filter excludes the operation-wide `completion` event, but the
iterator still ends when the shared reader ends. Large event logs consume memory;
release completed handles when replay is no longer needed.
`wait()` uses the same reader and then fetches the final status once. Repeated waits
reuse that response. Closing or cancelling an event iterator only removes that
subscriber. A failed or cancelled operation `wait()` attempts remote cancellation
and therefore affects all consumers of the operation. Call `shutdown()` if you
stop consuming before completion and no longer need the operation.
Session `run()`, `execute()`, and `wait_operation()` and Docker builds close the
operation handles they create. Async cleanup waits for the reader to stop, even
if the caller cancels again during cleanup. Cleanup can extend a timeout while
cancellation requests and reader shutdown finish. These helpers do not close a
client supplied by the caller.
Synchronous shutdown waits for the reader thread for a bounded time. It cannot
interrupt an arbitrary blocking event source. If the source remains blocked,
the thread exits only when that source returns or raises.
Sharing applies to one `Operation` or `AsyncOperation` object. Constructing another
handle for the same UUID creates a separate owner and can open another stream.
Reuse the existing handle when consumers run in the same application.
## Keep the result image
`spawn()` retains the result image by default. Wait for completion, then call
`commit_result(operation)` to advance session history. `run()` commits automatically.
Use `disposable=True` to leave the session image unchanged.
Saving an image is lightweight and can happen after every command. It stops the
VM; if files have not changed, the result can have the same image UUID.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> operation = session.spawn(shell="echo saved > /saved.txt")
> result = operation.wait()
> entry = session.commit_result(operation, title="Save output")
> print(entry.image_uuid)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> operation = await session.spawn(shell="echo saved > /saved.txt")
> result = await operation.wait()
> entry = await session.commit_result(operation, title="Save output")
> print(entry.image_uuid)
> ```
A subprocess’s writes can be part of that operation’s final filesystem image; only
the whole operation creates a history entry.
A UUID-only handle can inspect, wait for, or cancel an existing operation. It has no
session history context, so `commit_result()` cannot use it. Keep the original
session-created handle when you intend to commit.
A subprocess remembers its exit event. `wait()` after iteration does not wait for
another exit. Stream failures propagate to consumers. Operation `wait()` attempts
remote cancellation if waiting fails or is cancelled, while preserving the original error.
## Stream input with bounded memory
Start the process with `stdin_open=True`. This keeps remote stdin open until you
send EOF. `pipe_stdin()` waits for that process’s `spawn` event, sends chunks in
order, and sends an empty EOF request when the source ends. Its default maximum
input chunk size is 64 KiB after UTF-8 encoding. Base64 transport adds overhead.
Supply an iterable of `str` or `bytes` in sync code, or an async iterable in async
code. The SDK holds one source chunk at a time and splits large chunks before
sending them. To bound total input memory, keep the source’s chunks bounded too.
`stdin=...` remains an eager initial payload; use `pipe_stdin()` for large files.
> [tab] Sync
>
> ```python theme={null}
> from functools import partial
> from pathlib import Path
>
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> # Create sample input; replace it with your own file when using this workflow.
> Path("input.bin").write_bytes(bytes(range(256)) * 1024)
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> operation = session.spawn("cat", stdin_open=True)
> with open("input.bin", "rb") as source:
> delivery = operation.pipe_stdin(iter(partial(source.read, 65536), b""))
> result = operation.wait()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
> from pathlib import Path
>
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> # Create sample input before starting the remote process.
> Path("input.bin").write_bytes(bytes(range(256)) * 1024)
>
>
> async def input_chunks():
> source = await asyncio.to_thread(open, "input.bin", "rb")
> try:
> while chunk := await asyncio.to_thread(source.read, 65536):
> yield chunk
> finally:
> await asyncio.to_thread(source.close)
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> operation = await session.spawn("cat", stdin_open=True)
> source = input_chunks()
> try:
> delivery = await operation.pipe_stdin(source)
> finally:
> await source.aclose()
> result = await operation.wait()
> ```
`StdinResult.bytes_sent` counts bytes acknowledged by the server. It does not
prove that the process consumed them. `eof_sent` records successful EOF delivery.
If the shared reader observes an exit or operation completion before delivery
finishes, `process_exited` is true and the SDK stops sending input.
The caller owns the input source. A sync iterator can block inside `next()`;
the SDK checks for exit before and after that read but cannot interrupt arbitrary
blocking Python code. Use an interruptible source for live TTY input. Async
forwarding cancels a pending source read when the process exits. Sources must
cooperate with cancellation; cancelling `asyncio.to_thread()` does not stop its
underlying thread. The file example uses finite reads from a regular file.
Input-source errors, transport errors, and cancellation cancel the operation and
preserve the original exception. The SDK never retries stdin writes: a timeout
can mean that some bytes were delivered. An exit can race with a write and cause
a transport error instead of a `process_exited` result.
Use one writer per process. Set `close=False` on `pipe_stdin()` to deliver several
input batches before EOF. For a child process, use
`operation.run(..., stdin_open=True)` and pass its `spid` to `pipe_stdin()`.
`send_stdin()` remains a low-level single-write method; it does not wait for spawn
or manage input-source errors. Its default `close=True` sends EOF after that write.
`pipe_stdin()` returns after input delivery, without waiting for the operation.
Save `operation.uuid` if another owner will wait for completion. Do not enter an
operation context for this handoff: context exit stops the main process. The
shared reader remains active until completion or client closure. Input forwarding,
`events()`, and `wait()` on one handle use one transport subscription.
An optional `events(timeout=...)` limits that subscription. Timeout stops only
that subscriber; call `cancel()` to stop the remote operation. The client
resumes that subscription after a connection loss; input is not replayed.
`signal()` sends a signal without waiting. `cancel()` requests operation
cancellation. `wait()` returns the typed `InstanceResult`, including nonzero
process exit codes. A cancelled operation raises `InterruptedError`; an operation
failure raises `FailedOperationError`.
## Reattach to an operation by UUID
Save `operation.uuid` when another process must inspect or cancel work.
Construct a handle with the same UUID and a client for the same server. This does
not start a new operation or restore session history context.
> [tab] Sync
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.sync import ContreeClient
>
> from contree_sdk import ContreeSession
> from contree_sdk.session import Operation
>
>
> with ContreeClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> session = ContreeSession(client, image="tag:alpine:latest")
> operation = session.spawn("echo", args=["hello"])
> saved_uuid = operation.uuid
> reattached = Operation(client, saved_uuid)
> result = reattached.wait()
> print(reattached.uuid)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_client import profiles
> from contree_client.asyncio import ContreeAsyncClient
>
> from contree_sdk import ContreeAsyncSession
> from contree_sdk.session import AsyncOperation
>
>
> async with ContreeAsyncClient.from_profile(profiles.from_env() or profiles.resolve_profile()) as client:
> session = ContreeAsyncSession(client, image="tag:alpine:latest")
> operation = await session.spawn("echo", args=["hello"])
> saved_uuid = operation.uuid
> reattached = AsyncOperation(client, saved_uuid)
> result = await reattached.wait()
> print(reattached.uuid)
> ```
# Caches and upload sources
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/cache
Builders keep layer history, upload results, and URL-download metadata in one
Store. Helpers and direct builders accept `store=`. Tree kinds
separate reusable records from user sessions. Node data contains JSON values.
See [Build a Docker image](../building-images), [Tree stores](./store), and [Reuse uploads and retain their sources](../caching) for retention,
connection scope, and upload provenance.
Upload reuse through the public file-transfer and store contracts.
## `class AsyncCachedFileTransfer`
```python theme={null}
class contree_sdk.upload_cache.AsyncCachedFileTransfer(transfer, store, *, scope, ttl, sources)
```
Cache content uploads; apply permissions from each current request.
ttl is required and measured from upload completion. Hits do not renew it.
Concurrent misses may upload the same content. The caller owns all components.
### Methods
#### `download_file()`
```python theme={null}
async def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `iter_file()`
```python theme={null}
def iter_file(image_uuid, path) -> AsyncGenerator[bytes, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `AsyncGenerator[bytes, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
## `class CachedFileTransfer`
```python theme={null}
class contree_sdk.upload_cache.CachedFileTransfer(transfer, store, *, scope, ttl, sources)
```
Cache content uploads; apply permissions from each current request.
ttl is required and measured from upload completion. Hits do not renew it.
Concurrent misses may upload the same content. The caller owns all components.
### Methods
#### `download_file()`
```python theme={null}
def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `iter_file()`
```python theme={null}
def iter_file(image_uuid, path) -> Generator[bytes, None, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `Generator[bytes, None, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
## `class UploadSnapshot`
```python theme={null}
class contree_sdk.upload_cache.UploadSnapshot(file, sha256, source, directory)
```
Source records kept in a separate namespace from upload store entries.
## `class AsyncFileSources`
```python theme={null}
class contree_sdk.file_sources.AsyncFileSources(store, scope, *, clock)
```
Source registry backed by records with implementation-defined retention in a caller-owned store.
Upload invalidation does not remove source records. A source is provenance,
not proof that the remote upload still exists or that the local file is unchanged.
## `class FileSource`
```python theme={null}
class contree_sdk.file_sources.FileSource(file_uuid, sha256, source, kind, recorded_at)
```
## `class SyncFileSources`
```python theme={null}
class contree_sdk.file_sources.SyncFileSources(store, scope, *, clock)
```
Source registry backed by records with implementation-defined retention in a caller-owned store.
Upload invalidation does not remove source records. A source is provenance,
not proof that the remote upload still exists or that the local file is unchanged.
Bind cache namespaces to a server and an authorization context.
## `class StoreScope`
```python theme={null}
class contree_sdk.scope.StoreScope(digest)
```
A non-secret digest separating endpoint, project, credential, and profile.
### Methods
#### `from_client()`
```python theme={null}
@classmethod
def from_client(client, *, profile) -> StoreScope
```
Derive a scope without storing credentials in cache keys or records.
**client** *required*
**profile** (default: '')
**returns** `StoreScope`
[`StoreScope`](./cache#contree_sdk.scope.StoreScope)
A scope that changes when endpoint, project, credential, or profile changes.
# Dockerfile builders
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/docker
See [Build a Docker image](../building-images) for setup, supported instructions, and differences
from Docker. See [Advanced usage](../advanced) for callbacks, cache lifetimes, and manual assembly. See [Customize the SDK](../customization) for parser and factory hooks.
Dockerfile parser and keyword interpreters.
Each Dockerfile directive is a DockerKeyword subclass living in its own
module. parse\_dockerfile returns a list of directives ready to be executed
against a BuildContext/AsyncBuildContext.
## `class AddKeyword`
```python theme={null}
class contree_sdk.docker.AddKeyword(sources, dest, chown, chmod, from_stage)
```
### Attributes
**NAME** `ClassVar[str]`
**chmod** `str`
**chown** `str`
**dest** `str`
**from\_stage** `str`
**sources** `tuple[str, ...]`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> AddKeyword
```
**args\_text** *required*
**returns** `AddKeyword`
[`AddKeyword`](./docker#contree_sdk.docker.AddKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class ArgKeyword`
```python theme={null}
class contree_sdk.docker.ArgKeyword(name, default)
```
### Attributes
**NAME** `ClassVar[str]`
**default** `str | None`
**name** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> ArgKeyword
```
**args\_text** *required*
**returns** `ArgKeyword`
[`ArgKeyword`](./docker#contree_sdk.docker.ArgKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class AsyncBuildContext`
```python theme={null}
class contree_sdk.docker.AsyncBuildContext(client, store, local, http_fetch_async, session_factory, directive_executor, session_id, session, build_args, declared_args, arg_defaults, env, workdir, user, parent_hash, stages, stage_images, current_stage_alias, pending, no_cache, timeout, last_cache_hit, on_event, progress, upload_cache_ttl, upload_concurrency)
```
### Attributes
**current\_stage\_alias** `str`
**directive\_executor** `Callable[[DockerKeyword, AsyncBuildContext], Awaitable[None]] | None`
Callable\[\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword), [`AsyncBuildContext`](./docker#contree_sdk.docker.AsyncBuildContext)], Awaitable\[None]] | None
**file\_sources** `AsyncFileSources`
[`AsyncFileSources`](./cache#contree_sdk.file_sources.AsyncFileSources)
**last\_cache\_hit** `bool`
**last\_image** `str`
**no\_cache** `bool`
**on\_event** `Callable[[BuildEvent], object] | None`
Callable\[\[[`BuildEvent`](./docker#contree_sdk.docker.BuildEvent)], object] | None
**parent\_hash** `str`
**session** `ContreeAsyncSession | None`
[`ContreeAsyncSession`](./session#contree_sdk.session.ContreeAsyncSession) | None
**session\_factory**
alias of [`ContreeAsyncSession`](./session#contree_sdk.session.ContreeAsyncSession)
**session\_id** `str`
**timeout** `int`
**upload\_cache\_ttl** `float`
**upload\_concurrency** `int`
**user** `str`
**workdir** `str`
**client** `ContreeAsyncClient`
**store** `AsyncStore`
[`AsyncStore`](./store#contree_sdk.store.AsyncStore)
**local** `LocalContext`
[`LocalContext`](./docker#contree_sdk.docker.LocalContext)
**build\_args** `dict[str, str]`
**declared\_args** `set[str]`
**arg\_defaults** `dict[str, str]`
**env** `dict[str, str]`
**stages** `dict[str, str]`
**stage\_images** `list[str]`
**pending** `list[PendingFile]`
list\[[`PendingFile`](./docker#contree_sdk.docker.PendingFile)]
**progress** `BuildProgress`
### Methods
#### `arg_values()`
```python theme={null}
def arg_values() -> dict[str, str]
```
**returns** `dict[str, str]`
#### `cache_namespace()`
```python theme={null}
def cache_namespace(namespace) -> str
```
**namespace** *required*
**returns** `str`
#### `chain()`
```python theme={null}
def chain(contribution) -> str
```
**contribution** *required*
**returns** `str`
#### `commit_layer()`
```python theme={null}
async def commit_layer(branch_name, image_uuid, *, kind, title, operation_uuid) -> None
```
**branch\_name** *required*
**image\_uuid** *required*
**kind** *required*
**title** *required*
**operation\_uuid** (default: '')
**returns** `None`
#### `create_session()`
```python theme={null}
def create_session(client, *, session_id, store, image, node_id) -> ContreeAsyncSession
```
Return a session from the configured factory.
**client** *required*
**session\_id** *required*
**store** *required*
**image** *required*
**node\_id** (default: None)
**returns** `ContreeAsyncSession`
[`ContreeAsyncSession`](./session#contree_sdk.session.ContreeAsyncSession)
The configured session implementation.
#### `emit_event()`
```python theme={null}
async def emit_event(event_type, *, data, error) -> None
```
Deliver one notification through the configured build callback.
**event\_type** *required*
**data** (default: b'')
**error** (default: None)
**returns** `None`
#### `execute_directive()`
```python theme={null}
async def execute_directive(directive) -> None
```
Run a nested directive through the builder’s policy when configured.
**directive** *required*
**returns** `None`
#### `http_fetch_async()`
```python theme={null}
async def http_fetch_async(method, headers) -> tuple[int, Iterable[tuple[str, str]], AsyncIterable[bytes]]
```
**method** *required*
**headers** *required*
**returns** `tuple[int, Iterable[tuple[str, str]], AsyncIterable[bytes]]`
#### `pending_files_payload()`
```python theme={null}
def pending_files_payload() -> dict[str, str | Path | bytes | UploadFileSpec]
```
**returns** `dict[str, str | Path | bytes | UploadFileSpec]`
dict\[str, str | Path | bytes | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)]
#### `pending_repr()`
```python theme={null}
def pending_repr() -> str
```
**returns** `str`
#### `run_operation()`
```python theme={null}
async def run_operation(request, *, branch) -> InstanceResult
```
Stream and commit one RUN operation through the session’s public lifecycle.
**request** *required*
**branch** *required*
**returns** `InstanceResult`
The terminal process result, including nonzero exits.
**raises**
[**DockerBuildError**](./exceptions#contree_sdk.exceptions.DockerBuildError) – No FROM session is active.
#### `state_repr()`
```python theme={null}
def state_repr() -> str
```
**returns** `str`
#### `substitute()`
```python theme={null}
def substitute(text) -> str
```
**text** *required*
**returns** `str`
#### `try_cache_hit()`
```python theme={null}
async def try_cache_hit(branch_name, *, kind) -> str | None
```
**branch\_name** *required*
**kind** (default: 'run')
**returns** `str | None`
## `class BuildContext`
```python theme={null}
class contree_sdk.docker.BuildContext(client, store, local, http_fetch, session_factory, directive_executor, session_id, session, build_args, declared_args, arg_defaults, env, workdir, user, parent_hash, stages, stage_images, current_stage_alias, pending, no_cache, timeout, last_cache_hit, on_event, progress, upload_cache_ttl, upload_concurrency)
```
### Attributes
**current\_stage\_alias** `str`
**directive\_executor** `Callable[[DockerKeyword, BuildContext], None] | None`
Callable\[\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword), [`BuildContext`](./docker#contree_sdk.docker.BuildContext)], None] | None
**file\_sources** `SyncFileSources`
[`SyncFileSources`](./cache#contree_sdk.file_sources.SyncFileSources)
**last\_cache\_hit** `bool`
**last\_image** `str`
**no\_cache** `bool`
**on\_event** `Callable[[BuildEvent], None] | None`
Callable\[\[[`BuildEvent`](./docker#contree_sdk.docker.BuildEvent)], None] | None
**parent\_hash** `str`
**session** `ContreeSession | None`
[`ContreeSession`](./session#contree_sdk.session.ContreeSession) | None
**session\_factory**
alias of [`ContreeSession`](./session#contree_sdk.session.ContreeSession)
**session\_id** `str`
**timeout** `int`
**upload\_cache\_ttl** `float`
**upload\_concurrency** `int`
**user** `str`
**workdir** `str`
**client** `ContreeSyncClient`
**store** `SyncStore`
[`SyncStore`](./store#contree_sdk.store.SyncStore)
**local** `LocalContext`
[`LocalContext`](./docker#contree_sdk.docker.LocalContext)
**build\_args** `dict[str, str]`
**declared\_args** `set[str]`
**arg\_defaults** `dict[str, str]`
**env** `dict[str, str]`
**stages** `dict[str, str]`
**stage\_images** `list[str]`
**pending** `list[PendingFile]`
list\[[`PendingFile`](./docker#contree_sdk.docker.PendingFile)]
**progress** `BuildProgress`
### Methods
#### `arg_values()`
```python theme={null}
def arg_values() -> dict[str, str]
```
**returns** `dict[str, str]`
#### `cache_namespace()`
```python theme={null}
def cache_namespace(namespace) -> str
```
**namespace** *required*
**returns** `str`
#### `chain()`
```python theme={null}
def chain(contribution) -> str
```
**contribution** *required*
**returns** `str`
#### `commit_layer()`
```python theme={null}
def commit_layer(branch_name, image_uuid, *, kind, title, operation_uuid) -> None
```
**branch\_name** *required*
**image\_uuid** *required*
**kind** *required*
**title** *required*
**operation\_uuid** (default: '')
**returns** `None`
#### `create_session()`
```python theme={null}
def create_session(client, *, session_id, store, image, node_id) -> ContreeSession
```
Return a session from the configured factory.
**client** *required*
**session\_id** *required*
**store** *required*
**image** *required*
**node\_id** (default: None)
**returns** `ContreeSession`
[`ContreeSession`](./session#contree_sdk.session.ContreeSession)
The configured session implementation.
#### `emit_event()`
```python theme={null}
def emit_event(event_type, *, data, error) -> None
```
Deliver one notification through the configured build callback.
**event\_type** *required*
**data** (default: b'')
**error** (default: None)
**returns** `None`
#### `execute_directive()`
```python theme={null}
def execute_directive(directive) -> None
```
Run a nested directive through the builder’s policy when configured.
**directive** *required*
**returns** `None`
#### `http_fetch()`
```python theme={null}
def http_fetch(method, headers) -> tuple[int, Iterable[tuple[str, str]], Iterable[bytes]]
```
**method** *required*
**headers** *required*
**returns** `tuple[int, Iterable[tuple[str, str]], Iterable[bytes]]`
#### `pending_files_payload()`
```python theme={null}
def pending_files_payload() -> dict[str, str | Path | bytes | UploadFileSpec]
```
**returns** `dict[str, str | Path | bytes | UploadFileSpec]`
dict\[str, str | Path | bytes | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)]
#### `pending_repr()`
```python theme={null}
def pending_repr() -> str
```
**returns** `str`
#### `run_operation()`
```python theme={null}
def run_operation(request, *, branch) -> InstanceResult
```
Stream and commit one RUN operation through the session’s public lifecycle.
**request** *required*
**branch** *required*
**returns** `InstanceResult`
The terminal process result, including nonzero exits.
**raises**
[**DockerBuildError**](./exceptions#contree_sdk.exceptions.DockerBuildError) – No FROM session is active.
#### `state_repr()`
```python theme={null}
def state_repr() -> str
```
**returns** `str`
#### `substitute()`
```python theme={null}
def substitute(text) -> str
```
**text** *required*
**returns** `str`
#### `try_cache_hit()`
```python theme={null}
def try_cache_hit(branch_name, *, kind) -> str | None
```
**branch\_name** *required*
**kind** (default: 'run')
**returns** `str | None`
## `class BuildEvent`
```python theme={null}
class contree_sdk.docker.BuildEvent(*, type, step, operation_uuid, image_before, image_after, duration, data, result, error)
```
A build notification with raw output bytes and the current operation identity.
result is available after the operation finishes, including nonzero exits.
Errors retain their original exception object. Output is never decoded or formatted.
### Attributes
**data** `bytes`
**duration** `float`
**error** `BaseException | None`
**image\_after** `str | None`
**image\_before** `str | None`
**operation\_uuid** `str | None`
**result** `InstanceResult | None`
**type** `Literal['step_started', 'operation_started', 'stdout', 'stderr', 'cache_hit', 'step_completed', 'step_failed']`
**step** `BuildStep`
[`BuildStep`](./docker#contree_sdk.docker.BuildStep)
## `class BuildRequest`
```python theme={null}
class contree_sdk.docker.BuildRequest(*, context_dir, dockerfile_path, session_id, build_args, no_cache, timeout)
```
Resolved local inputs and options for one build context.
### Attributes
**no\_cache** `bool`
**timeout** `int`
**context\_dir** `Path`
**dockerfile\_path** `Path`
**session\_id** `str`
**build\_args** `dict[str, str]`
## `class BuildStep`
```python theme={null}
class contree_sdk.docker.BuildStep(id, keyword, index, parent_id)
```
One directive execution; IDs start at zero within each build.
index is the parsed Dockerfile position, or None for a synthetic step.
parent\_id identifies the enclosing directive for nested execution.
### Attributes
**index** `int | None`
**parent\_id** `int | None`
**id** `int`
**keyword** `str`
## `class BuildStepEvent`
```python theme={null}
class contree_sdk.docker.BuildStepEvent(index, keyword, cache_hit, image_before, image_after, duration, error)
```
Reported to on\_step around each directive’s execute()/execute\_async() call.
### Attributes
**error** `BaseException | None`
**index** `int`
**keyword** `str`
**cache\_hit** `bool`
**image\_before** `str | None`
**image\_after** `str | None`
**duration** `float`
## `class ContreeAsyncDockerBuilder`
```python theme={null}
class contree_sdk.docker.ContreeAsyncDockerBuilder(client, *, store, http_fetch_async, parser, session_factory)
```
Build a Dockerfile from context.
Applies each directive against a content-addressed layer cache keyed by
the build’s session.
### Attributes
**context\_class**
alias of [`AsyncBuildContext`](#contree_sdk.docker.AsyncBuildContext)
**session** `ContreeAsyncSession | None`
[`ContreeAsyncSession`](./session#contree_sdk.session.ContreeAsyncSession) | None
### Methods
#### `build()`
```python theme={null}
async def build(context, *, dockerfile, tag, build_args, no_cache, timeout, session_id, on_event, on_step) -> str
```
**context** *required*
**dockerfile** (default: None)
**tag** (default: None)
**build\_args** (default: None)
**no\_cache** (default: False)
**timeout** (default: 600)
**session\_id** (default: None)
**on\_event** (default: None)
**on\_step** (default: None)
**returns** `str`
#### `create_context()`
```python theme={null}
async def create_context(request) -> AsyncBuildContext
```
Construct per-build state using the public context and session factories.
**request** *required*
**returns** `AsyncBuildContext`
[`AsyncBuildContext`](./docker#contree_sdk.docker.AsyncBuildContext)
A context owned by this build invocation.
#### `execute_directive()`
```python theme={null}
async def execute_directive(directive, context) -> None
```
Execute one directive. Override for policy checks or instrumentation.
**directive** *required*
**context** *required*
**returns** `None`
#### `finalize()`
```python theme={null}
async def finalize(context) -> None
```
Commit pending file attachments through the same directive execution hook.
**context** *required*
**returns** `None`
#### `parse()`
```python theme={null}
def parse(text) -> list[DockerKeyword]
```
Return build directives through the configured parser.
**text** *required*
**returns** `list[DockerKeyword]`
list\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)]
The parsed directives in source order.
#### `run_step()`
```python theme={null}
async def run_step(directive, context, *, index) -> None
```
Report one directive execution, including nested and synthetic steps.
**directive** *required*
**context** *required*
**index** (default: None)
**returns** `None`
## `class ContreeDockerBuilder`
```python theme={null}
class contree_sdk.docker.ContreeDockerBuilder(client, *, store, http_fetch, parser, session_factory)
```
Build a Dockerfile from context.
Applies each directive against a content-addressed layer cache keyed by
the build’s session.
### Attributes
**context\_class**
alias of [`BuildContext`](#contree_sdk.docker.BuildContext)
**session** `ContreeSession | None`
[`ContreeSession`](./session#contree_sdk.session.ContreeSession) | None
### Methods
#### `build()`
```python theme={null}
def build(context, *, dockerfile, tag, build_args, no_cache, timeout, session_id, on_event, on_step) -> str
```
**context** *required*
**dockerfile** (default: None)
**tag** (default: None)
**build\_args** (default: None)
**no\_cache** (default: False)
**timeout** (default: 600)
**session\_id** (default: None)
**on\_event** (default: None)
**on\_step** (default: None)
**returns** `str`
#### `create_context()`
```python theme={null}
def create_context(request) -> BuildContext
```
Construct per-build state using the public context and session factories.
**request** *required*
**returns** `BuildContext`
[`BuildContext`](./docker#contree_sdk.docker.BuildContext)
A context owned by this build invocation.
#### `execute_directive()`
```python theme={null}
def execute_directive(directive, context) -> None
```
Execute one directive. Override for policy checks or instrumentation.
**directive** *required*
**context** *required*
**returns** `None`
#### `finalize()`
```python theme={null}
def finalize(context) -> None
```
Commit pending file attachments through the same directive execution hook.
**context** *required*
**returns** `None`
#### `parse()`
```python theme={null}
def parse(text) -> list[DockerKeyword]
```
Return build directives through the configured parser.
**text** *required*
**returns** `list[DockerKeyword]`
list\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)]
The parsed directives in source order.
#### `run_step()`
```python theme={null}
def run_step(directive, context, *, index) -> None
```
Report one directive execution, including nested and synthetic steps.
**directive** *required*
**context** *required*
**index** (default: None)
**returns** `None`
## `class CopyKeyword`
```python theme={null}
class contree_sdk.docker.CopyKeyword(sources, dest, chown, chmod, from_stage)
```
### Attributes
**NAME** `ClassVar[str]`
**chmod** `str`
**chown** `str`
**dest** `str`
**from\_stage** `str`
**sources** `tuple[str, ...]`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> CopyKeyword
```
**args\_text** *required*
**returns** `CopyKeyword`
[`CopyKeyword`](./docker#contree_sdk.docker.CopyKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class DockerKeyword`
```python theme={null}
class contree_sdk.docker.DockerKeyword()
```
Base class. Subclasses implement parse, serialize, execute.
### Attributes
**NAME** `ClassVar[str]`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> DockerKeyword
```
**args\_text** *required*
**returns** `DockerKeyword`
[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class DockerfileParser`
```python theme={null}
class contree_sdk.docker.DockerfileParser(*, keywords, skipped)
```
A per-instance directive registry. Subclass or register custom DockerKeyword classes.
### Methods
#### `parse()`
```python theme={null}
def parse(text) -> list[DockerKeyword]
```
Return directives using this parser’s registry.
**text** *required*
**returns** `list[DockerKeyword]`
list\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)]
The parsed directives in source order.
**raises**
**ValueError** – A directive is unknown or has invalid arguments.
#### `register()`
```python theme={null}
def register(keyword) -> None
```
**keyword** *required*
**returns** `None`
## `class DockerignoreRule`
```python theme={null}
class contree_sdk.docker.DockerignoreRule(negate, regex, raw)
```
One compiled .dockerignore line.
### Attributes
**negate** `bool`
**regex** `Pattern[str]`
**raw** `str`
## `class EnvKeyword`
```python theme={null}
class contree_sdk.docker.EnvKeyword(pairs)
```
### Attributes
**NAME** `ClassVar[str]`
**pairs** `tuple[tuple[str, str], ...]`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> EnvKeyword
```
**args\_text** *required*
**returns** `EnvKeyword`
[`EnvKeyword`](./docker#contree_sdk.docker.EnvKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class FromKeyword`
```python theme={null}
class contree_sdk.docker.FromKeyword(image_ref, alias)
```
### Attributes
**NAME** `ClassVar[str]`
**alias** `str`
**image\_ref** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> FromKeyword
```
**args\_text** *required*
**returns** `FromKeyword`
[`FromKeyword`](./docker#contree_sdk.docker.FromKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class LocalContext`
```python theme={null}
class contree_sdk.docker.LocalContext(root, dockerignore)
```
Read-only handle for the local build context directory.
### Attributes
**root** `Path`
**dockerignore** `tuple[DockerignoreRule, ...]`
tuple\[[`DockerignoreRule`](./docker#contree_sdk.docker.DockerignoreRule), ...]
### Methods
#### `collect()`
```python theme={null}
def collect(sources, dest, *, uid, gid, mode_override) -> list[MappedFile]
```
**sources** *required*
**dest** *required*
**uid** *required*
**gid** *required*
**mode\_override** *required*
**returns** `list[MappedFile]`
#### `from_dir()`
```python theme={null}
@classmethod
def from_dir(root) -> LocalContext
```
**root** *required*
**returns** `LocalContext`
[`LocalContext`](./docker#contree_sdk.docker.LocalContext)
#### `is_ignored()`
```python theme={null}
def is_ignored(rel_path) -> bool
```
**rel\_path** *required*
**returns** `bool`
#### `walk()`
```python theme={null}
def walk(host_path, dest, sources, uid, gid, mode_override) -> list[MappedFile]
```
**host\_path** *required*
**dest** *required*
**sources** *required*
**uid** *required*
**gid** *required*
**mode\_override** *required*
**returns** `list[MappedFile]`
#### `walk_dir()`
```python theme={null}
def walk_dir(host_path, dest, uid, gid, mode_override) -> list[MappedFile]
```
**host\_path** *required*
**dest** *required*
**uid** *required*
**gid** *required*
**mode\_override** *required*
**returns** `list[MappedFile]`
#### `walk_file()`
```python theme={null}
def walk_file(host_path, dest, sources, uid, gid, mode_override) -> list[MappedFile]
```
**host\_path** *required*
**dest** *required*
**sources** *required*
**uid** *required*
**gid** *required*
**mode\_override** *required*
**returns** `list[MappedFile]`
## `class PendingFile`
```python theme={null}
class contree_sdk.docker.PendingFile(instance_path, file_uuid, sha256, uid, gid, mode)
```
### Attributes
**instance\_path** `str`
**file\_uuid** `str`
**sha256** `str`
**uid** `int`
**gid** `int`
**mode** `str`
## `class RunKeyword`
```python theme={null}
class contree_sdk.docker.RunKeyword(parts, shell_form)
```
### Attributes
**NAME** `ClassVar[str]`
**shell\_form** `bool`
**parts** `tuple[str, ...]`
### Methods
#### `build_request()`
```python theme={null}
def build_request(ctx) -> RunRequest
```
Prepare the command for the context’s operation execution hook.
**ctx** *required*
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
A non-disposable request with the current build state and attachments.
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> RunKeyword
```
**args\_text** *required*
**returns** `RunKeyword`
[`RunKeyword`](./docker#contree_sdk.docker.RunKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class SkippedKeyword`
```python theme={null}
class contree_sdk.docker.SkippedKeyword(name, raw)
```
### Attributes
**NAME** `ClassVar[str]`
**name** `str`
**raw** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `of()`
```python theme={null}
@classmethod
def of(name, raw) -> SkippedKeyword
```
**name** *required*
**raw** *required*
**returns** `SkippedKeyword`
[`SkippedKeyword`](./docker#contree_sdk.docker.SkippedKeyword)
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> DockerKeyword
```
**args\_text** *required*
**returns** `DockerKeyword`
[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class UserKeyword`
```python theme={null}
class contree_sdk.docker.UserKeyword(spec)
```
### Attributes
**NAME** `ClassVar[str]`
**spec** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> UserKeyword
```
**args\_text** *required*
**returns** `UserKeyword`
[`UserKeyword`](./docker#contree_sdk.docker.UserKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `class WorkdirKeyword`
```python theme={null}
class contree_sdk.docker.WorkdirKeyword(path)
```
### Attributes
**NAME** `ClassVar[str]`
**path** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `execute_async()`
```python theme={null}
async def execute_async(ctx) -> None
```
**ctx** *required*
**returns** `None`
#### `parse()`
```python theme={null}
@classmethod
def parse(args_text) -> WorkdirKeyword
```
**args\_text** *required*
**returns** `WorkdirKeyword`
[`WorkdirKeyword`](./docker#contree_sdk.docker.WorkdirKeyword)
#### `serialize()`
```python theme={null}
def serialize() -> str
```
Stable text used for layer hashing.
**returns** `str`
## `is_ignored()`
```python theme={null}
def contree_sdk.docker.is_ignored(rel_path, rules) -> bool
```
**rel\_path** *required*
**rules** *required*
**returns** `bool`
## `parse_dockerfile()`
```python theme={null}
def contree_sdk.docker.parse_dockerfile(text) -> list[DockerKeyword]
```
**text** *required*
**returns** `list[DockerKeyword]`
list\[[`DockerKeyword`](./docker#contree_sdk.docker.DockerKeyword)]
## `parse_dockerignore()`
```python theme={null}
def contree_sdk.docker.parse_dockerignore(context_dir) -> tuple[DockerignoreRule, ...]
```
**context\_dir** *required*
**returns** `tuple[DockerignoreRule, ...]`
tuple\[[`DockerignoreRule`](./docker#contree_sdk.docker.DockerignoreRule), ...]
## `substitute()`
```python theme={null}
def contree_sdk.docker.substitute(text, env) -> str
```
**text** *required*
**env** *required*
**returns** `str`
# SDK exceptions
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/exceptions
See [Handle failures and unexpected state](../troubleshooting) for recovery scenarios. Client API errors, transport
errors, `InterruptedError`, and validation errors can also propagate. A nonzero
process exit code is returned in `InstanceResult` by command execution.
`write_file()` raises `FileWriteError` if its write command does not confirm success.
## `exception FailedOperationError`
```python theme={null}
exception contree_sdk.exceptions.FailedOperationError(operation_uuid, error)
```
An operation reached a terminal non-SUCCESS status with no result at all.
A nonzero exit code is a normal InstanceResult, not an error - this is
only raised for an operation-level failure (e.g. the VM couldn’t start).
### Attributes
**args**
### Methods
#### `add_note()`
```python theme={null}
def add_note(note, /)
```
Add a note to the exception
#### `with_traceback()`
```python theme={null}
def with_traceback(tb, /)
```
Set self.**traceback** to tb and return self.
## `exception DockerBuildError`
```python theme={null}
exception contree_sdk.exceptions.DockerBuildError()
```
A Dockerfile build step failed (nonzero RUN exit code, unresolvable stage/image reference, etc.).
### Attributes
**args**
### Methods
#### `add_note()`
```python theme={null}
def add_note(note, /)
```
Add a note to the exception
#### `with_traceback()`
```python theme={null}
def with_traceback(tb, /)
```
Set self.**traceback** to tb and return self.
## `exception FileWriteError`
```python theme={null}
exception contree_sdk.exceptions.FileWriteError(path, message)
```
A file could not be written to the executor’s filesystem.
### Attributes
**args**
### Methods
#### `add_note()`
```python theme={null}
def add_note(note, /)
```
Add a note to the exception
#### `with_traceback()`
```python theme={null}
def with_traceback(tb, /)
```
Set self.**traceback** to tb and return self.
# Execution contracts
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/execution
See [Customize the SDK](../customization) for hook ordering, ownership, and implementation obligations.
`RunRequest` describes one command. Executor contracts let adapters use a custom backend.
Public command values and execution contracts for integrations.
## `class RunRequest`
```python theme={null}
class contree_sdk.execution.RunRequest(*, command, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking)
```
Command configuration passed through the session’s public extension hooks.
Use `dataclasses.replace` to change a request. Arguments and environment
are copied at construction. File sources and stdin remain caller-owned.
Exactly one of `command` and `shell` must be supplied. Results are saved
by default; use `disposable=True` to leave session history unchanged.
### Attributes
**command** `str | None`
**shell** `str | None`
**args** `tuple[str, ...]`
**env** `Mapping[str, str] | None`
**cwd** `str | None`
**stdin** `str | bytes | Path | Readable[str] | Readable[bytes] | AsyncReadable[str] | AsyncReadable[bytes] | None`
str | bytes | Path | [`Readable`](./files#contree_sdk.files.Readable)\[str] | [`Readable`](./files#contree_sdk.files.Readable)\[bytes] | [`AsyncReadable`](./files#contree_sdk.files.AsyncReadable)\[str] | [`AsyncReadable`](./files#contree_sdk.files.AsyncReadable)\[bytes] | None
**stdin\_open** `bool`
**files** `list[str | Path | UploadFileSpec] | dict[str, str | Path | bytes | UploadFileSpec] | None`
list\[str | Path | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)] | dict\[str, str | Path | bytes | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)] | None
**timeout** `float | timedelta | None`
**disposable** `bool`
**truncate\_output\_at** `int | None`
**preserve\_env** `bool`
**hostname** `str | None`
**uid** `int | None`
**gid** `int | None`
**resources\_limits** `InstanceResourcesLimits | None`
**networking** `InstanceNetworking | None`
**title** `str`
**timeout\_seconds** `float | None`
## `class OperationContext`
```python theme={null}
class contree_sdk.execution.OperationContext(request, session_id, image_uuid, parent_id, branch, files, attachments, detached, node_id, created_at, position_version, session_cwd, session_env)
```
The effective request and history position captured before remote execution.
### Attributes
**request** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
**session\_id** `str`
**image\_uuid** `str`
**parent\_id** `str | None`
**branch** `str | None`
**files** `tuple[str, ...]`
**attachments** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
**detached** `bool`
**node\_id** `str`
**created\_at** `float`
**position\_version** `int`
**session\_cwd** `str | None`
**session\_env** `Mapping[str, str]`
## `class SyncExecutor`
```python theme={null}
class contree_sdk.execution.SyncExecutor()
```
Execution and file access required by synchronous framework adapters.
Implementations own their lifecycle. Adapters do not close executors.
Successful execution returns the client’s InstanceResult, including nonzero
exit codes. read\_file returns exact bytes or raises a client API exception.
### Attributes
**session\_id** `str`
### Methods
#### `execute()`
```python theme={null}
@abstractmethod
def execute(request) -> InstanceResult
```
**request** *required*
**returns** `InstanceResult`
#### `read_file()`
```python theme={null}
@abstractmethod
def read_file(path) -> bytes
```
**path** *required*
**returns** `bytes`
#### `write_file()`
```python theme={null}
def write_file(path, content) -> None
```
Write bytes to an absolute path, creating its parent directories.
Returns after the write is applied to the executor’s filesystem. It does
not merely stage a file or upload a blob. Persistence follows execute().
The default runs mkdir and cat through execute() with binary stdin.
Override this method to use another file-transfer mechanism. An override
must coordinate with the executor’s commands and snapshot lifecycle.
Invalid paths raise ValueError; a failed write raises FileWriteError.
Transport errors, timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
## `class AsyncExecutor`
```python theme={null}
class contree_sdk.execution.AsyncExecutor()
```
Native asynchronous execution and file access for framework adapters.
### Attributes
**session\_id** `str`
### Methods
#### `execute()`
```python theme={null}
def execute(request) -> InstanceResult
```
**request** *required*
**returns** `InstanceResult`
#### `read_file()`
```python theme={null}
def read_file(path) -> bytes
```
**path** *required*
**returns** `bytes`
#### `write_file()`
```python theme={null}
async def write_file(path, content) -> None
```
Write bytes with the same contract as SyncExecutor.write\_file.
The default awaits execute() with binary stdin. Override with native
async file transfer, coordinating with commands and snapshot lifecycle.
Returns after application, not after staging or blob upload. Invalid paths
raise ValueError; a failed write raises FileWriteError. Transport errors,
timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
Public lifecycle contracts for operation and subprocess implementations.
## `class SubprocessContract`
```python theme={null}
class contree_sdk.session.contracts.SubprocessContract()
```
Waitable event stream for one subprocess. Iteration and wait share completion state.
### Attributes
**spid** `int`
### Methods
#### `wait()`
```python theme={null}
@abstractmethod
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
#### `pipe_to()`
```python theme={null}
@abstractmethod
def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
## `class AsyncSubprocessContract`
```python theme={null}
class contree_sdk.session.contracts.AsyncSubprocessContract()
```
Waitable event stream for one subprocess. Iteration and wait share completion state.
### Attributes
**spid** `int`
### Methods
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
#### `pipe_to()`
```python theme={null}
def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
## `class OperationContract`
```python theme={null}
class contree_sdk.session.contracts.OperationContract()
```
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `apply_files()`
```python theme={null}
@abstractmethod
def apply_files(files) -> None
```
**files** *required*
**returns** `None`
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `events()`
```python theme={null}
@abstractmethod
def events(*, since, spid, timeout) -> Iterator[OperationEvent]
```
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `Iterator[OperationEvent]`
#### `status()`
```python theme={null}
@abstractmethod
def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `send_stdin()`
```python theme={null}
@abstractmethod
def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `pipe_stdin()`
```python theme={null}
@abstractmethod
def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
#### `signal()`
```python theme={null}
@abstractmethod
def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `cancel()`
```python theme={null}
@abstractmethod
def cancel() -> None
```
**returns** `None`
#### `wait()`
```python theme={null}
@abstractmethod
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
#### `run()`
```python theme={null}
@abstractmethod
def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> SubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
#### `shutdown()`
```python theme={null}
@abstractmethod
def shutdown() -> None
```
**returns** `None`
## `class AsyncOperationContract`
```python theme={null}
class contree_sdk.session.contracts.AsyncOperationContract()
```
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `apply_files()`
```python theme={null}
def apply_files(files) -> None
```
**files** *required*
**returns** `None`
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `events()`
```python theme={null}
@abstractmethod
def events(*, since, spid, timeout) -> AsyncIterator[OperationEvent]
```
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `AsyncIterator[OperationEvent]`
#### `status()`
```python theme={null}
def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `send_stdin()`
```python theme={null}
def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `pipe_stdin()`
```python theme={null}
def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
#### `signal()`
```python theme={null}
def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `cancel()`
```python theme={null}
def cancel() -> None
```
**returns** `None`
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
#### `run()`
```python theme={null}
def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> AsyncSubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
#### `shutdown()`
```python theme={null}
def shutdown() -> None
```
**returns** `None`
# File transfer
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/files
See [Work with sandbox files](../files) for upload and download scenarios, and [Customize the SDK](../customization)
for transfer implementations. Import file types from `contree_sdk.files`.
Public file-transfer contracts and client-backed implementations.
## `class AsyncClientFileTransfer`
```python theme={null}
class contree_sdk.files.AsyncClientFileTransfer(client, *, max_concurrency, on_progress)
```
File transfer using a caller-owned asynchronous contree-client.
### Attributes
**max\_concurrency**
**on\_progress** `Callable[[TransferProgress], None] | None`
Callable\[\[[`TransferProgress`](./files#contree_sdk.files.TransferProgress)], None] | None
### Methods
#### `upload()`
```python theme={null}
async def upload(file) -> FileSpec
```
**file** *required*
**returns** `FileSpec`
#### `read_file()`
```python theme={null}
async def read_file(image_uuid, path) -> bytes
```
**image\_uuid** *required*
**path** *required*
**returns** `bytes`
#### `iter_file()`
```python theme={null}
async def iter_file(image_uuid, path) -> AsyncGenerator[bytes, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `AsyncGenerator[bytes, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
#### `download_file()`
```python theme={null}
async def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `prepare_files()`
```python theme={null}
async def prepare_files(files) -> dict[str, FileSpec] | None
```
**files** *required*
**returns** `dict[str, FileSpec] | None`
#### `read_stdin()`
```python theme={null}
async def read_stdin(source) -> str | bytes
```
**source** *required*
**returns** `str | bytes`
## `class AsyncFileTransfer`
```python theme={null}
class contree_sdk.files.AsyncFileTransfer()
```
Native async counterpart of SyncFileTransfer.
prepare\_files limits uploads to max\_concurrency workers. It cancels and
joins sibling uploads when one fails. Custom backends can replace batching.
### Attributes
**max\_concurrency**
**on\_progress** `Callable[[TransferProgress], None] | None`
Callable\[\[[`TransferProgress`](./files#contree_sdk.files.TransferProgress)], None] | None
### Methods
#### `upload()`
```python theme={null}
def upload(file) -> FileSpec
```
**file** *required*
**returns** `FileSpec`
#### `read_file()`
```python theme={null}
def read_file(image_uuid, path) -> bytes
```
**image\_uuid** *required*
**path** *required*
**returns** `bytes`
#### `prepare_files()`
```python theme={null}
async def prepare_files(files) -> dict[str, FileSpec] | None
```
**files** *required*
**returns** `dict[str, FileSpec] | None`
#### `iter_file()`
```python theme={null}
async def iter_file(image_uuid, path) -> AsyncGenerator[bytes, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `AsyncGenerator[bytes, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
#### `download_file()`
```python theme={null}
async def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `read_stdin()`
```python theme={null}
async def read_stdin(source) -> str | bytes
```
**source** *required*
**returns** `str | bytes`
## `class AsyncReadable`
```python theme={null}
class contree_sdk.files.AsyncReadable(*args, **kwargs)
```
### Methods
#### `read()`
```python theme={null}
async def read(size, /) -> TypeVar(DataT_co, str, bytes, covariant=True)
```
**size** (default: -1)
**returns** `TypeVar(DataT_co, str, bytes, covariant=True)`
## `class ClientFileTransfer`
```python theme={null}
class contree_sdk.files.ClientFileTransfer(client, *, max_concurrency, on_progress)
```
File transfer using a caller-owned synchronous contree-client.
### Attributes
**max\_concurrency**
**on\_progress** `Callable[[TransferProgress], None] | None`
Callable\[\[[`TransferProgress`](./files#contree_sdk.files.TransferProgress)], None] | None
### Methods
#### `upload()`
```python theme={null}
def upload(file) -> FileSpec
```
**file** *required*
**returns** `FileSpec`
#### `read_file()`
```python theme={null}
def read_file(image_uuid, path) -> bytes
```
**image\_uuid** *required*
**path** *required*
**returns** `bytes`
#### `iter_file()`
```python theme={null}
def iter_file(image_uuid, path) -> Generator[bytes, None, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `Generator[bytes, None, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
#### `download_file()`
```python theme={null}
def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `prepare_files()`
```python theme={null}
def prepare_files(files) -> dict[str, FileSpec] | None
```
**files** *required*
**returns** `dict[str, FileSpec] | None`
#### `read_stdin()`
```python theme={null}
def read_stdin(source) -> str | bytes
```
**source** *required*
**returns** `str | bytes`
## `class Readable`
```python theme={null}
class contree_sdk.files.Readable(*args, **kwargs)
```
### Methods
#### `read()`
```python theme={null}
def read(size, /) -> TypeVar(DataT_co, str, bytes, covariant=True)
```
**size** (default: -1)
**returns** `TypeVar(DataT_co, str, bytes, covariant=True)`
## `class StagedFile`
```python theme={null}
class contree_sdk.files.StagedFile(path, uuid, uid, gid, mode)
```
An uploaded file and its destination metadata, detached from a local source.
### Attributes
**path** `str`
**uuid** `str`
**uid** `int | None`
**gid** `int | None`
**mode** `int | None`
### Methods
#### `from_spec()`
```python theme={null}
@classmethod
def from_spec(path, spec) -> StagedFile
```
Copy a transport attachment, preserving omitted permission fields.
**path** *required*
**spec** *required*
**returns** `StagedFile`
[`StagedFile`](./files#contree_sdk.files.StagedFile)
A detached attachment with an octal mode converted to an integer.
**raises**
**ValueError** – The upload UUID is missing or the mode is not octal.
#### `as_spec()`
```python theme={null}
def as_spec() -> FileSpec
```
Create a transport attachment without reading or uploading its source.
**returns** `FileSpec`
A new FileSpec with the recorded metadata.
## `class SyncFileTransfer`
```python theme={null}
class contree_sdk.files.SyncFileTransfer()
```
Replace upload, download, or stdin handling without replacing a session.
Returned FileSpec values identify uploads on the same server as the session.
Input streams belong to the caller and must not be closed by this component.
### Attributes
**max\_concurrency**
**on\_progress** `Callable[[TransferProgress], None] | None`
Callable\[\[[`TransferProgress`](./files#contree_sdk.files.TransferProgress)], None] | None
### Methods
#### `upload()`
```python theme={null}
@abstractmethod
def upload(file) -> FileSpec
```
**file** *required*
**returns** `FileSpec`
#### `read_file()`
```python theme={null}
@abstractmethod
def read_file(image_uuid, path) -> bytes
```
**image\_uuid** *required*
**path** *required*
**returns** `bytes`
#### `prepare_files()`
```python theme={null}
def prepare_files(files) -> dict[str, FileSpec] | None
```
**files** *required*
**returns** `dict[str, FileSpec] | None`
#### `iter_file()`
```python theme={null}
def iter_file(image_uuid, path) -> Generator[bytes, None, None]
```
Yield file content. Override this buffered fallback for streaming backends.
**image\_uuid** *required*
**path** *required*
**returns** `Generator[bytes, None, None]`
**yields**
File content chunks. Close the generator if iteration stops early.
#### `download_file()`
```python theme={null}
def download_file(image_uuid, path, destination) -> int
```
Atomically save streamed content.
**image\_uuid** *required*
**path** *required*
**destination** *required*
**returns** `int`
The number of downloaded bytes.
#### `read_stdin()`
```python theme={null}
def read_stdin(source) -> str | bytes
```
**source** *required*
**returns** `str | bytes`
## `class TransferProgress`
```python theme={null}
class contree_sdk.files.TransferProgress(direction, path, bytes_transferred, total_bytes)
```
Completed upload size or cumulative downloaded bytes for one remote path.
### Attributes
**total\_bytes** `int | None`
**direction** `Literal['upload', 'download']`
Literal\['[`upload`](./files#contree_sdk.files.AsyncClientFileTransfer.upload)', 'download']
**path** `str`
**bytes\_transferred** `int`
## `class UploadFileSpec`
```python theme={null}
class contree_sdk.files.UploadFileSpec(*, uid, gid, mode, path, source)
```
### Attributes
**gid** `int`
**mode** `int`
**path** `PurePosixPath | str | None`
**uid** `int`
**source** `str | Path | bytes | UploadedFile`
str | Path | bytes | [`UploadedFile`](./files#contree_sdk.files.UploadedFile)
### Methods
#### `prepare_files()`
```python theme={null}
@classmethod
def prepare_files(files, default_image_path) -> list[UploadFileSpec]
```
**files** *required*
**default\_image\_path** (default: '/')
**returns** `list[UploadFileSpec]`
list\[[`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)]
## `class UploadedFile`
```python theme={null}
class contree_sdk.files.UploadedFile(uuid, sha256)
```
### Attributes
**uuid** `str`
**sha256** `str`
## `prepare_file_tree()`
```python theme={null}
def contree_sdk.files.prepare_file_tree(source, destination, *, exclude, uid, gid, mode) -> list[UploadFileSpec]
```
Expand directory contents into regular files in stable relative-path order.
Patterns match POSIX relative paths, or basenames when they contain no slash.
Excluded directories are pruned. Symlinks and special files raise ValueError.
Empty directories cannot be represented by spawn attachments and are omitted.
mode=None preserves permission bits; ownership defaults to uid=gid=0.
**source** *required*
**destination** (default: '/')
**exclude** (default: ())
**uid** (default: 0)
**gid** (default: 0)
**mode** (default: None)
**returns** `list[UploadFileSpec]`
list\[[`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)]
Prepared attachments in relative-path order.
**raises**
**ValueError** – The source is not a directory, or an included entry is not a regular file or directory.
## `write_download()`
```python theme={null}
def contree_sdk.files.write_download(chunks, destination, *, path, on_progress) -> int
```
Write streamed bytes atomically; preserve the destination on failure.
**chunks** *required*
**destination** *required*
**path** (default: '')
**on\_progress** (default: None)
**returns** `int`
The number of downloaded bytes.
## `write_download_async()`
```python theme={null}
async def contree_sdk.files.write_download_async(chunks, destination, *, path, on_progress) -> int
```
Write streamed bytes atomically, joining local writes before cancellation escapes.
**chunks** *required*
**destination** *required*
**path** (default: '')
**on\_progress** (default: None)
**returns** `int`
The number of downloaded bytes.
# Image helpers
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/images
See [Import a Docker image](../images) and [Build a Docker image](../building-images) for complete programs.
These helpers use the same connection sources as the sandbox factory.
A supplied client, cache, or store remains owned by the caller.
Import and build sandbox images with managed clients and persistent caches.
Each helper returns a ConTree image UUID for create\_sandbox\_session. Connection
settings follow the sandbox factory. Supplied clients and stores remain
caller-owned; helpers close only the resources they create.
## `image_cache_directory()`
```python theme={null}
def contree_sdk.images.image_cache_directory(cache_dir) -> Path
```
Select the image store directory without creating it.
**cache\_dir** (default: None)
**returns** `Path`
The explicit directory or \$XDG\_CACHE\_HOME/contree (default \~/.cache/contree).
## `sync_import_image()`
```python theme={null}
def contree_sdk.images.sync_import_image(source, *, tag, timeout, no_cache, store, cache_dir, cache_ttl, url, project, token, auth_type, profile, config_path, client, client_type, **client_kwargs) -> str
```
Import a registry image and wait for a usable filesystem image.
Registry names such as alpine:latest and docker:// URLs are accepted. Pass
ImageImportRegistry for registry credentials. Results are cached for one
hour by default. no\_cache=True imports again and refreshes the cached result.
A requested tag is reapplied on cache hits. Timeout or interruption after
submission requests cancellation of the import operation. Import failure or
a missing result image raises FailedOperationError.
**source** *required*
**tag** (default: None)
**timeout** (default: 300)
**no\_cache** (default: False)
**store** (default: None)
**cache\_dir** (default: None)
**cache\_ttl** (default: 3600)
**url** (default: None)
**project** (default: None)
**token** (default: None)
**auth\_type** (default: None)
**profile** (default: None)
**config\_path** (default: None)
**client** (default: None)
**client\_type** (default: None)
\*\***client\_kwargs**
**returns** `str`
The imported ConTree image UUID.
**raises**
**TypeError** – A supplied component uses the wrong execution mode.
**raises**
**ValueError** – The source, timeout, TTL, or connection settings are invalid.
## `async_import_image()`
```python theme={null}
async def contree_sdk.images.async_import_image(source, *, tag, timeout, no_cache, store, cache_dir, cache_ttl, url, project, token, auth_type, profile, config_path, client, client_type, **client_kwargs) -> str
```
Import a registry image and wait for a usable filesystem image.
Registry names such as alpine:latest and docker:// URLs are accepted. Pass
ImageImportRegistry for registry credentials. Results are cached for one
hour by default. no\_cache=True imports again and refreshes the cached result.
A requested tag is reapplied on cache hits. Timeout or interruption after
submission requests cancellation of the import operation. Import failure or
a missing result image raises FailedOperationError.
**source** *required*
**tag** (default: None)
**timeout** (default: 300)
**no\_cache** (default: False)
**store** (default: None)
**cache\_dir** (default: None)
**cache\_ttl** (default: 3600)
**url** (default: None)
**project** (default: None)
**token** (default: None)
**auth\_type** (default: None)
**profile** (default: None)
**config\_path** (default: None)
**client** (default: None)
**client\_type** (default: None)
\*\***client\_kwargs**
**returns** `str`
The imported ConTree image UUID.
**raises**
**TypeError** – A supplied component uses the wrong execution mode.
**raises**
**ValueError** – The source, timeout, TTL, or connection settings are invalid.
## `sync_build_image()`
```python theme={null}
def contree_sdk.images.sync_build_image(context, *, dockerfile, tag, build_args, no_cache, timeout, session_id, store, cache_dir, on_event, on_step, builder_type, builder_kwargs, url, project, token, auth_type, profile, config_path, client, client_type, **client_kwargs) -> str
```
Build a Dockerfile with persistent layer history and upload caching.
The default Dockerfile is context/Dockerfile. A SQLite store in the XDG
cache directory holds history and reusable results unless supplied explicitly.
no\_cache=True disables layer reuse; content-addressed uploads remain cached.
Use builder\_type and builder\_kwargs to extend the existing Docker builder.
The connection scope is part of the default build session identity.
Invalid inputs raise ValueError; failed build steps raise DockerBuildError.
**context** *required*
**dockerfile** (default: None)
**tag** (default: None)
**build\_args** (default: None)
**no\_cache** (default: False)
**timeout** (default: 600)
**session\_id** (default: None)
**store** (default: None)
**cache\_dir** (default: None)
**on\_event** (default: None)
**on\_step** (default: None)
**builder\_type** (default: \)
**builder\_kwargs** (default: None)
**url** (default: None)
**project** (default: None)
**token** (default: None)
**auth\_type** (default: None)
**profile** (default: None)
**config\_path** (default: None)
**client** (default: None)
**client\_type** (default: None)
\*\***client\_kwargs**
**returns** `str`
The built ConTree filesystem image UUID.
**raises**
**TypeError** – A supplied component uses the wrong execution mode.
## `async_build_image()`
```python theme={null}
async def contree_sdk.images.async_build_image(context, *, dockerfile, tag, build_args, no_cache, timeout, session_id, store, cache_dir, on_event, on_step, builder_type, builder_kwargs, url, project, token, auth_type, profile, config_path, client, client_type, **client_kwargs) -> str
```
Build a Dockerfile with persistent layer history and upload caching.
The default Dockerfile is context/Dockerfile. A SQLite store in the XDG
cache directory holds history and reusable results unless supplied explicitly.
no\_cache=True disables layer reuse; content-addressed uploads remain cached.
Use builder\_type and builder\_kwargs to extend the existing Docker builder.
The connection scope is part of the default build session identity.
Invalid inputs raise ValueError; failed build steps raise DockerBuildError.
**context** *required*
**dockerfile** (default: None)
**tag** (default: None)
**build\_args** (default: None)
**no\_cache** (default: False)
**timeout** (default: 600)
**session\_id** (default: None)
**store** (default: None)
**cache\_dir** (default: None)
**on\_event** (default: None)
**on\_step** (default: None)
**builder\_type** (default: \)
**builder\_kwargs** (default: None)
**url** (default: None)
**project** (default: None)
**token** (default: None)
**auth\_type** (default: None)
**profile** (default: None)
**config\_path** (default: None)
**client** (default: None)
**client\_type** (default: None)
\*\***client\_kwargs**
**returns** `str`
The built ConTree filesystem image UUID.
**raises**
**TypeError** – A supplied component uses the wrong execution mode.
# API reference
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/index
Use the guides for complete workflows and these pages for signatures and component
contracts. Clients, HTTP transports, authentication, and low-level image operations
belong to the separate `contree-client` package.
> [card] [Sessions and operations](./session)
> [card] [Sandbox factories](./sandbox)
> [card] [Image helpers](./images)
> [card] [File transfer](./files)
> [card] [Tree stores](./store)
> [card] [Dockerfile builders](./docker)
> [card] [Caches and upload sources](./cache)
> [card] [Execution contracts](./execution)
> [card] [deepagents sandboxes](./langchain)
> [card] [SDK exceptions](./exceptions)
# deepagents sandboxes
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/langchain
Requires Python 3.11+ and the `contree-sdk[langchain]` extra. See
[LangChain DeepAgents](../../integrations/langchain) for executable scenarios. Adapters accept the
public executor contracts; they do not require concrete session implementations.
Other inherited `BaseSandbox` tools belong to deepagents.
## `class ContreeAsyncSandbox`
```python theme={null}
class contree_sdk.langchain.ContreeAsyncSandbox(session)
```
A deepagents sandbox with native asynchronous session operations.
### Attributes
**id** `str`
### Methods
#### `adownload_files()`
```python theme={null}
async def adownload_files(paths) -> list[FileDownloadResponse]
```
**paths** *required*
**returns** `list[FileDownloadResponse]`
#### `aexecute()`
```python theme={null}
async def aexecute(command, *, timeout) -> ExecuteResponse
```
**command** *required*
**timeout** (default: None)
**returns** `ExecuteResponse`
#### `aupload_files()`
```python theme={null}
async def aupload_files(files) -> list[FileUploadResponse]
```
**files** *required*
**returns** `list[FileUploadResponse]`
#### `download_files()`
```python theme={null}
def download_files(paths) -> list[FileDownloadResponse]
```
**paths** *required*
**returns** `list[FileDownloadResponse]`
#### `download_one_file()`
```python theme={null}
async def download_one_file(path) -> FileDownloadResponse
```
**path** *required*
**returns** `FileDownloadResponse`
#### `execute()`
```python theme={null}
def execute(command, *, timeout) -> ExecuteResponse
```
**command** *required*
**timeout** (default: None)
**returns** `ExecuteResponse`
#### `upload_files()`
```python theme={null}
def upload_files(files) -> list[FileUploadResponse]
```
**files** *required*
**returns** `list[FileUploadResponse]`
## `class ContreeSandbox`
```python theme={null}
class contree_sdk.langchain.ContreeSandbox(session)
```
A deepagents adapter for any SyncExecutor implementation.
Mutating calls on this adapter are serialized. The executor remains
caller-owned. deepagents may dispatch async calls through a thread pool;
use ContreeAsyncSandbox for a native async executor.
### Attributes
**id** `str`
### Methods
#### `download_files()`
```python theme={null}
def download_files(paths) -> list[FileDownloadResponse]
```
**paths** *required*
**returns** `list[FileDownloadResponse]`
#### `download_one_file()`
```python theme={null}
def download_one_file(path) -> FileDownloadResponse
```
**path** *required*
**returns** `FileDownloadResponse`
#### `execute()`
```python theme={null}
def execute(command, *, timeout) -> ExecuteResponse
```
**command** *required*
**timeout** (default: None)
**returns** `ExecuteResponse`
#### `upload_files()`
```python theme={null}
def upload_files(files) -> list[FileUploadResponse]
```
**files** *required*
**returns** `list[FileUploadResponse]`
# Sandbox factories
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/sandbox
See [Your first sandbox](../getting-started) for complete sync/async programs and connection rules.
All three factory functions accept the configuration parameters of `session_maker`.
Connect the SDK abstractions through a simple, extensible sandbox interface.
ConTree’s stateless execution model differs from a classic stateful sandbox:
filesystem state passes between executions through images and snapshots. This
module assembles clients, sessions, stores, and policies to provide a
familiar sandbox workflow without requiring users to connect each component.
The default lazy session reuses a VM between commands. Snapshots preserve files,
but do not preserve running processes or memory. Advanced users can select or
extend session classes, supply components, and configure policies while keeping
control over execution, state, and resource ownership.
## `class SandboxConfig`
```python theme={null}
class contree_sdk.sandbox.SandboxConfig(image, url, project, token, auth_type, profile, config_path, session_type, session_id, node_id, store, cache_ttl, cwd, env, commit_policy, file_transfer, session_kwargs, client, client_type, client_kwargs)
```
### Attributes
**image** `str | None`
**url** `str | None`
**project** `str | None`
**token** `str | None`
**auth\_type** `Literal['iam', 'jwt'] | None`
**profile** `Profile | str | None`
**config\_path** `str | Path | None`
**session\_type** `type[SyncExecutor | AsyncExecutor] | None`
type\[[`SyncExecutor`](./execution#contree_sdk.execution.SyncExecutor) | [`AsyncExecutor`](./execution#contree_sdk.execution.AsyncExecutor)] | None
**session\_id** `str | None`
**node\_id** `str | None`
**store** `SyncStore | AsyncStore | None`
[`SyncStore`](./store#contree_sdk.store.SyncStore) | [`AsyncStore`](./store#contree_sdk.store.AsyncStore) | None
**cache\_ttl** `float`
**cwd** `str | None`
**env** `dict[str, str] | None`
**commit\_policy** `AbstractCommitPolicy | None`
[`AbstractCommitPolicy`](./session#contree_sdk.session.AbstractCommitPolicy) | None
**file\_transfer** `SyncFileTransfer | AsyncFileTransfer | None`
[`SyncFileTransfer`](./files#contree_sdk.files.SyncFileTransfer) | [`AsyncFileTransfer`](./files#contree_sdk.files.AsyncFileTransfer) | None
**session\_kwargs** `dict[str, Any]`
**client** `ContreeSyncClient | ContreeAsyncClient | None`
**client\_type** `type[ContreeSyncClient | ContreeAsyncClient] | None`
**client\_kwargs** `dict[str, Any]`
### Methods
#### `connection()`
```python theme={null}
def connection() -> ConnectionConfig
```
**returns** `ConnectionConfig`
#### `resolve_profile()`
```python theme={null}
def resolve_profile() -> Profile
```
**returns** `Profile`
#### `validate()`
```python theme={null}
def validate(*, asynchronous) -> None
```
**asynchronous** *required*
**returns** `None`
#### `session_arguments()`
```python theme={null}
def session_arguments(store, transfer) -> tuple[dict[str, Any], dict[str, Any]]
```
**store** *required*
**transfer** *required*
**returns** `tuple[dict[str, Any], dict[str, Any]]`
## `class SyncSandboxSessionContext`
```python theme={null}
class contree_sdk.sandbox.SyncSandboxSessionContext(config)
```
Construct a synchronous session and unwind its owned resources.
### Methods
#### `__enter__()`
```python theme={null}
def __enter__() -> TypeVar(SyncSessionT, bound= SyncExecutor)
```
**returns** `TypeVar(SyncSessionT, bound= SyncExecutor)`
TypeVar(SyncSessionT, bound= [`SyncExecutor`](./execution#contree_sdk.execution.SyncExecutor))
## `class AsyncSandboxSessionContext`
```python theme={null}
class contree_sdk.sandbox.AsyncSandboxSessionContext(config)
```
Construct a native async session and join cleanup despite cancellation.
### Methods
#### `__aenter__()`
```python theme={null}
async def __aenter__() -> TypeVar(AsyncSessionT, bound= AsyncExecutor)
```
**returns** `TypeVar(AsyncSessionT, bound= AsyncExecutor)`
TypeVar(AsyncSessionT, bound= [`AsyncExecutor`](./execution#contree_sdk.execution.AsyncExecutor))
## `class SandboxSessionContext`
```python theme={null}
class contree_sdk.sandbox.SandboxSessionContext(config)
```
Compose sync and async contexts with one shared, single-use boundary.
Construction performs no I/O. Entry chooses the context mode explicitly.
Re-entry, nesting, and switching modes on the same object are rejected.
### Methods
#### `__enter__()`
```python theme={null}
def __enter__() -> TypeVar(SyncSessionT, bound= SyncExecutor)
```
**returns** `TypeVar(SyncSessionT, bound= SyncExecutor)`
TypeVar(SyncSessionT, bound= [`SyncExecutor`](./execution#contree_sdk.execution.SyncExecutor))
#### `__aenter__()`
```python theme={null}
async def __aenter__() -> TypeVar(AsyncSessionT, bound= AsyncExecutor)
```
**returns** `TypeVar(AsyncSessionT, bound= AsyncExecutor)`
TypeVar(AsyncSessionT, bound= [`AsyncExecutor`](./execution#contree_sdk.execution.AsyncExecutor))
## `create_sandbox_session()`
```python theme={null}
def contree_sdk.sandbox.create_sandbox_session(*, session_type, session_kwargs, **kwargs) -> SandboxSessionContext[Any, Any]
```
Create a single-use context supporting both with and async with.
Pass constructor options for the selected class through session\_kwargs.
Other keyword arguments configure the factory or its client.
**session\_type** (default: None)
**session\_kwargs** (default: None)
\*\***kwargs**
**returns** `SandboxSessionContext[Any, Any]`
[`SandboxSessionContext`](./sandbox#contree_sdk.sandbox.SandboxSessionContext)\[Any, Any]
A composed context. See session\_maker for all configuration parameters.
## `create_sync_sandbox_session()`
```python theme={null}
def contree_sdk.sandbox.create_sync_sandbox_session(*, session_type, session_kwargs, **kwargs) -> SyncSandboxSessionContext[Any]
```
Create a sync-only context; its default session is LazySession.
Pass constructor options for the selected class through session\_kwargs.
Other keyword arguments configure the factory or its client.
**session\_type** (default: None)
**session\_kwargs** (default: None)
\*\***kwargs**
**returns** `SyncSandboxSessionContext[Any]`
[`SyncSandboxSessionContext`](./sandbox#contree_sdk.sandbox.SyncSandboxSessionContext)\[Any]
A synchronous context with the configuration accepted by session\_maker.
## `create_async_sandbox_session()`
```python theme={null}
def contree_sdk.sandbox.create_async_sandbox_session(*, session_type, session_kwargs, **kwargs) -> AsyncSandboxSessionContext[Any]
```
Create an async-only context; its default session is AsyncLazySession.
Pass constructor options for the selected class through session\_kwargs.
Other keyword arguments configure the factory or its client.
**session\_type** (default: None)
**session\_kwargs** (default: None)
\*\***kwargs**
**returns** `AsyncSandboxSessionContext[Any]`
[`AsyncSandboxSessionContext`](./sandbox#contree_sdk.sandbox.AsyncSandboxSessionContext)\[Any]
An asynchronous context with the configuration accepted by session\_maker.
## `session_maker()`
```python theme={null}
def contree_sdk.sandbox.session_maker(context_type, /, *, image, url, project, token, auth_type, profile, config_path, session_type, session_id, node_id, store, cache_ttl, cwd, env, commit_policy, file_transfer, session_kwargs, client, client_type, **client_kwargs) -> TypeVar(ContextT)
```
Prepare a sync/async sandbox context without opening connections or a VM.
Without session\_type, entry selects LazySession or AsyncLazySession. Explicit
classes must implement SyncExecutor or AsyncExecutor and match the context
mode. Lazy subclasses receive a base session; other classes receive a client
and the standard ContreeSession constructor keywords. session\_kwargs adds
arguments to the selected class, never to the underlying lazy base session.
Factory-managed arguments take priority over duplicates in session\_kwargs.
Connection arguments, an explicit profile/config\_path, and a borrowed client
are separate sources. Without an explicit source, use the client’s environment
profile, then its default INI resolution. client\_kwargs is forwarded unchanged
to the selected client’s from\_profile constructor. Created clients use
RetryPolicy() unless retry is supplied; retry=None disables retries.
The default lazy policy snapshots after 10 idle seconds. Normal exit saves
pending work; exceptional exit discards unsaved work. Snapshots retain files,
not running processes. ContreeSession and ContreeAsyncSession save each command
by default in a separate VM. Pass disposable=True to leave their history unchanged.
**context\_type** *required*
**image** (default: None)
**url** (default: None)
**project** (default: None)
**token** (default: None)
**auth\_type** (default: None)
**profile** (default: None)
**config\_path** (default: None)
**session\_type** (default: None)
**session\_id** (default: None)
**node\_id** (default: None)
**store** (default: None)
**cache\_ttl** (default: 60)
**cwd** (default: None)
**env** (default: None)
**commit\_policy** (default: None)
**file\_transfer** (default: None)
**session\_kwargs** (default: None)
**client** (default: None)
**client\_type** (default: None)
\*\***client\_kwargs**
**returns** `TypeVar(ContextT)`
A single-use context owning its created client, memory store, and session.
Supplied clients, stores, and file transfers remain caller-owned.
## `profile_from_args()`
```python theme={null}
def contree_sdk.connection.profile_from_args(*, token, url, project, auth_type) -> Profile
```
Build an explicit client profile without reading or writing configuration.
The default configuration uses the client’s endpoint when URL is omitted.
**token** *required*
**url** (default: None)
**project** (default: None)
**auth\_type** (default: 'iam')
**returns** `Profile`
A regular contree-client Profile.
**raises**
**ValueError** – Credentials, URL, or authentication type are invalid.
# Sessions and operations
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/session
Start with [Work with a Session](../session-model), [Save and resume a session](../sessions), or [Advanced: control a running sandbox](../operation).
Sync calls return results directly. Async calls must be awaited unless used as the
`PendingRun` context described in the operation guide.
`ContreeSession` and `ContreeAsyncSession` save each command by default.
`disposable=True` leaves the session image unchanged. `LazySession` and
`AsyncLazySession` reuse a VM until snapshot. Snapshots are lightweight and can
run after every command, but they stop the VM. An unchanged filesystem can return
the same image UUID. See [Save after every command](../session-model#save-after-every-command).
## `class AbstractCommitPolicy`
```python theme={null}
class contree_sdk.session.AbstractCommitPolicy()
```
Decide whether a validated operation result advances session history.
Sessions call this synchronous method only after API success, for a
non-disposable request. Implementations must not perform blocking I/O.
A policy cannot accept API failure, cancellation, or a missing result image.
### Methods
#### `should_commit()`
```python theme={null}
@abstractmethod
def should_commit(context, result) -> bool
```
**context** *required*
**result** *required*
**returns** `bool`
## `class AbstractSnapshotPolicy`
```python theme={null}
class contree_sdk.session.AbstractSnapshotPolicy()
```
Own the decision state and expose one future per VM cycle.
Use one policy instance per lazy session. Subclasses call super().**init**()
and super().notify(event) to reset or cancel the cycle future. Resolve the
future to request a snapshot, or fail it to report a policy error. The session
still waits for all accepted commands and inspections before stopping its VM.
### Methods
#### `notify()`
```python theme={null}
@abstractmethod
def notify(event) -> None
```
Handle an execution event without blocking or performing network I/O.
**event** *required*
**returns** `None`
#### `should_snapshot()`
```python theme={null}
def should_snapshot() -> Future[None]
```
Return this cycle’s future; successful completion requests a snapshot.
The caller must not cancel or resolve it. To await it from asyncio, use
shield(wrap\_future(…)) so cancellation does not affect the policy.
**returns** `Future[None]`
A future shared by all readers of the current policy decision.
## `class ApiSuccessCommitPolicy`
```python theme={null}
class contree_sdk.session.ApiSuccessCommitPolicy()
```
Retain every successful API result, including a nonzero or unknown exit code.
### Methods
#### `should_commit()`
```python theme={null}
def should_commit(context, result) -> bool
```
**context** *required*
**result** *required*
**returns** `bool`
## `class AsyncLazySession`
```python theme={null}
class contree_sdk.session.AsyncLazySession(session, *, snapshot_policy, snapshot_timeout, vm_timeout)
```
Share one VM across commands; save one history entry per snapshot.
The supplied session, its client and its store remain caller-owned. Do not
mutate that session outside this wrapper while a VM is active. Use this
object as a context manager or call close/abort to release its worker.
### Attributes
**error** `BaseException | None`
**phase** `Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']`
**session\_id** `str`
### Methods
#### `abort()`
```python theme={null}
async def abort() -> None
```
Discard unsaved work and close. An already running snapshot finishes first.
**returns** `None`
#### `close()`
```python theme={null}
async def close(*, timeout) -> None
```
Save pending work and close this wrapper, retaining caller-owned resources.
**timeout** (default: None)
**returns** `None`
**raises**
**RuntimeError** – Saving failed; the cause is available as error.
**raises**
**TimeoutError** – The caller’s wait expired; closing continues in the worker.
#### `create_branch()`
```python theme={null}
async def create_branch(name, *, from_branch) -> None
```
**name** *required*
**from\_branch** (default: None)
**returns** `None`
#### `execute()`
```python theme={null}
async def execute(request) -> InstanceResult
```
**request** *required*
**returns** `InstanceResult`
#### `grep()`
```python theme={null}
async def grep(pattern, *, path, glob, max_count, max_total, case, before, after) -> GrepResult
```
Search session files using the current source’s syntax and limits.
**pattern** *required*
**path** (default: None)
**glob** (default: None)
**max\_count** (default: None)
**max\_total** (default: None)
**case** (default: None)
**before** (default: None)
**after** (default: None)
**returns** `GrepResult`
Matching lines and the server’s truncation indicator.
#### `inspect()`
```python theme={null}
async def inspect(*, timeout) -> AsyncSessionInspector
```
Return a view that selects the current filesystem for each request.
Live requests do not stop the VM. Cold requests use the saved image;
pending staged files start a VM so the view includes those files.
timeout limits admission and VM startup waits, not HTTP I/O.
Use inspect\_snapshot() for a stable image and its image\_uuid.
**timeout** (default: None)
**returns** `AsyncSessionInspector`
A session-bound inspector; creating it starts no VM.
#### `inspect_snapshot()`
```python theme={null}
async def inspect_snapshot(*, timeout) -> AsyncImageInspector
```
Save active work and pin the resulting image for inspection.
Waits for admitted commands and inspections, then stops the VM.
A cold session starts no VM. Later commands cannot change the pinned image.
timeout limits the snapshot wait; saving continues if the wait ends early.
A failed snapshot raises instead of returning the previous image.
Staged attachments appear only after a command applies them.
**timeout** (default: None)
**returns** `AsyncImageInspector`
An inspector borrowing the underlying client and file transfer.
#### `inspection_source()`
```python theme={null}
def inspection_source(*, timeout) -> AsyncIterator[AsyncImageInspector | str]
```
Reserve the current source until the request and its stream close.
Override this hook to customize source selection. Image inspectors are
pinned; operation UUIDs remain protected from automatic snapshot.
**timeout** (default: None)
**returns** `AsyncIterator[AsyncImageInspector | str]`
**yields**
A saved image inspector or an active operation UUID.
**raises**
**RuntimeError** – The session fails or closes before inspection starts.
**raises**
**TimeoutError** – Admission or VM startup exceeds the timeout.
#### `keepalive_request()`
```python theme={null}
def keepalive_request() -> RunRequest
```
Supply a long-running main process available in the base image.
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The non-disposable request used to start each VM.
#### `list_dir()`
```python theme={null}
async def list_dir(path) -> DirectoryList
```
List session directory entries relative to the filesystem root.
**path** (default: '/')
**returns** `DirectoryList`
Directory entries and their filesystem metadata.
#### `observe()`
```python theme={null}
async def observe(event, error) -> None
```
Observe the operation’s sole reader without depending on handle.wait().
**event** *required*
**error** *required*
**returns** `None`
#### `prepare_request()`
```python theme={null}
def prepare_request(request) -> RunRequest
```
Apply the wrapped session’s policy and validate shared-VM semantics.
**request** *required*
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The effective request.
**raises**
**ValueError** – The request needs a disposable VM or startup-only options.
#### `read_file()`
```python theme={null}
async def read_file(path) -> bytes
```
Read current files without stopping an active VM.
**path** *required*
**returns** `bytes`
The complete file as bytes.
#### `rollback()`
```python theme={null}
async def rollback(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `run()`
```python theme={null}
async def run(command, **kwargs) -> InstanceResult
```
Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
**command** (default: None)
\*\***kwargs**
**returns** `InstanceResult`
The subprocess result, including a nonzero exit code.
#### `snapshot()`
```python theme={null}
async def snapshot(*, timeout) -> HistoryEntry | None
```
Drain commands and inspections, save their common image, and reopen admission.
Snapshots are lightweight and can run after every command. They stop
the VM. An unchanged filesystem can return the same image UUID.
timeout limits this wait; an already requested snapshot continues.
Errors remain available as error and are raised on subsequent calls.
Saving failure or a closed wrapper raises RuntimeError. A wait that
expires raises TimeoutError; saving continues in the worker.
**timeout** (default: None)
**returns** `HistoryEntry | None`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry) | None
The saved history entry, or None if no VM has run yet.
#### `spawn()`
```python theme={null}
async def spawn(command, **kwargs) -> AsyncSubprocessContract
```
**command** (default: None)
\*\***kwargs**
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
#### `spawn_request()`
```python theme={null}
async def spawn_request(request) -> AsyncSubprocessContract
```
Start a subprocess; track its exit even if the caller never waits.
**request** *required*
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
The subprocess handle from the operation factory.
#### `switch_branch()`
```python theme={null}
async def switch_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `write_file()`
```python theme={null}
async def write_file(path, content) -> None
```
Write bytes with the same contract as SyncExecutor.write\_file.
The default awaits execute() with binary stdin. Override with native
async file transfer, coordinating with commands and snapshot lifecycle.
Returns after application, not after staging or blob upload. Invalid paths
raise ValueError; a failed write raises FileWriteError. Transport errors,
timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
## `class AsyncOperation`
```python theme={null}
class contree_sdk.session.AsyncOperation(client, operation_uuid, *, timeout, shutdown_timeout, files, context)
```
Handle to a spawned instance operation, identified by its UUID.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `apply_files()`
```python theme={null}
async def apply_files(files) -> None
```
Apply already-uploaded files to this running VM.
**files** *required*
**returns** `None`
#### `cancel()`
```python theme={null}
async def cancel() -> None
```
**returns** `None`
#### `claim_queue()`
```python theme={null}
async def claim_queue(spid) -> Queue[OperationEvent | None]
```
**spid** *required*
**returns** `Queue[OperationEvent | None]`
#### `create_subprocess()`
```python theme={null}
def create_subprocess(spid, events_queue) -> AsyncSubprocessContract
```
Create a subprocess handle. Override to return a custom implementation.
**spid** *required*
**events\_queue** *required*
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
A handle consuming the supplied event queue.
#### `events()`
```python theme={null}
async def events(*, since, spid, timeout) -> AsyncIterator[OperationEvent]
```
Replay buffered events, then follow the shared reader with local filters.
timeout bounds this subscription. Expiry does not cancel the operation.
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `AsyncIterator[OperationEvent]`
**yields**
Events after `since` whose process matches `spid`, when specified.
**raises**
**TimeoutError** – The subscription did not finish before timeout.
#### `open_event_stream()`
```python theme={null}
def open_event_stream() -> AsyncIterator[OperationEvent]
```
Open the unfiltered source. Override this hook to supply custom events.
**returns** `AsyncIterator[OperationEvent]`
The single transport stream consumed by the operation.
#### `pipe_stdin()`
```python theme={null}
async def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
Forward chunks after spawn and stop waiting for input when the process exits.
Use one writer per process. Errors and cancellation stop the target process; spid=1 cancels the operation.
A pending source read is cancelled on exit; the caller owns the source.
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
Acknowledged bytes, EOF delivery, and observed early completion.
**raises**
**ValueError** – chunk\_size or spid is not positive.
#### `pump()`
```python theme={null}
async def pump() -> None
```
**returns** `None`
#### `route_event()`
```python theme={null}
async def route_event(event) -> None
```
**event** *required*
**returns** `None`
#### `run()`
```python theme={null}
async def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> AsyncSubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
#### `send_stdin()`
```python theme={null}
async def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `shutdown()`
```python theme={null}
async def shutdown() -> None
```
**returns** `None`
#### `signal()`
```python theme={null}
async def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `status()`
```python theme={null}
async def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `wait()`
```python theme={null}
async def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class AsyncOperationContract`
```python theme={null}
class contree_sdk.session.AsyncOperationContract()
```
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `apply_files()`
```python theme={null}
def apply_files(files) -> None
```
**files** *required*
**returns** `None`
#### `cancel()`
```python theme={null}
def cancel() -> None
```
**returns** `None`
#### `events()`
```python theme={null}
@abstractmethod
def events(*, since, spid, timeout) -> AsyncIterator[OperationEvent]
```
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `AsyncIterator[OperationEvent]`
#### `pipe_stdin()`
```python theme={null}
def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
#### `run()`
```python theme={null}
def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> AsyncSubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `AsyncSubprocessContract`
[`AsyncSubprocessContract`](./execution#contree_sdk.session.contracts.AsyncSubprocessContract)
#### `send_stdin()`
```python theme={null}
def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `shutdown()`
```python theme={null}
def shutdown() -> None
```
**returns** `None`
#### `signal()`
```python theme={null}
def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `status()`
```python theme={null}
def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class AsyncSubprocessContract`
```python theme={null}
class contree_sdk.session.AsyncSubprocessContract()
```
Waitable event stream for one subprocess. Iteration and wait share completion state.
### Attributes
**spid** `int`
### Methods
#### `pipe_to()`
```python theme={null}
def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class AsyncSubprocessHandle`
```python theme={null}
class contree_sdk.session.AsyncSubprocessHandle(operation, spid, events_queue)
```
Both awaitable (final result) and async-iterable (live events) for one spid.
### Attributes
**spid** `int`
### Methods
#### `iterate()`
```python theme={null}
async def iterate() -> AsyncIterator[OperationEvent]
```
**returns** `AsyncIterator[OperationEvent]`
#### `pipe_to()`
```python theme={null}
async def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
#### `wait()`
```python theme={null}
async def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class CommandCountSnapshotPolicy`
```python theme={null}
class contree_sdk.session.CommandCountSnapshotPolicy(limit)
```
Request a snapshot after exactly limit command admissions in one VM.
### Methods
#### `notify()`
```python theme={null}
def notify(event) -> None
```
Handle an execution event without blocking or performing network I/O.
**event** *required*
**returns** `None`
#### `should_snapshot()`
```python theme={null}
def should_snapshot() -> Future[None]
```
Return this cycle’s future; successful completion requests a snapshot.
The caller must not cancel or resolve it. To await it from asyncio, use
shield(wrap\_future(…)) so cancellation does not affect the policy.
**returns** `Future[None]`
A future shared by all readers of the current policy decision.
## `class CompositeSnapshotPolicy`
```python theme={null}
class contree_sdk.session.CompositeSnapshotPolicy(*policies)
```
Request a snapshot when any child policy’s future completes.
### Methods
#### `notify()`
```python theme={null}
def notify(event) -> None
```
Handle an execution event without blocking or performing network I/O.
**event** *required*
**returns** `None`
#### `should_snapshot()`
```python theme={null}
def should_snapshot() -> Future[None]
```
Return this cycle’s future; successful completion requests a snapshot.
The caller must not cancel or resolve it. To await it from asyncio, use
shield(wrap\_future(…)) so cancellation does not affect the policy.
**returns** `Future[None]`
A future shared by all readers of the current policy decision.
## `class ContreeAsyncSession`
```python theme={null}
class contree_sdk.session.ContreeAsyncSession(client, *, image, session_id, node_id, tree_kind, store, file_transfer, cwd, env, commit_policy)
```
A durable, resumable ConTree session backed by a Store.
### Attributes
**session\_id** `str`
### Methods
#### `check_operation_endpoint()`
```python theme={null}
def check_operation_endpoint(record) -> None
```
Check the recorded server before using an operation UUID.
**record** *required*
**returns** `None`
**raises**
**ValueError** – The current client targets a different endpoint.
#### `commit_result()`
```python theme={null}
async def commit_result(operation, *, title, branch, files, data) -> HistoryEntry | None
```
**operation** *required*
**title** (default: None)
**branch** (default: None)
**files** (default: None)
**data** (default: None)
**returns** `HistoryEntry | None`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry) | None
#### `create_branch()`
```python theme={null}
async def create_branch(name, *, from_branch) -> None
```
**name** *required*
**from\_branch** (default: None)
**returns** `None`
#### `create_file_transfer()`
```python theme={null}
def create_file_transfer() -> AsyncFileTransfer
```
Create file I/O when no component was supplied.
**returns** `AsyncFileTransfer`
[`AsyncFileTransfer`](./files#contree_sdk.files.AsyncFileTransfer)
A file-transfer component using the session client.
#### `create_inspector()`
```python theme={null}
def create_inspector(image_uuid) -> AsyncImageInspector
```
Create a view of one image. Override to customize inspection.
**image\_uuid** *required*
**returns** `AsyncImageInspector`
An inspector borrowing the client’s connection and file transfer.
#### `create_operation()`
```python theme={null}
def create_operation(response, context) -> AsyncOperationContract
```
Construct a lifecycle implementation bound to the supplied operation context.
**response** *required*
**context** *required*
**returns** `AsyncOperationContract`
[`AsyncOperationContract`](./execution#contree_sdk.session.contracts.AsyncOperationContract)
An implementation of the matching operation lifecycle contract.
#### `create_operation_record()`
```python theme={null}
def create_operation_record(operation) -> OperationRecord
```
Serialize an operation context. Override to persist custom request fields.
**operation** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
A pending record without local input sources.
**raises**
**ValueError** – The operation does not belong to this session.
#### `create_pending_run()`
```python theme={null}
def create_pending_run(request, *, branch) -> PendingRun
```
Create the awaitable/context-manager wrapper for a command.
**request** *required*
**branch** (default: None)
**returns** `PendingRun`
[`PendingRun`](./session#contree_sdk.session.PendingRun)
A one-use wrapper for awaiting or entering the operation.
#### `create_store()`
```python theme={null}
def create_store() -> AsyncStore
```
Create the default store when none was supplied.
**returns** `AsyncStore`
[`AsyncStore`](./store#contree_sdk.store.AsyncStore)
A new memory store owned by this session.
#### `delete_branch()`
```python theme={null}
async def delete_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `detach()`
```python theme={null}
async def detach(operation) -> OperationRecord
```
Register an already spawned operation without reading events or closing it.
**operation** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
Its durable record. The caller still owns the live handle.
**raises**
**ValueError** – The operation does not belong to this session.
#### `ensure_ready()`
```python theme={null}
async def ensure_ready() -> None
```
**returns** `None`
#### `execute()`
```python theme={null}
async def execute(request, *, branch) -> InstanceResult
```
Run a request to completion and commit its effective non-disposable result.
**request** *required*
**branch** (default: None)
**returns** `InstanceResult`
The completed process result, including nonzero exit codes.
#### `get_entry()`
```python theme={null}
async def get_entry(node_id) -> HistoryEntry
```
**node\_id** *required*
**returns** `HistoryEntry`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)
#### `get_operation()`
```python theme={null}
async def get_operation(operation_uuid) -> OperationRecord
```
**operation\_uuid** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
#### `grep()`
```python theme={null}
async def grep(pattern, *, path, glob, max_count, max_total, case, before, after) -> GrepResult
```
Search session files using the current source’s syntax and limits.
**pattern** *required*
**path** (default: None)
**glob** (default: None)
**max\_count** (default: None)
**max\_total** (default: None)
**case** (default: None)
**before** (default: None)
**after** (default: None)
**returns** `GrepResult`
Matching lines and the server’s truncation indicator.
#### `history()`
```python theme={null}
async def history() -> tuple[list[HistoryEntry], dict[str, list[str]]]
```
**returns** `tuple[list[HistoryEntry], dict[str, list[str]]]`
tuple\[list\[[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)], dict\[str, list\[str]]]
#### `inspect()`
```python theme={null}
async def inspect() -> AsyncImageInspector
```
Pin the current saved image without starting a VM.
Pending staged attachments appear only after an operation applies them.
**returns** `AsyncImageInspector`
A read-only view that borrows this session’s client and file transfer.
#### `list_branches()`
```python theme={null}
async def list_branches() -> list[tuple[str, bool]]
```
**returns** `list[tuple[str, bool]]`
#### `list_dir()`
```python theme={null}
async def list_dir(path) -> DirectoryList
```
List session directory entries relative to the filesystem root.
**path** (default: '/')
**returns** `DirectoryList`
Directory entries and their filesystem metadata.
#### `list_operations()`
```python theme={null}
async def list_operations(*, pending_only) -> tuple[OperationRecord, ...]
```
**pending\_only** (default: True)
**returns** `tuple[OperationRecord, ...]`
tuple\[[`OperationRecord`](./session#contree_sdk.session.OperationRecord), ...]
#### `navigate()`
```python theme={null}
async def navigate(node_id) -> None
```
**node\_id** *required*
**returns** `None`
#### `navigate_forward()`
```python theme={null}
async def navigate_forward(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `pending_files()`
```python theme={null}
async def pending_files(node_id) -> tuple[StagedFile, ...]
```
**node\_id** (default: None)
**returns** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
#### `prepare_environment()`
```python theme={null}
def prepare_environment(env) -> dict[str, str] | None
```
Overlay command variables on session defaults without mutating either input.
**env** *required*
**returns** `dict[str, str] | None`
A fresh mapping, or None when both inputs omit environment variables.
#### `prepare_request()`
```python theme={null}
def prepare_request(request) -> RunRequest
```
Apply defaults before uploads or execution. Override to validate or transform commands.
**request** *required*
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The effective command with session defaults applied.
#### `read_file()`
```python theme={null}
async def read_file(path) -> bytes
```
**path** *required*
**returns** `bytes`
#### `refresh_from_entry()`
```python theme={null}
async def refresh_from_entry(entry) -> None
```
**entry** *required*
**returns** `None`
#### `resolve_image()`
```python theme={null}
async def resolve_image(image) -> str
```
Resolve a base image. Override to implement an import or registry policy.
**image** *required*
**returns** `str`
The resolved image UUID.
#### `restore_operation()`
```python theme={null}
async def restore_operation(operation_uuid) -> AsyncOperationContract
```
Recreate a control handle from the persisted source context.
**operation\_uuid** *required*
**returns** `AsyncOperationContract`
[`AsyncOperationContract`](./execution#contree_sdk.session.contracts.AsyncOperationContract)
An unentered handle. Use wait\_operation to reuse a stored final result.
#### `restore_operation_context()`
```python theme={null}
def restore_operation_context(record) -> OperationContext
```
Decode a stored request. Override together with create\_operation\_record.
**record** *required*
**returns** `OperationContext`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext)
Its immutable source context, ready for an operation factory or policy.
#### `rollback()`
```python theme={null}
async def rollback(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `run()`
```python theme={null}
def run(command, *, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking, branch) -> PendingRun
```
**command** (default: None)
**shell** (default: None)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**files** (default: None)
**timeout** (default: None)
**disposable** (default: False)
**truncate\_output\_at** (default: None)
**preserve\_env** (default: False)
**hostname** (default: None)
**uid** (default: None)
**gid** (default: None)
**resources\_limits** (default: None)
**networking** (default: None)
**branch** (default: None)
**returns** `PendingRun`
[`PendingRun`](./session#contree_sdk.session.PendingRun)
#### `set_cwd()`
```python theme={null}
async def set_cwd(cwd) -> None
```
**cwd** *required*
**returns** `None`
#### `set_env()`
```python theme={null}
async def set_env(updates) -> None
```
**updates** *required*
**returns** `None`
#### `spawn()`
```python theme={null}
async def spawn(command, *, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking) -> AsyncOperationContract
```
**command** (default: None)
**shell** (default: None)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**files** (default: None)
**timeout** (default: None)
**disposable** (default: False)
**truncate\_output\_at** (default: None)
**preserve\_env** (default: False)
**hostname** (default: None)
**uid** (default: None)
**gid** (default: None)
**resources\_limits** (default: None)
**networking** (default: None)
**returns** `AsyncOperationContract`
[`AsyncOperationContract`](./execution#contree_sdk.session.contracts.AsyncOperationContract)
#### `spawn_detached()`
```python theme={null}
async def spawn_detached(command, **kwargs) -> OperationRecord
```
Spawn and register a command; options are RunRequest fields.
**command** (default: None)
\*\***kwargs**
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
A durable record whose UUID can be passed to wait\_operation.
#### `spawn_request()`
```python theme={null}
async def spawn_request(request) -> AsyncOperationContract
```
Prepare and submit a command, then construct its operation through the factory.
**request** *required*
**returns** `AsyncOperationContract`
[`AsyncOperationContract`](./execution#contree_sdk.session.contracts.AsyncOperationContract)
A bound operation whose context records the effective request.
#### `stage_files()`
```python theme={null}
async def stage_files(files) -> HistoryEntry
```
**files** *required*
**returns** `HistoryEntry`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)
#### `submit_request()`
```python theme={null}
async def submit_request(request, image_uuid, *, files, stdin) -> InstanceSpawnResponse
```
Submit prepared input to the transport. Override for transport-level customization.
**request** *required*
**image\_uuid** *required*
**files** *required*
**stdin** *required*
**returns** `InstanceSpawnResponse`
The transport response identifying the spawned operation.
#### `switch_branch()`
```python theme={null}
async def switch_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `wait_operation()`
```python theme={null}
async def wait_operation(operation_uuid, *, timeout, branch) -> InstanceResult
```
Wait and finish once, without switching the session’s active branch.
Completed outcomes are replayed locally. Transport errors remain pending.
Late results retain their original parent without replacing newer local
positions. The first completed outcome wins across concurrent policies.
**operation\_uuid** *required*
**timeout** (default: None)
**branch** (default: None)
**returns** `InstanceResult`
The stored process result, including nonzero exit codes.
#### `write_file()`
```python theme={null}
async def write_file(path, content) -> None
```
Write bytes with the same contract as SyncExecutor.write\_file.
The default awaits execute() with binary stdin. Override with native
async file transfer, coordinating with commands and snapshot lifecycle.
Returns after application, not after staging or blob upload. Invalid paths
raise ValueError; a failed write raises FileWriteError. Transport errors,
timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
## `class ContreeSession`
```python theme={null}
class contree_sdk.session.ContreeSession(client, *, image, session_id, node_id, tree_kind, store, file_transfer, cwd, env, commit_policy)
```
A durable, resumable ConTree session backed by a Store (sync).
### Attributes
**session\_id** `str`
### Methods
#### `check_operation_endpoint()`
```python theme={null}
def check_operation_endpoint(record) -> None
```
Check the recorded server before using an operation UUID.
**record** *required*
**returns** `None`
**raises**
**ValueError** – The current client targets a different endpoint.
#### `commit_result()`
```python theme={null}
def commit_result(operation, *, title, branch, files, data) -> HistoryEntry | None
```
**operation** *required*
**title** (default: None)
**branch** (default: None)
**files** (default: None)
**data** (default: None)
**returns** `HistoryEntry | None`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry) | None
#### `create_branch()`
```python theme={null}
def create_branch(name, *, from_branch) -> None
```
**name** *required*
**from\_branch** (default: None)
**returns** `None`
#### `create_file_transfer()`
```python theme={null}
def create_file_transfer() -> SyncFileTransfer
```
Create file I/O when no component was supplied.
**returns** `SyncFileTransfer`
[`SyncFileTransfer`](./files#contree_sdk.files.SyncFileTransfer)
A file-transfer component using the session client.
#### `create_inspector()`
```python theme={null}
def create_inspector(image_uuid) -> ImageInspector
```
Create a view of one image. Override to customize inspection.
**image\_uuid** *required*
**returns** `ImageInspector`
An inspector borrowing the client’s connection and file transfer.
#### `create_operation()`
```python theme={null}
def create_operation(response, context) -> OperationContract
```
Construct a lifecycle implementation bound to the supplied operation context.
**response** *required*
**context** *required*
**returns** `OperationContract`
[`OperationContract`](./execution#contree_sdk.session.contracts.OperationContract)
An implementation of the matching operation lifecycle contract.
#### `create_operation_record()`
```python theme={null}
def create_operation_record(operation) -> OperationRecord
```
Serialize an operation context. Override to persist custom request fields.
**operation** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
A pending record without local input sources.
**raises**
**ValueError** – The operation does not belong to this session.
#### `create_store()`
```python theme={null}
def create_store() -> SyncStore
```
Create the default store when none was supplied.
**returns** `SyncStore`
[`SyncStore`](./store#contree_sdk.store.SyncStore)
A new memory store owned by this session.
#### `delete_branch()`
```python theme={null}
def delete_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `detach()`
```python theme={null}
def detach(operation) -> OperationRecord
```
Register an already spawned operation without reading events or closing it.
**operation** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
Its durable record. The caller still owns the live handle.
**raises**
**ValueError** – The operation does not belong to this session.
#### `execute()`
```python theme={null}
def execute(request, *, branch) -> InstanceResult
```
Run a request to completion and commit its effective non-disposable result.
**request** *required*
**branch** (default: None)
**returns** `InstanceResult`
The completed process result, including nonzero exit codes.
**raises**
**ValueError** – The operation factory returned an unbound operation.
#### `get_entry()`
```python theme={null}
def get_entry(node_id) -> HistoryEntry
```
**node\_id** *required*
**returns** `HistoryEntry`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)
#### `get_operation()`
```python theme={null}
def get_operation(operation_uuid) -> OperationRecord
```
**operation\_uuid** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
#### `grep()`
```python theme={null}
def grep(pattern, *, path, glob, max_count, max_total, case, before, after) -> GrepResult
```
Search session files using the current source’s syntax and limits.
**pattern** *required*
**path** (default: None)
**glob** (default: None)
**max\_count** (default: None)
**max\_total** (default: None)
**case** (default: None)
**before** (default: None)
**after** (default: None)
**returns** `GrepResult`
Matching lines and the server’s truncation indicator.
#### `history()`
```python theme={null}
def history() -> tuple[list[HistoryEntry], dict[str, list[str]]]
```
**returns** `tuple[list[HistoryEntry], dict[str, list[str]]]`
tuple\[list\[[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)], dict\[str, list\[str]]]
#### `inspect()`
```python theme={null}
def inspect() -> ImageInspector
```
Pin the current saved image without starting a VM.
Pending staged attachments appear only after an operation applies them.
**returns** `ImageInspector`
A read-only view that borrows this session’s client and file transfer.
#### `list_branches()`
```python theme={null}
def list_branches() -> list[tuple[str, bool]]
```
**returns** `list[tuple[str, bool]]`
#### `list_dir()`
```python theme={null}
def list_dir(path) -> DirectoryList
```
List session directory entries relative to the filesystem root.
**path** (default: '/')
**returns** `DirectoryList`
Directory entries and their filesystem metadata.
#### `list_operations()`
```python theme={null}
def list_operations(*, pending_only) -> tuple[OperationRecord, ...]
```
**pending\_only** (default: True)
**returns** `tuple[OperationRecord, ...]`
tuple\[[`OperationRecord`](./session#contree_sdk.session.OperationRecord), ...]
#### `navigate()`
```python theme={null}
def navigate(node_id) -> None
```
**node\_id** *required*
**returns** `None`
#### `navigate_forward()`
```python theme={null}
def navigate_forward(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `pending_files()`
```python theme={null}
def pending_files(node_id) -> tuple[StagedFile, ...]
```
**node\_id** (default: None)
**returns** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
#### `prepare_environment()`
```python theme={null}
def prepare_environment(env) -> dict[str, str] | None
```
Overlay command variables on session defaults without mutating either input.
**env** *required*
**returns** `dict[str, str] | None`
A fresh mapping, or None when both inputs omit environment variables.
#### `prepare_request()`
```python theme={null}
def prepare_request(request) -> RunRequest
```
Apply defaults before uploads or execution. Override to validate or transform commands.
**request** *required*
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The effective command with session defaults applied.
#### `read_file()`
```python theme={null}
def read_file(path) -> bytes
```
**path** *required*
**returns** `bytes`
#### `refresh_from_entry()`
```python theme={null}
def refresh_from_entry(entry) -> None
```
**entry** *required*
**returns** `None`
#### `resolve_image()`
```python theme={null}
def resolve_image(image) -> str
```
Resolve a base image. Override to implement an import or registry policy.
**image** *required*
**returns** `str`
The resolved image UUID.
#### `restore_operation()`
```python theme={null}
def restore_operation(operation_uuid) -> OperationContract
```
Recreate a control handle from the persisted source context.
**operation\_uuid** *required*
**returns** `OperationContract`
[`OperationContract`](./execution#contree_sdk.session.contracts.OperationContract)
An unentered handle. Use wait\_operation to reuse a stored final result.
#### `restore_operation_context()`
```python theme={null}
def restore_operation_context(record) -> OperationContext
```
Decode a stored request. Override together with create\_operation\_record.
**record** *required*
**returns** `OperationContext`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext)
Its immutable source context, ready for an operation factory or policy.
#### `rollback()`
```python theme={null}
def rollback(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `run()`
```python theme={null}
def run(command, *, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking, branch) -> InstanceResult
```
**command** (default: None)
**shell** (default: None)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**files** (default: None)
**timeout** (default: None)
**disposable** (default: False)
**truncate\_output\_at** (default: None)
**preserve\_env** (default: False)
**hostname** (default: None)
**uid** (default: None)
**gid** (default: None)
**resources\_limits** (default: None)
**networking** (default: None)
**branch** (default: None)
**returns** `InstanceResult`
#### `set_cwd()`
```python theme={null}
def set_cwd(cwd) -> None
```
**cwd** *required*
**returns** `None`
#### `set_env()`
```python theme={null}
def set_env(updates) -> None
```
**updates** *required*
**returns** `None`
#### `spawn()`
```python theme={null}
def spawn(command, *, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking) -> OperationContract
```
**command** (default: None)
**shell** (default: None)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**files** (default: None)
**timeout** (default: None)
**disposable** (default: False)
**truncate\_output\_at** (default: None)
**preserve\_env** (default: False)
**hostname** (default: None)
**uid** (default: None)
**gid** (default: None)
**resources\_limits** (default: None)
**networking** (default: None)
**returns** `OperationContract`
[`OperationContract`](./execution#contree_sdk.session.contracts.OperationContract)
#### `spawn_detached()`
```python theme={null}
def spawn_detached(command, **kwargs) -> OperationRecord
```
Spawn and register a command; options are RunRequest fields.
**command** (default: None)
\*\***kwargs**
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
A durable record whose UUID can be passed to wait\_operation.
#### `spawn_request()`
```python theme={null}
def spawn_request(request) -> OperationContract
```
Prepare and submit a command, then construct its operation through the factory.
**request** *required*
**returns** `OperationContract`
[`OperationContract`](./execution#contree_sdk.session.contracts.OperationContract)
A bound operation whose context records the effective request.
#### `stage_files()`
```python theme={null}
def stage_files(files) -> HistoryEntry
```
**files** *required*
**returns** `HistoryEntry`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry)
#### `submit_request()`
```python theme={null}
def submit_request(request, image_uuid, *, files, stdin) -> InstanceSpawnResponse
```
Submit prepared input to the transport. Override for transport-level customization.
**request** *required*
**image\_uuid** *required*
**files** *required*
**stdin** *required*
**returns** `InstanceSpawnResponse`
The transport response identifying the spawned operation.
#### `switch_branch()`
```python theme={null}
def switch_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `wait_operation()`
```python theme={null}
def wait_operation(operation_uuid, *, timeout, branch) -> InstanceResult
```
Wait and finish once, without switching the session’s active branch.
Completed outcomes are replayed locally. Transport errors remain pending.
Late results retain their original parent without replacing newer local
positions. The first completed outcome wins across concurrent policies.
**operation\_uuid** *required*
**timeout** (default: None)
**branch** (default: None)
**returns** `InstanceResult`
The stored process result, including nonzero exit codes.
#### `write_file()`
```python theme={null}
def write_file(path, content) -> None
```
Write bytes to an absolute path, creating its parent directories.
Returns after the write is applied to the executor’s filesystem. It does
not merely stage a file or upload a blob. Persistence follows execute().
The default runs mkdir and cat through execute() with binary stdin.
Override this method to use another file-transfer mechanism. An override
must coordinate with the executor’s commands and snapshot lifecycle.
Invalid paths raise ValueError; a failed write raises FileWriteError.
Transport errors, timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
## `class DurationSnapshotPolicy`
```python theme={null}
class contree_sdk.session.DurationSnapshotPolicy(seconds, *, timer_factory, clock)
```
Request a snapshot after a fixed VM lifetime, including startup time.
### Methods
#### `expired()`
```python theme={null}
def expired(generation) -> None
```
**generation** *required*
**returns** `None`
#### `notify()`
```python theme={null}
def notify(event) -> None
```
Handle an execution event without blocking or performing network I/O.
**event** *required*
**returns** `None`
#### `schedule_timer()`
```python theme={null}
def schedule_timer() -> None
```
**returns** `None`
#### `set_duration()`
```python theme={null}
def set_duration(seconds) -> None
```
Update the deadline relative to the original VM startup time.
**seconds** *required*
**returns** `None`
**raises**
**ValueError** – The duration is not finite and positive.
#### `should_snapshot()`
```python theme={null}
def should_snapshot() -> Future[None]
```
Return this cycle’s future; successful completion requests a snapshot.
The caller must not cancel or resolve it. To await it from asyncio, use
shield(wrap\_future(…)) so cancellation does not affect the policy.
**returns** `Future[None]`
A future shared by all readers of the current policy decision.
#### `start_deferred()`
```python theme={null}
def start_deferred() -> None
```
Record startup time; set\_duration later arms the effective deadline.
**returns** `None`
## `class HistoryEntry`
```python theme={null}
class contree_sdk.session.HistoryEntry(id, session_id, image_uuid, parent_id, kind, title, operation_uuid, exit_code, created_at, files, attachments, applied_files, data)
```
### Attributes
**applied\_files** `tuple[str, ...]`
**attachments** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
**files** `tuple[str, ...]`
**id** `str`
**session\_id** `str`
**image\_uuid** `str`
**parent\_id** `str | None`
**kind** `str`
**title** `str`
**operation\_uuid** `str | None`
**exit\_code** `int | None`
**created\_at** `datetime`
**data** `dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]]`
## `class IdleSnapshotPolicy`
```python theme={null}
class contree_sdk.session.IdleSnapshotPolicy(seconds, *, timer_factory)
```
Request a snapshot after commands and inspections have been idle for seconds.
Timers start when the last command or inspection finishes. Admission,
reset, or close cancels the timer. Async callers use their event loop’s timer; sync callers
use a daemon threading.Timer. Inject timer\_factory for a custom scheduler.
### Methods
#### `notify()`
```python theme={null}
def notify(event) -> None
```
Handle an execution event without blocking or performing network I/O.
**event** *required*
**returns** `None`
#### `should_snapshot()`
```python theme={null}
def should_snapshot() -> Future[None]
```
Return this cycle’s future; successful completion requests a snapshot.
The caller must not cancel or resolve it. To await it from asyncio, use
shield(wrap\_future(…)) so cancellation does not affect the policy.
**returns** `Future[None]`
A future shared by all readers of the current policy decision.
## `class LazySession`
```python theme={null}
class contree_sdk.session.LazySession(session, *, snapshot_policy, snapshot_timeout, vm_timeout)
```
Share one VM across commands; save one history entry per snapshot.
The supplied session, its client and its store remain caller-owned. Do not
mutate that session outside this wrapper while a VM is active. Use this
object as a context manager or call close/abort to release its worker.
### Attributes
**error** `BaseException | None`
**phase** `Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']`
**session\_id** `str`
### Methods
#### `abort()`
```python theme={null}
def abort() -> None
```
Discard unsaved work and close. An already running snapshot finishes first.
**returns** `None`
#### `close()`
```python theme={null}
def close(*, timeout) -> None
```
Save pending work and close this wrapper, retaining caller-owned resources.
**timeout** (default: None)
**returns** `None`
**raises**
**RuntimeError** – Saving failed; the cause is available as error.
**raises**
**TimeoutError** – The caller’s wait expired; closing continues in the worker.
#### `create_branch()`
```python theme={null}
def create_branch(name, *, from_branch) -> None
```
**name** *required*
**from\_branch** (default: None)
**returns** `None`
#### `execute()`
```python theme={null}
def execute(request) -> InstanceResult
```
**request** *required*
**returns** `InstanceResult`
#### `grep()`
```python theme={null}
def grep(pattern, *, path, glob, max_count, max_total, case, before, after) -> GrepResult
```
Search session files using the current source’s syntax and limits.
**pattern** *required*
**path** (default: None)
**glob** (default: None)
**max\_count** (default: None)
**max\_total** (default: None)
**case** (default: None)
**before** (default: None)
**after** (default: None)
**returns** `GrepResult`
Matching lines and the server’s truncation indicator.
#### `inspect()`
```python theme={null}
def inspect(*, timeout) -> SessionInspector
```
Return a view that selects the current filesystem for each request.
Live requests do not stop the VM. Cold requests use the saved image;
pending staged files start a VM so the view includes those files.
timeout limits admission and VM startup waits, not HTTP I/O.
Use inspect\_snapshot() for a stable image and its image\_uuid.
**timeout** (default: None)
**returns** `SessionInspector`
A session-bound inspector; creating it starts no VM.
#### `inspect_snapshot()`
```python theme={null}
def inspect_snapshot(*, timeout) -> ImageInspector
```
Save active work and pin the resulting image for inspection.
Waits for admitted commands and inspections, then stops the VM.
A cold session starts no VM. Later commands cannot change the pinned image.
timeout limits the snapshot wait; saving continues if the wait ends early.
A failed snapshot raises instead of returning the previous image.
Staged attachments appear only after a command applies them.
**timeout** (default: None)
**returns** `ImageInspector`
An inspector borrowing the underlying client and file transfer.
#### `inspection_source()`
```python theme={null}
def inspection_source(*, timeout) -> Iterator[ImageInspector | str]
```
Reserve the current source until the request and its stream close.
Override this hook to customize source selection. Image inspectors are
pinned; operation UUIDs remain protected from automatic snapshot.
**timeout** (default: None)
**returns** `Iterator[ImageInspector | str]`
**yields**
A saved image inspector or an active operation UUID.
**raises**
**RuntimeError** – The session fails or closes before inspection starts.
**raises**
**TimeoutError** – Admission or VM startup exceeds the timeout.
#### `keepalive_request()`
```python theme={null}
def keepalive_request() -> RunRequest
```
Supply a long-running main process available in the base image.
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The non-disposable request used to start each VM.
#### `list_dir()`
```python theme={null}
def list_dir(path) -> DirectoryList
```
List session directory entries relative to the filesystem root.
**path** (default: '/')
**returns** `DirectoryList`
Directory entries and their filesystem metadata.
#### `observe()`
```python theme={null}
def observe(event, error) -> None
```
Observe the operation’s sole reader without depending on handle.wait().
**event** *required*
**error** *required*
**returns** `None`
#### `prepare_request()`
```python theme={null}
def prepare_request(request) -> RunRequest
```
Apply the wrapped session’s policy and validate shared-VM semantics.
**request** *required*
**returns** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
The effective request.
**raises**
**ValueError** – The request needs a disposable VM or startup-only options.
#### `read_file()`
```python theme={null}
def read_file(path) -> bytes
```
Read current files without stopping an active VM.
**path** *required*
**returns** `bytes`
The complete file as bytes.
#### `rollback()`
```python theme={null}
def rollback(steps) -> None
```
**steps** (default: 1)
**returns** `None`
#### `run()`
```python theme={null}
def run(command, **kwargs) -> InstanceResult
```
Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
**command** (default: None)
\*\***kwargs**
**returns** `InstanceResult`
The subprocess result, including a nonzero exit code.
#### `snapshot()`
```python theme={null}
def snapshot(*, timeout) -> HistoryEntry | None
```
Drain commands and inspections, save their common image, and reopen admission.
Snapshots are lightweight and can run after every command. They stop
the VM. An unchanged filesystem can return the same image UUID.
timeout limits this wait; an already requested snapshot continues.
Errors remain available as error and are raised on subsequent calls.
Saving failure or a closed wrapper raises RuntimeError. A wait that
expires raises TimeoutError; saving continues in the worker.
**timeout** (default: None)
**returns** `HistoryEntry | None`
[`HistoryEntry`](./session#contree_sdk.session.HistoryEntry) | None
The saved history entry, or None if no VM has run yet.
#### `spawn()`
```python theme={null}
def spawn(command, **kwargs) -> SubprocessContract
```
**command** (default: None)
\*\***kwargs**
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
#### `spawn_request()`
```python theme={null}
def spawn_request(request) -> SubprocessContract
```
Start a subprocess; track its exit even if the caller never waits.
**request** *required*
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
The subprocess handle from the operation factory.
#### `switch_branch()`
```python theme={null}
def switch_branch(name) -> None
```
**name** *required*
**returns** `None`
#### `write_file()`
```python theme={null}
def write_file(path, content) -> None
```
Write bytes to an absolute path, creating its parent directories.
Returns after the write is applied to the executor’s filesystem. It does
not merely stage a file or upload a blob. Persistence follows execute().
The default runs mkdir and cat through execute() with binary stdin.
Override this method to use another file-transfer mechanism. An override
must coordinate with the executor’s commands and snapshot lifecycle.
Invalid paths raise ValueError; a failed write raises FileWriteError.
Transport errors, timeouts, and cancellation propagate unchanged.
**path** *required*
**content** *required*
**returns** `None`
## `class Operation`
```python theme={null}
class contree_sdk.session.Operation(client, operation_uuid, *, timeout, shutdown_timeout, files, context)
```
Handle to a spawned instance operation, identified by its UUID.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `apply_files()`
```python theme={null}
def apply_files(files) -> None
```
Apply already-uploaded files to this running VM.
**files** *required*
**returns** `None`
#### `cancel()`
```python theme={null}
def cancel() -> None
```
**returns** `None`
#### `claim_queue()`
```python theme={null}
def claim_queue(spid) -> Queue[OperationEvent | None]
```
**spid** *required*
**returns** `Queue[OperationEvent | None]`
#### `create_subprocess()`
```python theme={null}
def create_subprocess(spid, events_queue) -> SubprocessContract
```
Create a subprocess handle. Override to return a custom implementation.
**spid** *required*
**events\_queue** *required*
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
A handle consuming the supplied event queue.
#### `events()`
```python theme={null}
def events(*, since, spid, timeout) -> Iterator[OperationEvent]
```
Replay buffered events, then follow the shared reader with local filters.
timeout bounds this subscription. Expiry does not cancel the operation.
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `Iterator[OperationEvent]`
**yields**
Events after `since` whose process matches `spid`, when specified.
**raises**
**TimeoutError** – The subscription did not finish before timeout.
#### `open_event_stream()`
```python theme={null}
def open_event_stream() -> Iterator[OperationEvent]
```
Open the unfiltered source. Override this hook to supply custom events.
**returns** `Iterator[OperationEvent]`
The single transport stream consumed by the operation.
#### `pipe_stdin()`
```python theme={null}
def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
Forward chunks after spawn, using the operation’s shared event reader.
The caller owns the source and must make blocking reads interruptible.
Use one writer per process. Errors stop the target process and propagate.
Errors for spid=1 cancel the operation.
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
Acknowledged bytes, EOF delivery, and observed early completion.
**raises**
**ValueError** – chunk\_size or spid is not positive.
#### `pump()`
```python theme={null}
def pump() -> None
```
**returns** `None`
#### `route_event()`
```python theme={null}
def route_event(event) -> None
```
**event** *required*
**returns** `None`
#### `run()`
```python theme={null}
def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> SubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
#### `send_stdin()`
```python theme={null}
def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `shutdown()`
```python theme={null}
def shutdown() -> None
```
**returns** `None`
#### `signal()`
```python theme={null}
def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `status()`
```python theme={null}
def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class OperationContext`
```python theme={null}
class contree_sdk.session.OperationContext(request, session_id, image_uuid, parent_id, branch, files, attachments, detached, node_id, created_at, position_version, session_cwd, session_env)
```
The effective request and history position captured before remote execution.
### Attributes
**attachments** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
**detached** `bool`
**files** `tuple[str, ...]`
**position\_version** `int`
**session\_cwd** `str | None`
**request** `RunRequest`
[`RunRequest`](./execution#contree_sdk.execution.RunRequest)
**session\_id** `str`
**image\_uuid** `str`
**parent\_id** `str | None`
**branch** `str | None`
**node\_id** `str`
**created\_at** `float`
**session\_env** `Mapping[str, str]`
## `class OperationContract`
```python theme={null}
class contree_sdk.session.OperationContract()
```
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
### Attributes
**uuid** `str`
**context** `OperationContext | None`
[`OperationContext`](./execution#contree_sdk.execution.OperationContext) | None
**response** `OperationResponse | None`
### Methods
#### `add_observer()`
```python theme={null}
def add_observer(observer) -> None
```
Register an observer before starting the shared operation reader.
A None event marks EOF, with an optional stream error. Observers must
not consume events or wait for this operation. Implementations without
this optional facility reject registration.
**observer** *required*
**returns** `None`
#### `apply_files()`
```python theme={null}
@abstractmethod
def apply_files(files) -> None
```
**files** *required*
**returns** `None`
#### `cancel()`
```python theme={null}
@abstractmethod
def cancel() -> None
```
**returns** `None`
#### `events()`
```python theme={null}
@abstractmethod
def events(*, since, spid, timeout) -> Iterator[OperationEvent]
```
**since** (default: None)
**spid** (default: None)
**timeout** (default: None)
**returns** `Iterator[OperationEvent]`
#### `pipe_stdin()`
```python theme={null}
@abstractmethod
def pipe_stdin(chunks, *, spid, close, chunk_size) -> StdinResult
```
**chunks** *required*
**spid** (default: 1)
**close** (default: True)
**chunk\_size** (default: 65536)
**returns** `StdinResult`
[`StdinResult`](./session#contree_sdk.session.StdinResult)
#### `run()`
```python theme={null}
@abstractmethod
def run(command, *, shell, args, env, cwd, uid, gid, stdin, stdin_open, truncate_output_at) -> SubprocessContract
```
**command** *required*
**shell** (default: False)
**args** (default: ())
**env** (default: None)
**cwd** (default: None)
**uid** (default: None)
**gid** (default: None)
**stdin** (default: None)
**stdin\_open** (default: False)
**truncate\_output\_at** (default: None)
**returns** `SubprocessContract`
[`SubprocessContract`](./execution#contree_sdk.session.contracts.SubprocessContract)
#### `send_stdin()`
```python theme={null}
@abstractmethod
def send_stdin(data, *, spid, close) -> None
```
**data** *required*
**spid** (default: 1)
**close** (default: True)
**returns** `None`
#### `shutdown()`
```python theme={null}
@abstractmethod
def shutdown() -> None
```
**returns** `None`
#### `signal()`
```python theme={null}
@abstractmethod
def signal(sig, *, spid) -> None
```
**sig** (default: None)
**spid** (default: 1)
**returns** `None`
#### `status()`
```python theme={null}
@abstractmethod
def status(*, inflight) -> OperationResponse
```
**inflight** (default: False)
**returns** `OperationResponse`
#### `wait()`
```python theme={null}
@abstractmethod
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class OperationRecord`
```python theme={null}
class contree_sdk.session.OperationRecord(*, uuid, session_id, image_uuid, parent_id, branch, title, disposable, request, endpoint, created_at, node_id, session_cwd, session_env, files, attachments, response, history_id)
```
A registered operation and its first atomically completed outcome.
request holds the effective command, excluding source streams. A non-null
response marks completion, including failed, cancelled, and discarded
results. history\_id is set only when that completion retained an image.
### Attributes
**attachments** `tuple[StagedFile, ...]`
tuple\[[`StagedFile`](./files#contree_sdk.files.StagedFile), ...]
**created\_at** `float`
**endpoint** `str`
**files** `tuple[str, ...]`
**history\_id** `str | None`
**node\_id** `str`
**pending** `bool`
**response** `dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]] | None`
**session\_cwd** `str | None`
**uuid** `str`
**session\_id** `str`
**image\_uuid** `str`
**parent\_id** `str`
**branch** `str`
**title** `str`
**disposable** `bool`
**request** `dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]]`
**session\_env** `dict[str, str]`
### Methods
#### `from_dict()`
```python theme={null}
@classmethod
def from_dict(payload) -> OperationRecord
```
**payload** *required*
**returns** `OperationRecord`
[`OperationRecord`](./session#contree_sdk.session.OperationRecord)
#### `to_dict()`
```python theme={null}
def to_dict() -> dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]]
```
**returns** `dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]]`
## `class PendingRun`
```python theme={null}
class contree_sdk.session.PendingRun(session, request, *, branch)
```
One-use execution wrapper. Await a result or enter an operation context.
### Methods
#### `commit()`
```python theme={null}
async def commit(operation) -> None
```
**operation** *required*
**returns** `None`
#### `run_to_result()`
```python theme={null}
async def run_to_result() -> InstanceResult
```
**returns** `InstanceResult`
#### `spawn()`
```python theme={null}
async def spawn() -> AsyncOperationContract
```
**returns** `AsyncOperationContract`
[`AsyncOperationContract`](./execution#contree_sdk.session.contracts.AsyncOperationContract)
## `class RunRequest`
```python theme={null}
class contree_sdk.session.RunRequest(*, command, shell, args, env, cwd, stdin, stdin_open, files, timeout, disposable, truncate_output_at, preserve_env, hostname, uid, gid, resources_limits, networking)
```
Command configuration passed through the session’s public extension hooks.
Use `dataclasses.replace` to change a request. Arguments and environment
are copied at construction. File sources and stdin remain caller-owned.
Exactly one of `command` and `shell` must be supplied. Results are saved
by default; use `disposable=True` to leave session history unchanged.
### Attributes
**args** `tuple[str, ...]`
**command** `str | None`
**cwd** `str | None`
**disposable** `bool`
**env** `Mapping[str, str] | None`
**files** `list[str | Path | UploadFileSpec] | dict[str, str | Path | bytes | UploadFileSpec] | None`
list\[str | Path | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)] | dict\[str, str | Path | bytes | [`UploadFileSpec`](./files#contree_sdk.files.UploadFileSpec)] | None
**gid** `int | None`
**hostname** `str | None`
**networking** `InstanceNetworking | None`
**preserve\_env** `bool`
**resources\_limits** `InstanceResourcesLimits | None`
**shell** `str | None`
**stdin** `str | bytes | Path | Readable[str] | Readable[bytes] | AsyncReadable[str] | AsyncReadable[bytes] | None`
str | bytes | Path | [`Readable`](./files#contree_sdk.files.Readable)\[str] | [`Readable`](./files#contree_sdk.files.Readable)\[bytes] | [`AsyncReadable`](./files#contree_sdk.files.AsyncReadable)\[str] | [`AsyncReadable`](./files#contree_sdk.files.AsyncReadable)\[bytes] | None
**stdin\_open** `bool`
**timeout** `float | timedelta | None`
**timeout\_seconds** `float | None`
**title** `str`
**truncate\_output\_at** `int | None`
**uid** `int | None`
## `class SnapshotEvent`
```python theme={null}
class contree_sdk.session.SnapshotEvent(*values)
```
Notifications for one policy instance owned by one lazy session.
RESET starts a new VM cycle. VM\_STARTING precedes the VM spawn request.
COMMAND\_STARTED reserves an accepted command
before its subprocess is created. COMMAND\_FINISHED confirms its exit event,
including nonzero exits. INSPECTION\_STARTED/FINISHED bracket a live filesystem
request, including its stream. They affect idle time, not command counts.
CLOSE releases resources after completion or failure.
### Attributes
**RESET**
**VM\_STARTING**
**COMMAND\_STARTED**
**COMMAND\_FINISHED**
**INSPECTION\_STARTED**
**INSPECTION\_FINISHED**
**CLOSE**
## `class StdinResult`
```python theme={null}
class contree_sdk.session.StdinResult(bytes_sent, eof_sent, process_exited)
```
Acknowledged input bytes and whether EOF was sent or the process ended.
A successful write does not prove that the remote process read the bytes.
An ambiguous transport error raises instead of returning a partial result.
### Attributes
**bytes\_sent** `int`
**eof\_sent** `bool`
**process\_exited** `bool`
## `class SubprocessContract`
```python theme={null}
class contree_sdk.session.SubprocessContract()
```
Waitable event stream for one subprocess. Iteration and wait share completion state.
### Attributes
**spid** `int`
### Methods
#### `pipe_to()`
```python theme={null}
@abstractmethod
def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
#### `wait()`
```python theme={null}
@abstractmethod
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class SubprocessHandle`
```python theme={null}
class contree_sdk.session.SubprocessHandle(operation, spid, events_queue)
```
Both blocking-waitable (final result) and iterable (live events) for one spid.
### Attributes
**spid** `int`
### Methods
#### `pipe_to()`
```python theme={null}
def pipe_to(*, stdout, stderr) -> InstanceResult
```
**stdout** (default: None)
**stderr** (default: None)
**returns** `InstanceResult`
#### `wait()`
```python theme={null}
def wait(*, timeout) -> InstanceResult
```
**timeout** (default: None)
**returns** `InstanceResult`
## `class ZeroExitCommitPolicy`
```python theme={null}
class contree_sdk.session.ZeroExitCommitPolicy()
```
Retain a result only when its process exit code is explicitly zero.
### Methods
#### `should_commit()`
```python theme={null}
def should_commit(context, result) -> bool
```
**context** *required*
**result** *required*
**returns** `bool`
## `instance_result()`
```python theme={null}
def contree_sdk.session.instance_result(op) -> InstanceResult
```
Get the operation’s InstanceResult.
**op** *required*
**returns** `InstanceResult`
The InstanceResult from op.metadata.result.
**raises**
**InterruptedError** – The operation was cancelled.
**raises**
[**FailedOperationError**](./exceptions#contree_sdk.exceptions.FailedOperationError) – The operation itself failed with no result at all
(a nonzero exit code inside a successful operation is not an error).
# Tree stores
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/store
For a step-by-step introduction to memory, SQLite, and continuing saved sessions,
start with [Save and resume a session](../sessions). To implement another backend, see
[Implement a custom Store](../custom-store) in Advanced Usage.
`SyncStore` and `AsyncStore` store immutable trees. Sessions, Docker builds, and
upload reuse share one Store. Helpers and direct
constructors accept it through `store=`. The Store holds references; images and files remain
on the ConTree server.
## Nodes and tree kinds
A `Node` contains `id`, `parent_id`, `kind`, and JSON-object `data`. Its generated
ID identifies a record, not a command, image, timestamp, or execution order.
Retain the same Node when retrying a write. Two executions can have equal inputs
and still produce different nodes.
A tree has one root and an immutable string `kind`. Standard consumers use
`session`, `docker-build`, `upload-cache`, and `file-sources`. Applications can
supply their own kinds. A node’s kind describes its step, such as `run`, `stage`,
or `config`. Tree kinds let a CLI exclude service histories before pagination.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk.store import Node, SyncMemoryStore
>
> with SyncMemoryStore() as store:
> store.create_session("example", kind="session", ttl=3600)
> root = Node(parent_id=None, kind="init", data={"image_uuid": "base-image"})
> store.append("example", root)
> first = Node(parent_id=root.id, kind="run", data={"user": {"label": "first"}})
> second = Node(parent_id=root.id, kind="run", data={"user": {"label": "second"}})
> store.append("example", first)
> store.append("example", second)
> store.append("example", first) # A repeated delivery creates no duplicate.
> assert store.get_nodes("example", (first.id, "missing")) == (first, None)
> assert len(store.list_children("example", root.id).items) == 2
> page = store.list_sessions(kind="session", limit=20)
> assert page.items[0].session_id == "example"
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk.store import AsyncMemoryStore, Node
>
> async with AsyncMemoryStore() as store:
> await store.create_session("example", kind="session", ttl=3600)
> root = Node(parent_id=None, kind="init", data={"image_uuid": "base-image"})
> await store.append("example", root)
> first = Node(parent_id=root.id, kind="run", data={"user": {"label": "first"}})
> second = Node(parent_id=root.id, kind="run", data={"user": {"label": "second"}})
> await store.append("example", first)
> await store.append("example", second)
> await store.append("example", first)
> assert len((await store.list_children("example", root.id)).items) == 2
> page = await store.list_sessions(kind="session", limit=20)
> assert page.items[0].session_id == "example"
> ```
## Contract
* `create_session()` creates an empty tree. Repeating it with the same kind returns
the existing tree without renewing its TTL. A different kind raises `ValueError`.
* `append()` requires a live tree and a parent in that tree, except for its root.
It atomically inserts one node. Equal identity and contents succeed on retry;
changed contents or a second root raise `NodeConflictError` without overwriting.
* Reads return independent JSON values. Mutating a returned dictionary does not
modify storage. Updating a saved node requires a new node.
* Calls are atomic across clients sharing a backend. A successful write is
visible to subsequent reads from any client, unless deletion or expiry removes
the tree. Concurrent calls may take either order. Separate calls are not a
transaction. A lost response leaves the write outcome unknown; retry an append
with the same prepared Node.
* `get_session()` returns `None` for a missing or expired tree. Reading a missing
node or appending to a missing tree raises `ValueError`.
* `get_nodes(session_id, node_ids)` reads up to 1000 identities in one atomic
call. The returned tuple preserves input order and duplicates. Missing nodes
occupy `None` slots. A missing or expired tree raises `ValueError`, including
for an empty batch. Each returned node contains independent JSON values.
* `list_sessions()`, `list_nodes()`, and `list_children()` filter before pagination
and order by identity. `list_history()` follows parents from the specified node.
Pass `next_cursor` with the same selection; `None` means the end. Pages are live
reads and do not share a snapshot across calls.
* List methods request 1000 items by default. A backend can return fewer items
with a continuation cursor to bound response size. Always follow `next_cursor`;
a short page does not imply the end. Treat cursors as opaque positions. They
are not authorization tokens; a remote backend must check access separately.
* TTL belongs to the whole tree. `set_session_ttl()` sets a new expiry from now.
Reads and append do not renew it. `ttl=None` uses the implementation policy;
the supplied Memory and SQLite implementations retain the tree until deletion.
Zero expires immediately; negative or nonfinite TTL raises `ValueError`.
* `delete_session()` removes the tree and returns whether stored data existed,
including expired data. It does not delete remote images or cancel operations.
A late append cannot recreate a deleted tree. Explicit creation can reuse its
name; use a new session ID when a new lifetime must remain distinguishable.
## Execution belongs to Session
The Store has no selected branch or shared head. Each Session keeps its own
position and local branch names. Two actors executing from the same parent add
two children. A late result keeps its captured parent even after local navigation.
Use separate Session instances for independent actors. Serialize navigation when
sharing one Session across threads. See [Branch, switch, and roll back](../branching) and [Save and resume a session](../sessions)
for selection and explicit resume.
For a live tree with root `R`, actors can append `R → A` and `R → B` in either
order. Both nodes remain available. Each actor can then extend its own node or
explicitly select a node written by another actor. Repeating the same append
adds no duplicate. Changing a node’s parent or data under the same ID raises
`NodeConflictError`. This holds for any number of actors because each successful
append adds one node without changing existing nodes.
Each actor must retain its selected `(session_id, node_id)` and the prepared
Node for a retry. Use explicit `node_id` when opening a shared session;
automatic selection is not a durable actor position. Store does not merge
filesystem changes or make VM execution exactly once.
An identity cursor is not an event subscription. Concurrent inserts with IDs
before that cursor will not appear in the remaining pages. Restart enumeration
to discover them, or exchange explicit node IDs between actors. The ancestry of
a known node is stable while other actors append, so `list_history()` can page
that path without mixing branches. Deletion and expiry can still interrupt it.
Pending operations and their completions are immutable nodes too. A completion
node contains the response and retained image, so atomic append also protects
completion from partial writes. See [Advanced: resume a background operation](../detached-operations).
Session lists operation registrations by page and reads their completion nodes
with `get_nodes()`. It does not fetch each registration again. Successful image
commits record a `staging_complete` marker in the SDK payload. Staging recovery
stops there because that image contains all staged inputs captured for the
operation. Older records remain readable through ancestry traversal. Failed or
discarded operations do not consume their source staging.
Docker searches `run` children of the selected parent and `use` nodes for FROM.
It still checks Docker hashes in the client. Large sibling sets and accumulated
FROM records can require multiple pages. Opening a session without `node_id`
still enumerates its tree to detect ambiguous continuation; pass `node_id` when
resuming a known position.
Custom backends implement this contract through `SyncStore` or `AsyncStore`.
Atomicity must cover all clients, including separate processes and connections.
An SDK-side lock alone does not meet that requirement. Memory uses SQLite’s
in-memory engine; SQLite stores persist to a file. `AsyncSQLiteStore` uses
`aiosqlite`. Existing databases from earlier experimental contracts are not
migrated into these trees.
## `class AsyncMemoryStore`
```python theme={null}
class contree_sdk.store.AsyncMemoryStore(*, clock)
```
### Methods
#### `append()`
```python theme={null}
async def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
async def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
async def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
async def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
async def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
async def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
async def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
async def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
async def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
async def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
async def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
async def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
## `class AsyncSQLiteStore`
```python theme={null}
class contree_sdk.store.AsyncSQLiteStore(db_path, *, clock)
```
Native aiosqlite implementation of the same tree contract.
### Methods
#### `append()`
```python theme={null}
async def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
async def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
async def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
async def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
async def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
async def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
async def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
async def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
async def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
async def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
async def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
async def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
## `class AsyncStore`
```python theme={null}
class contree_sdk.store.AsyncStore()
```
Async equivalent of SyncStore with the same guarantees.
### Methods
#### `append()`
```python theme={null}
def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
## `class Node`
```python theme={null}
class contree_sdk.store.Node(*, parent_id, kind, data, id)
```
### Attributes
**parent\_id** `str | None`
**kind** `str`
**data** `dict[str, str | int | float | bool | None | list[str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]] | dict[str, str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue]]]`
**id** `str`
## `exception NodeConflictError`
```python theme={null}
exception contree_sdk.store.NodeConflictError()
```
An identity already names a different node, or the tree already has a root.
### Attributes
**args**
### Methods
#### `add_note()`
```python theme={null}
def add_note(note, /)
```
Add a note to the exception
#### `with_traceback()`
```python theme={null}
def with_traceback(tb, /)
```
Set self.**traceback** to tb and return self.
**NodeId**
alias of `str`
## `class Page`
```python theme={null}
class contree_sdk.store.Page(items, next_cursor)
```
### Attributes
**next\_cursor** `str | None`
**items** `tuple[TypeVar(T), ...]`
## `class SessionInfo`
```python theme={null}
class contree_sdk.store.SessionInfo(session_id, kind, created_at, expires_at)
```
### Attributes
**session\_id** `str`
**kind** `str`
**created\_at** `float`
**expires\_at** `float | None`
## `class SyncMemoryStore`
```python theme={null}
class contree_sdk.store.SyncMemoryStore(*, clock)
```
### Methods
#### `append()`
```python theme={null}
def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
## `class SyncSQLiteStore`
```python theme={null}
class contree_sdk.store.SyncSQLiteStore(db_path, *, clock)
```
Persist trees. None TTL means no expiry for this implementation.
### Methods
#### `append()`
```python theme={null}
def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
## `class SyncStore`
```python theme={null}
class contree_sdk.store.SyncStore()
```
Store independent trees with atomic, idempotent node insertion.
Repeating create\_session with the same kind returns the existing tree without
renewing TTL. append requires a live tree and an existing parent, except for
its single root. Repeating an identical node succeeds; changed data conflicts.
Reads return detached JSON. Node IDs are identities, not execution order.
Pages use stable identity order; they are live reads, not a shared snapshot.
None TTL delegates retention to the implementation.
Calls are atomic across clients sharing a backend. Once a write succeeds,
subsequent reads through any client observe it unless the tree was deleted
or expired. Concurrent calls may take either order; separate calls do not
form a transaction. A lost response does not imply that the write failed.
Retry append with the same node identity, parent, kind, and data.
### Methods
#### `append()`
```python theme={null}
@abstractmethod
def append(session_id, node) -> None
```
**session\_id** *required*
**node** *required*
**returns** `None`
#### `close()`
```python theme={null}
@abstractmethod
def close() -> None
```
**returns** `None`
#### `create_session()`
```python theme={null}
@abstractmethod
def create_session(session_id, *, kind, ttl) -> SessionInfo
```
**session\_id** *required*
**kind** (default: 'session')
**ttl** (default: None)
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
#### `delete_session()`
```python theme={null}
@abstractmethod
def delete_session(session_id) -> bool
```
**session\_id** *required*
**returns** `bool`
#### `get_node()`
```python theme={null}
@abstractmethod
def get_node(session_id, node_id) -> Node
```
**session\_id** *required*
**node\_id** *required*
**returns** `Node`
[`Node`](./store#contree_sdk.store.Node)
#### `get_nodes()`
```python theme={null}
@abstractmethod
def get_nodes(session_id, node_ids) -> tuple[Node | None, ...]
```
Read up to 1000 identities atomically, preserving input order and duplicates.
Missing nodes occupy None slots. A missing or expired tree raises ValueError,
including for an empty batch. Returned nodes contain independent JSON.
**session\_id** *required*
**node\_ids** *required*
**returns** `tuple[Node | None, ...]`
tuple\[[`Node`](./store#contree_sdk.store.Node) | None, ...]
#### `get_session()`
```python theme={null}
@abstractmethod
def get_session(session_id) -> SessionInfo | None
```
**session\_id** *required*
**returns** `SessionInfo | None`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo) | None
#### `list_children()`
```python theme={null}
@abstractmethod
def list_children(session_id, parent_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**parent\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_history()`
```python theme={null}
@abstractmethod
def list_history(session_id, from_node, *, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**from\_node** *required*
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_nodes()`
```python theme={null}
@abstractmethod
def list_nodes(session_id, *, kind, limit, cursor) -> Page[Node]
```
**session\_id** *required*
**kind** (default: None)
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[Node]`
[`Page`](./store#contree_sdk.store.Page)\[[`Node`](./store#contree_sdk.store.Node)]
#### `list_sessions()`
```python theme={null}
@abstractmethod
def list_sessions(*, kind, prefix, limit, cursor) -> Page[SessionInfo]
```
**kind** (default: None)
**prefix** (default: '')
**limit** (default: 1000)
**cursor** (default: None)
**returns** `Page[SessionInfo]`
[`Page`](./store#contree_sdk.store.Page)\[[`SessionInfo`](./store#contree_sdk.store.SessionInfo)]
#### `set_session_ttl()`
```python theme={null}
@abstractmethod
def set_session_ttl(session_id, ttl) -> SessionInfo
```
**session\_id** *required*
**ttl** *required*
**returns** `SessionInfo`
[`SessionInfo`](./store#contree_sdk.store.SessionInfo)
# Work with a Session
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/session-model
The `session` returned by `create_sandbox_session` runs commands, saves
checkpoints, and switches between branches. Use the connection from
[Your first sandbox](./getting-started).
## Run commands and save a checkpoint
These two commands share one VM. `snapshot()` is a lightweight operation that
saves their files and stops the running VM. The next command starts from the
saved image. You can snapshot as often as needed, including after every command.
If the filesystem has not changed, a snapshot can return the same `image_uuid`.
This is normal: a new checkpoint does not require a new image UUID.
> [tab] Sync
>
> ```python theme={null}
> """Save filesystem changes as a session checkpoint."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as session:
> # Start a VM and prepare files shared by both commands.
> session.run("mkdir", args=["-p", "/work"])
> session.run(shell="echo ready > /work/status.txt")
>
> # Save both commands as one checkpoint and stop the VM.
> checkpoint = session.snapshot()
> assert checkpoint is not None
> print(checkpoint.image_uuid)
>
> # Start a new VM from the checkpoint. The file is still there.
> session.run(shell="cat /work/status.txt")
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as session:
> # Start a VM and prepare files shared by both commands.
> await session.run("mkdir", args=["-p", "/work"])
> await session.run(shell="echo ready > /work/status.txt")
>
> # Save both commands as one checkpoint and stop the VM.
> checkpoint = await session.snapshot()
> assert checkpoint is not None
> print(checkpoint.image_uuid)
>
> # Start a new VM from the checkpoint. The file is still there.
> await session.run(shell="cat /work/status.txt")
>
>
> asyncio.run(main())
> ```
The program prints the saved image UUID. Files survive a snapshot; processes and
memory do not. Normal context exit saves pending work. An exception aborts unsaved
work; completed snapshots remain available.
The default policy also saves after 10 idle seconds. Each snapshot is one
checkpoint, even when it contains several commands.
## Save after every command
Pass `session_type=ContreeSession` or `ContreeAsyncSession` to save each command
automatically. Each command runs in a separate VM, which stops when it finishes.
The next command starts from the saved image. No explicit `snapshot()` is needed.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(image="tag:alpine:latest", session_type=ContreeSession) as session:
> # Write a file. The command finishes and saves its image automatically.
> session.run(shell="echo ready > /status.txt")
>
> # Start another VM from that image and read the saved file.
> result = session.run("cat", args=["/status.txt"])
> print(result.stdout)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async with create_sandbox_session(image="tag:alpine:latest", session_type=ContreeAsyncSession) as session:
> # Write a file. The command finishes and saves its image automatically.
> await session.run(shell="echo ready > /status.txt")
>
> # Start another VM from that image and read the saved file.
> result = await session.run("cat", args=["/status.txt"])
> print(result.stdout)
> ```
Set `disposable=True` on a command to leave the session image unchanged. The
default commit policy saves completed operations even when the command exits
with a nonzero code. Failed or cancelled operations do not advance history.
Use the default `LazySession` when commands need the same running processes.
It keeps the VM until a snapshot. Choose snapshot frequency to match the required
checkpoints and process lifetime. An unchanged filesystem can produce
the same image UUID in either mode.
## Start a new session from a snapshot
Each session builds an independent chain of saved images. Only the Store records
the links between history nodes and the positions of branches. An `image_uuid`
identifies saved files; it does not carry SDK session history.
You can start any number of new sessions from any history node’s `image_uuid`,
or from any other image UUID you can access. Each session has its own history.
Changes in one session do not change the source image or other sessions.
> [tab] Sync
>
> ```python theme={null}
> """Use a saved image as the starting point of an independent session."""
>
> from contree_sdk import create_sandbox_session
>
>
> def main() -> None:
> # Prepare files in the original session and save their image UUID.
> with create_sandbox_session(image="tag:alpine:latest") as source:
> source.run(shell="echo baseline > /choice.txt")
> checkpoint = source.snapshot()
> assert checkpoint is not None
> image_uuid = checkpoint.image_uuid
>
> # Create a new session with those files and its own history.
> with create_sandbox_session(image=image_uuid) as fork:
> assert fork.session_id != source.session_id
> result = fork.run("cat", args=["/choice.txt"])
> print(result.stdout)
>
> # Change only the new session. The source image stays unchanged.
> fork.run(shell="echo experiment > /choice.txt")
>
>
> main()
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
>
>
> async def main() -> None:
> # Prepare files in the original session and save their image UUID.
> async with create_sandbox_session(image="tag:alpine:latest") as source:
> await source.run(shell="echo baseline > /choice.txt")
> checkpoint = await source.snapshot()
> assert checkpoint is not None
> image_uuid = checkpoint.image_uuid
>
> # Create a new session with those files and its own history.
> async with create_sandbox_session(image=image_uuid) as fork:
> assert fork.session_id != source.session_id
> result = await fork.run("cat", args=["/choice.txt"])
> print(result.stdout)
>
> # Change only the new session. The source image stays unchanged.
> await fork.run(shell="echo experiment > /choice.txt")
>
>
> asyncio.run(main())
> ```
Reuse `image_uuid` in further `create_sandbox_session(image=image_uuid)` calls to
start more independent sessions. The source session can already be closed.
The new sessions do not inherit its history, branch names, or Store metadata.
If you share a Store, omit `session_id` to generate a new ID, or supply an unused
ID. An existing ID resumes that session instead; see [Save and resume a session](./sessions).
## Continue with a task
* [Branch, switch, and roll back](./branching): create a branch, compare results, and roll back a checkpoint.
* [Save and resume a session](./sessions): keep history in SQLite and resume after Python exits.
* [Work with sandbox files](./files): upload inputs and read saved files.
History uses an in-memory Store by default. To resume later, supply a SQLite
Store and a stable `session_id`. Filesystem images remain on the ConTree server.
# Save and resume a session
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/sessions
A session runs commands and records saved states in a **Store**. The Store keeps
the session’s history and references to its filesystem images. ConTree keeps the
images on the server. To continue later, open the same Store and select the same
session.
This guide starts with memory storage, then saves work in SQLite and opens it
again. Configure your connection as described in [Connection sources](./getting-started#sandbox-connection).
Async SQLite examples require the `contree-sdk[async]` extra.
## 1. Choose where to keep history
Store is a storage interface. The SDK includes two implementations:
| Store | Where history lives | When to use it |
| - | - | - |
| `SyncMemoryStore` / `AsyncMemoryStore` | In memory, while that Store remains open | Work within one Python program. |
| `SyncSQLiteStore` / `AsyncSQLiteStore` | In a local SQLite file | Continue work after Python exits. |
Without `store=`, `create_sandbox_session()` creates a memory Store for that
context. To share history between contexts, create a Store yourself and pass it
through `store=`. The outer context below keeps that Store open until both
sessions have finished.
Both sessions use `session_id="demo"`. The second context opens the first
session’s saved state and reads its file.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SyncMemoryStore
>
> with SyncMemoryStore() as store:
> with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="demo") as session:
> session.run(shell="echo saved > /saved.txt")
>
> with create_sandbox_session(store=store, session_id="demo") as session:
> content = session.read_file("/saved.txt")
> print(content.decode())
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncMemoryStore
>
>
> async def main() -> None:
> async with AsyncMemoryStore() as store:
> async with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="demo") as session:
> await session.run(shell="echo saved > /saved.txt")
>
> async with create_sandbox_session(store=store, session_id="demo") as session:
> content = await session.read_file("/saved.txt")
> print(content.decode())
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
saved
```
Closing the memory Store discards its history. A new memory Store starts empty,
even if you reuse the same session ID. Use SQLite to keep history between runs.
## 2. Save work in a SQLite file
Replace the memory Store with a SQLite Store. This program creates `sessions.db`
in the current directory and records a session named `my-project`.
Run this program first. Normal exit from the session context saves the filesystem
changes and records the saved image in the Store. Then the outer context closes
the database.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SyncSQLiteStore
>
> with SyncSQLiteStore("sessions.db") as store:
> with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="my-project") as session:
> session.run(shell="echo saved > /saved.txt")
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async def main() -> None:
> async with AsyncSQLiteStore("sessions.db") as store:
> async with create_sandbox_session(image="tag:alpine:latest", store=store, session_id="my-project") as session:
> await session.run(shell="echo saved > /saved.txt")
>
>
> asyncio.run(main())
> ```
There are now two different files: `sessions.db` is local history, and
`/saved.txt` is inside the filesystem image stored by ConTree. The SQLite file
does not contain a copy of that filesystem.
## 3. Continue in another program
Run this second program from the same directory. It opens the existing database
and selects `my-project`. No `image=` argument is needed: the session gets its
saved image from the Store.
The command reads the file created by the first program. You can run more
commands in this context; normal exit saves their filesystem changes too.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SyncSQLiteStore
>
> with SyncSQLiteStore("sessions.db") as store:
> with create_sandbox_session(store=store, session_id="my-project") as session:
> result = session.run("cat", args=["/saved.txt"])
> print(result.stdout)
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async def main() -> None:
> async with AsyncSQLiteStore("sessions.db") as store:
> async with create_sandbox_session(store=store, session_id="my-project") as session:
> result = await session.run("cat", args=["/saved.txt"])
> print(result.stdout)
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
saved
```
Keep the same database path, session ID, and access to the same ConTree server
and project. A different working directory can make `"sessions.db"` refer to a
different file. Use an absolute path when programs run from different directories.
An unknown session ID without `image=` raises `ValueError`. If you provide an
image and an unused ID, the SDK creates a new session. An existing ID resumes its
saved state even when you pass `image=`. Use a new ID for independent work.
## 4. Keep several sessions in one file
One Store can hold many sessions. Each `session_id` identifies a separate history
within that Store. These two sessions start from the same base image, then save
different contents at the same path.
Run this program to create a separate `projects.db` for the next steps.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SyncSQLiteStore
>
> with SyncSQLiteStore("projects.db") as store:
> for name in ("project-a", "project-b"):
> with create_sandbox_session(image="tag:alpine:latest", store=store, session_id=name) as session:
> session.run(shell=f"echo {name} > /project.txt")
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async def main() -> None:
> async with AsyncSQLiteStore("projects.db") as store:
> for name in ("project-a", "project-b"):
> async with create_sandbox_session(image="tag:alpine:latest", store=store, session_id=name) as session:
> await session.run(shell=f"echo {name} > /project.txt")
>
>
> asyncio.run(main())
> ```
The shared database does not combine the files or histories of these sessions.
Omit `session_id` to generate a new ID automatically; read `session.session_id`
if you need to keep that ID.
## 5. Find a saved session
Open the database and call `list_sessions(kind="session")`. The filter selects
user session histories and excludes records used for builds or upload reuse.
Listing stored sessions does not start a VM or contact ConTree.
Results arrive in pages. Print each page, then pass `next_cursor` to read the next
one. Stop when it is `None`. This example requests one item per page so you can
see pagination with just two sessions; increase `limit` for larger lists.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk.store import SyncSQLiteStore
>
> with SyncSQLiteStore("projects.db") as store:
> cursor = None
> while True:
> page = store.list_sessions(kind="session", limit=1, cursor=cursor)
> for saved in page.items:
> print(saved.session_id)
> cursor = page.next_cursor
> if cursor is None:
> break
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async def main() -> None:
> async with AsyncSQLiteStore("projects.db") as store:
> cursor = None
> while True:
> page = await store.list_sessions(kind="session", limit=1, cursor=cursor)
> for saved in page.items:
> print(saved.session_id)
> cursor = page.next_cursor
> if cursor is None:
> break
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
project-a
project-b
```
The list is ordered by session ID, not by last activity. Each item also contains
`created_at` and `expires_at`. Pass `prefix="project-"` to select IDs with that
prefix.
## 6. Continue the session you chose
Copy an ID from the list into `session_id`. This program selects `project-b` and
reads its saved file. To open `project-a`, change only that ID.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import SyncSQLiteStore
>
> with SyncSQLiteStore("projects.db") as store:
> with create_sandbox_session(store=store, session_id="project-b") as session:
> content = session.read_file("/project.txt")
> print(content.decode())
> ```
> [tab] Async
>
> ```python theme={null}
> import asyncio
>
> from contree_sdk import create_sandbox_session
> from contree_sdk.store import AsyncSQLiteStore
>
>
> async def main() -> None:
> async with AsyncSQLiteStore("projects.db") as store:
> async with create_sandbox_session(store=store, session_id="project-b") as session:
> content = await session.read_file("/project.txt")
> print(content.decode())
>
>
> asyncio.run(main())
> ```
Output:
```text theme={null}
project-b
```
## Resume a selected node
The examples above each have one continuation, so a session ID is enough.
After branching, a history can contain several continuations. The SDK then
raises `ValueError` unless you pass `node_id=` to select a saved state.
Keep the entry ID returned by `snapshot()` when you need an exact checkpoint.
Pass it as `node_id=` together with `session_id=` when reopening. A session ID
selects the history; a node ID selects a point within that history. See
[Branch, switch, and roll back](./branching) for checkpoints and branches.
The Store does not retain the last selected position or local branch names.
Even with one continuation, reopening can select a later saved state than the
one you selected with `rollback()`. Keep the selected node ID for exact resume.
Independent clients can resume the same node and create separate continuations.
## What must remain available?
* Keep the SQLite database and access to the same ConTree server and project.
* Keep the referenced images on that server. SQLite cannot restore a deleted image.
* Save filesystem changes before stopping Python. Normal context exit saves them;
`snapshot()` saves an earlier checkpoint. An exception discards changes since
the last completed snapshot. Abrupt process termination does not guarantee a save.
* Snapshots save files, not running processes or VM memory. Continuing a session
starts new processes from the saved filesystem.
An unchanged filesystem can produce the same image UUID at several checkpoints.
History entry IDs still distinguish them. For automatic saving after each
command, see [Save after every command](./session-model#save-after-every-command).
A nonzero command exit code can still produce a saved image; inspect the result
before continuing or rolling back.
## Use another storage backend
For your own database or service, implement `SyncStore` or `AsyncStore` and pass
the object through `store=`. See [Implement a custom Store](./custom-store) in Advanced Usage for an
example and the implementation requirements.
The application closes any Store it supplies. Keep the Store context outside all
session contexts that use it, as in these examples. See [Advanced: assemble a sandbox yourself](./manual-sandbox) for
explicit component construction and cleanup, and [Tree stores](./reference/store) for the
complete storage API.
# Handle failures and unexpected state
Source: https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/troubleshooting
| Symptom | Check or action |
| - | - |
| Authentication or profile error | Check the URL, token, and AI project; see [Connection sources](./getting-started#sandbox-connection). |
| Unknown image tag | Import the image on the selected endpoint; see [Import a Docker image](./images). |
| A file from the previous command disappeared | For explicit `ContreeSession`, check that `disposable=True` was not requested. For a lazy sandbox, check whether an exception discarded unsaved work. |
| Work disappeared after Python restarted | Resume the same `session_id` from the same SQLite database. |
| Explicit async session has no `image_uuid` yet | Await `ensure_ready()` or a session operation before reading it. |
| `ValueError` when resuming | Supply a base image for a new tree, or `node_id` when existing history has multiple leaves. |
| A completed result did not become current | A newer local selection exists; select the saved result explicitly as shown below. |
| `NotImplementedError` from async sandbox sync methods | Use `aexecute`, `aupload_files`, or `adownload_files`. |
> [!NOTE]
>
> Async snippets with top-level `await` run inside an async function or a notebook
> that supports it. For a standalone script, use the `asyncio.run(main())` structure
> from [Your first sandbox](./getting-started).
## Fail a sandbox workflow on a nonzero exit
A nonzero command exit returns a result. Calling `run_workflow()` below raises
inside the context, discards unsaved changes, and closes the VM.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
>
>
> def run_workflow() -> None:
> with create_sandbox_session(image="tag:alpine:latest") as sandbox:
> result = sandbox.run(shell="exit 7")
> if result.state.exit_code != 0:
> raise RuntimeError(f"Command failed with exit code {result.state.exit_code}")
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import create_sandbox_session
>
>
> async def run_workflow() -> None:
> async with create_sandbox_session(image="tag:alpine:latest") as sandbox:
> result = await sandbox.run(shell="exit 7")
> if result.state.exit_code != 0:
> raise RuntimeError(f"Command failed with exit code {result.state.exit_code}")
> ```
## Advanced: a command returned a nonzero exit code
This is a process result, so `run()` returns it without raising `FailedOperationError`.
The example uses disposable execution and leaves the session image unchanged.
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> result = session.run(shell="echo failed >&2; exit 7", disposable=True)
> if result.state.exit_code != 0:
> print(result.stderr)
> print("exit:", result.state.exit_code)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> result = await session.run(shell="echo failed >&2; exit 7", disposable=True)
> if result.state.exit_code != 0:
> print(result.stderr)
> print("exit:", result.state.exit_code)
> ```
Commands save by default. Inspect the exit code before continuing. A saved command
can have changed files even when its process exits nonzero. Roll back explicitly
if those changes should not remain selected.
## Advanced: select a late result
A completed operation retains its original parent. If local navigation or another
operation changes the selected position, committing the result saves a sibling
without selecting it. To save and select that result, give it a local branch name:
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> operation = session.spawn(shell="echo candidate > /value.txt")
> session.run(shell="echo newer > /value.txt")
> operation.wait()
> session.commit_result(operation, branch="recovered", title="Recovered result")
> print(session.image_uuid)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> operation = await session.spawn(shell="echo candidate > /value.txt")
> await session.run(shell="echo newer > /value.txt")
> await operation.wait()
> await session.commit_result(operation, branch="recovered", title="Recovered result")
> print(session.image_uuid)
> ```
Choose a fresh recovery branch name. The newer branch remains intact. The recovery
branch selects the completed operation’s image; it does not merge the two filesystems.
## Waiting failed, timed out, or was cancelled
`Operation.wait()` attempts cancellation when waiting raises and keeps the original
exception. A cancelled operation raises `InterruptedError`; an operation with no
successful result raises `FailedOperationError`. Client transport errors can also
propagate. Cleanup is best effort: retain the operation UUID if you need to inspect
its server status afterward.
A subprocess wait timeout does not itself terminate the whole operation. Use its
operation’s `signal()` or `cancel()`, or leave the operation context to shut it down.
See [Advanced: control a running sandbox](./operation) and [SDK exceptions](./reference/exceptions).
## Advanced: catch an operation failure
If the server cannot complete the operation, the SDK raises `FailedOperationError`
and leaves history unchanged. Keep the operation UUID to investigate the failure:
> [tab] Sync
>
> ```python theme={null}
> from contree_sdk import ContreeSession, create_sandbox_session
> from contree_sdk.exceptions import FailedOperationError
>
>
> with create_sandbox_session(session_type=ContreeSession, image="tag:alpine:latest") as session:
> try:
> session.run("echo", args=["hello"])
> except FailedOperationError as error:
> print("failed operation:", error.operation_uuid)
> ```
> [tab] Async
>
> ```python theme={null}
> from contree_sdk import ContreeAsyncSession, create_sandbox_session
> from contree_sdk.exceptions import FailedOperationError
>
>
> async with create_sandbox_session(session_type=ContreeAsyncSession, image="tag:alpine:latest") as session:
> try:
> await session.run("echo", args=["hello"])
> except FailedOperationError as error:
> print("failed operation:", error.operation_uuid)
> ```
# Choose an interface
Source: https://docs.tokenfactory.nebius.com/sandboxes/start/choose-an-interface
Choose between the Python SDK, REST API, CLI, and MCP for a Sandboxes workflow.
All interfaces start from an image and create operations. Choose based on how the caller needs to submit, observe, and control work.
| Need | Start with | Reason |
| - | - | - |
| Python application or agent integration | Python SDK | Python objects for images, commands, and final results. |
| Integration in another language, live events, or additional process control | REST API | Exact request and status schemas, resumable SSE, and subprocess endpoints. |
| Manual image exploration and shell workflows | CLI | Local profiles, sessions, filesystem inspection, and command-oriented workflows. |
| Tool access from an MCP-compatible client | MCP | Tools for commands, images, files, and operation polling. |
## Capability map
The examples and method names on this page use Python SDK 0.3.6 and CLI 0.9.4. For MCP, check the tools exposed by the server connected to your client.
| Task | Python SDK 0.3.6 | REST API | CLI 0.9.4 | MCP |
| - | - | - | - | - |
| Run a command and wait for its result | Async `await image.run(...)`; sync `run(...).wait()` | Submit, then poll until the operation reaches a terminal state | `contree run` | `run` with `wait=true` |
| Start work and inspect it later | Use REST when the application must receive an operation ID immediately | Submit and keep the returned operation ID | Use `contree run -d`, then `contree op wait OPERATION_ID`; see the [operation reference](/sandboxes/cli/commands/operation) | `run` with `wait=false`, then `get_operation` or `wait_operations` |
| Save or discard filesystem changes | Set `disposable=False` to save or `True` to discard | Send `disposable: false` to save or `true` to discard; the request schema defaults to `false` | Runs save by default; add `-D` to discard | Set `disposable=false` to save; the tool defaults to `true` |
| Stream operation events and resume after disconnect | Use REST; SDK 0.3.6 has no event-stream method | Subscribe with SSE and resume with `Last-Event-Id` | CLI 0.9.4 has no event-stream command | The exposed tool set has no event-stream tool |
| Start and control another process inside an active operation | Use REST; SDK 0.3.6 has no additional-process API | Use the spawn, stdin, EOF, result, and signal endpoints | CLI 0.9.4 has no additional-process command | The exposed tool set has no additional-process, stdin, or signal tool |
| Inspect files in a stored image without guest compute | Use `ls`, `read`, and `download` | Use the image inspection endpoints | Use `ls`, `cat`, and `cp` | Use `list_files`, `read_file`, and `download` |
## Interface boundaries
* A Python SDK 0.3.6 `run()` call prepares work; awaiting the returned object submits it and waits for the final result.
* A CLI session tracks a selected image and local workflow history. It does not keep a VM alive.
* REST is the reference for operation status, SSE events, and additional subprocesses.
* MCP capabilities depend on the tools exposed by the deployed server. Check the connected server before building a workflow around a specific tool.
Choose persistence before submission on every interface. See [Images, checkpoints, and branches](/sandboxes/concepts/images-checkpoints-and-branches) for defaults and result-image outcomes.
## Continue
* [Set up access](/sandboxes/start/set-up-access)
* [Python quickstart](/sandboxes/start/python-quickstart)
* [CLI quickstart](/sandboxes/start/cli-quickstart)
* [Run commands and handle results](/sandboxes/guides/run-commands-and-results)
* [Stream output and events](/sandboxes/guides/stream-output-and-events)
* [Run subprocesses and send input](/sandboxes/guides/run-subprocesses-and-send-input)
* [Reference map](/sandboxes/reference/index)
# CLI quickstart
Source: https://docs.tokenfactory.nebius.com/sandboxes/start/cli-quickstart
Install the Sandboxes CLI, configure a profile, and reuse saved filesystem state.
The CLI keeps a local session pointed at an image. This quickstart uses `contree-cli` 0.9.4 and `ubuntu:latest` to save a file in one operation and read it in the next.
**1. Install and authenticate**
Create an API key and copy the project ID as described in [Set up access](/sandboxes/start/set-up-access#create-an-api-key-and-find-the-project-id), then install CLI 0.9.4:
```bash theme={null}
uv tool install "contree-cli==0.9.4"
contree --version
contree auth
contree auth ls
```
`contree auth` prompts for the API key without echoing it, then for the project ID, and saves a local profile. Values supplied through flags or environment variables skip the corresponding prompt. `contree auth ls` probes the profile. Continue when its status is `ok`.
For non-interactive profile registration, set the CLI-specific project variable before running `auth`:
```bash theme={null}
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_AI_PROJECT="YOUR_PROJECT_ID"
contree auth -y
```
The CLI reads these values when registering the profile. Later CLI commands use the saved profile.
**2. Find and select an image**
List available Ubuntu images and note the immutable UUID in the first column:
```bash theme={null}
contree images --prefix=ubuntu
```
Select `ubuntu:latest` in a unique local session:
```bash theme={null}
export CONTREE_SESSION="quickstart-$USER-$$"
contree use tag:ubuntu:latest
```
A tag is convenient for discovery, but it can move. Record the resolved image UUID when reproducibility matters.
**3. Save and reuse a file**
CLI runs retain changes and advance the session unless `-D` or `--disposable` is present. Choose the retained mode by omitting that flag before submitting the first command:
```bash theme={null}
# No -D: retain the resulting filesystem and advance the session image.
contree run -- sh -c 'printf "ready\n" > /tmp/quickstart.txt'
contree run -D -- cat /tmp/quickstart.txt
```
Expected output from the second command:
```text theme={null}
ready
```
Each command starts fresh compute. The session carries the selected image, working directory, staged files, and history; it does not keep the previous VM or process running.
**4. Verify disposable behavior**
Use `-D` for a command whose filesystem changes must not advance the session:
```bash theme={null}
contree run -D -- sh -c 'printf "temporary\n" > /tmp/disposable.txt'
contree run -D -- test ! -e /tmp/disposable.txt
```
The second command exits successfully because the previous disposable run did not change the session image.
## Continue
* [Sessions and execution modes](/sandboxes/concepts/sessions-and-execution-modes)
* [CLI tutorial](/sandboxes/cli/tutorial/index)
* [CLI command reference](/sandboxes/cli/commands/index)
* [Troubleshooting](/sandboxes/operate/troubleshooting)
# Python quickstart
Source: https://docs.tokenfactory.nebius.com/sandboxes/start/python-quickstart
Create a Python project, save a filesystem change, and reuse it in a later operation.
This quickstart uses `contree-sdk` 0.3.6 and `alpine:3.19` to create a file in one operation, save the resulting filesystem, and read the file in a second operation.
**1. Set up access**
Create an API key and copy the project ID as described in [Set up access](/sandboxes/start/set-up-access#create-an-api-key-and-find-the-project-id). For the Python SDK, export both values in each shell that runs the program:
```bash theme={null}
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_PROJECT_ID="YOUR_PROJECT_ID"
```
The SDK reads `NEBIUS_PROJECT_ID`. `NEBIUS_AI_PROJECT` is the CLI's profile-registration variable and does not replace it.
**2. Create a project**
Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if it is not already available, then create an isolated project and install SDK 0.3.6:
```bash theme={null}
mkdir sandboxes-quickstart
cd sandboxes-quickstart
uv init --bare --python 3.12
uv add "contree-sdk==0.3.6"
```
Use Python 3.12 for this quickstart.
**3. Save and reuse a file**
Create `quickstart.py`:
```python theme={null}
import asyncio
from contree_sdk import Contree
async def main() -> None:
client = Contree()
base = await client.images.use("alpine:3.19", strict=True)
# Choose persistence before the operation is submitted.
preparation = base.run(
shell="printf 'ready\\n' > /tmp/status.txt",
disposable=False,
)
checkpoint = await preparation
if checkpoint.exit_code != 0:
raise RuntimeError(f"Preparation failed: {checkpoint.stderr}")
if checkpoint.uuid is None:
raise RuntimeError("Preparation returned no reusable image UUID")
print(f"Saved image UUID: {checkpoint.uuid}")
reuse = checkpoint.run(
shell="cat /tmp/status.txt",
disposable=True,
)
result = await reuse
if result.exit_code != 0:
raise RuntimeError(f"Reuse failed: {result.stderr}")
print(result.stdout, end="")
if __name__ == "__main__":
asyncio.run(main())
```
Run it locally:
```bash theme={null}
uv run python quickstart.py
```
Expected output includes an immutable image UUID followed by:
```text theme={null}
ready
```
The object returned by awaiting a run exposes both its process result (`exit_code`, `stdout`, and `stderr`) and its saved image. When the run saves an image, you can use its `uuid` and call `.run()` again, as `checkpoint` does here. A disposable result has `uuid is None` and cannot be used to start another run.
`base.run(...)` prepares the first operation. Awaiting the returned object submits the operation and waits for its result. Because `disposable=False` was selected before submission, a successful preparation can return a reusable image. The second operation sets `disposable=True`, so its filesystem changes are discarded.
**4. Inspect failures before continuing**
An accepted operation and a completed command are different outcomes. Check the process result before using its output or image:
### Command succeeded: `exit_code == 0`
Use the output and, when requested, the returned image UUID.
### Command failed: nonzero `exit_code`
Inspect stderr and fix the command or input. Follow the [result-image rules](/sandboxes/concepts/images-checkpoints-and-branches#interpret-the-result-image) before reusing files from that run.
### SDK raised an exception
The operation did not produce a normal process result. Record safe diagnostic details and follow [Troubleshooting](/sandboxes/operate/troubleshooting).
> [!NOTE]
>
> When an SDK 0.3.6 wait ends before a terminal result, the SDK attempts best-effort cancellation. A REST event-stream disconnect has different behavior. See [Execution lifecycle](/sandboxes/concepts/execution-lifecycle).
## Continue
* [Images, checkpoints, and branches](/sandboxes/concepts/images-checkpoints-and-branches)
* [Run commands and handle results](/sandboxes/guides/run-commands-and-results)
* [Prepare once, reuse safely](/sandboxes/cookbook/prepare-once-reuse-safely)
* [Python SDK reference](/sandboxes/sdk/python_sdk/reference/index)
# Set up access
Source: https://docs.tokenfactory.nebius.com/sandboxes/start/set-up-access
Create credentials, select a project, verify Sandboxes access, and find a base image.
Complete these steps before running the Python, CLI, or REST examples.
## Create an API key and find the project ID
1. Open the Token Factory [API keys page](https://tokenfactory.nebius.com/project/api-keys), create a key in the project that will run Sandboxes, and save the value when it is shown. The value cannot be opened again later.
2. Open **Project settings** in Token Factory and copy the project ID shown under the project name. [Organizations and projects](/team-access/org-projects) explains project scope; [Groups and access management](/team-access/groups) explains how project membership grants access to resources.
Keep the API key outside source files and sandbox inputs.
## Verify access with the CLI
This diagnostic step is optional for Python and REST users. It gives a quick way to distinguish an accepted credential from a missing Sandboxes permission.
Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if needed, then install CLI 0.9.4 and register a profile:
```bash theme={null}
uv tool install "contree-cli==0.9.4"
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_AI_PROJECT="YOUR_PROJECT_ID"
contree auth -y
contree auth ls
```
The profile status distinguishes several setup failures:
| Status | Meaning | Next action |
| - | - | - |
| `ok` | The profile probe succeeded and the required Sandboxes permission is present. | Continue to image discovery. |
| `inactive` | The token was accepted, but the required Sandboxes permission is missing. The project may need Sandboxes activation or the caller may need access. | Ask the project administrator to verify both project activation and the caller's authorization. Contact [contree@nebius.com](mailto:contree@nebius.com) when activation is required. |
| `timeout` | The two-second profile probe did not finish. | Check network access and the configured service URL, then retry. |
| `error` | The probe failed, including invalid credentials or another API error. | Recheck the key and project, then register the profile again. |
For activation help, send the project ID and profile status to [contree@nebius.com](mailto:contree@nebius.com). An `inactive` profile can mean either missing project activation or missing caller permission; do not send the API key.
## Use the correct project variable
| Surface | API key | Project ID | When read |
| - | - | - | - |
| CLI profile registration | `NEBIUS_API_KEY` | `NEBIUS_AI_PROJECT` | `contree auth` reads the values and saves a profile. |
| Python SDK 0.3.6 | `NEBIUS_API_KEY` | `NEBIUS_PROJECT_ID` | The SDK reads the variables when it creates the client. |
| REST examples | `NEBIUS_API_KEY` | `NEBIUS_PROJECT_ID` | The shell expands them into the `Authorization` and `Project` headers. |
For SDK or REST work, export the runtime project variable explicitly:
```bash theme={null}
export NEBIUS_API_KEY="YOUR_API_KEY"
export NEBIUS_PROJECT_ID="YOUR_PROJECT_ID"
```
## Find an image UUID
List images available to the selected project:
```bash theme={null}
contree images
contree images --prefix=alpine
```
The first column is the immutable image UUID. A `tag:NAME` reference is easier to discover, but a tag can later point to another image. Use the UUID in recorded experiments and REST examples.
The Python quickstart uses `alpine:3.19`, and the CLI quickstart uses `ubuntu:latest`. If either tag is absent, select an available image from `contree images` and record its UUID. Replace `"alpine:3.19"` in the Python example with that UUID, or pass the UUID to `contree use` in the CLI example. Choose an image with `/bin/sh` and the commands used by the example.
## Continue
* [Python quickstart](/sandboxes/start/python-quickstart)
* [CLI quickstart](/sandboxes/start/cli-quickstart)
* [Choose an interface](/sandboxes/start/choose-an-interface)
# Sandboxes for SWE agents
Source: https://docs.tokenfactory.nebius.com/sandboxes/swe-agents
Researching SWE agents is hard: there are thousands of heavy-weight environments, setup is slow, and reproducibility is fragile. Sandboxes provides a branchable, VM-isolated sandbox designed for rapid experimentation across thousands of SWE environments — over 7,000 are preloaded out of the box.
## Purpose-built for SWE agent research
* Thousands of ready-to-run SWE environments, so you can benchmark agents with minimal infrastructure setup.
* Git-like branching to try multiple patches or strategies in parallel from the same checkpoint, then keep only the winning branch: MCTS, beam search, rollbacks, value-function estimation.
* VM-level isolation with per-run metrics to keep generated code contained and experiments auditable.
## Environment catalog
Pick from the preloaded catalog rather than building or pulling terabytes of images yourself. What's included now:
* [SWE-bench Verified](https://huggingface.co/datasets/princeton-nlp/SWE-bench_Verified)
* [SWE-rebench](https://huggingface.co/datasets/nebius/SWE-rebench/viewer/default/filtered)
* [SWE-rebench-V2](https://huggingface.co/datasets/nebius/SWE-rebench-V2)
## Integrations
> [card] [Contree CLI](/sandboxes/cli)
>
> Terminal-first agent workflows, scripted runs, session branching, and filesystem inspection.
> [card] [Contree SDK](/sandboxes/sdk)
>
> Integrate your own agent via contree-sdk.
> [card] [Contree MCP](/sandboxes/mcp)
>
> Plug sandboxes into AI assistants that speak the Model Context Protocol.
# Switch to Token Factory
Source: https://docs.tokenfactory.nebius.com/switch
Nebius Token Factory provides an OpenAI-compatible API, making it easy to migrate existing OpenAI integrations with minimal changes.
## Switching from OpenAI
Here is a standard OpenAI example:
```python theme={null}
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input="Write a one-sentence bedtime story about a unicorn."
)
print(response.output_text)
```
To switch to Nebius Token Factory:
1. **Set the `base_url`** to the Token Factory endpoint:\
`https://api.tokenfactory.nebius.com/v1/`
2. **Set your API key** using the `NEBIUS_API_KEY` environment variable. Get your key at: [https://tokenfactory.nebius.com/](https://tokenfactory.nebius.com/)
3. **Specify the model** you want to use (for example, `moonshotai/Kimi-K2.5`).
That's it - no other changes are required.
## Full Example Using Token Factory
```python lines theme={null}
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.tokenfactory.nebius.com/v1/",
api_key=os.environ.get("NEBIUS_API_KEY")
)
response = client.chat.completions.create(
model="moonshotai/Kimi-K2.5",
messages=[
{
"role": "system",
"content": "You are a helpful assistant"
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Write a haiku about cats"
}
]
}
]
)
print(response.to_json())
```
# Groups & Access management
Source: https://docs.tokenfactory.nebius.com/team-access/groups
Learn about access management on different levels
Being listed as a user in an organization does **not** automatically grant access to its resources.\
Each user or service account must be assigned to a **group** that defines their access level within the organization or its projects.
Groups exist at two levels:
* **Organization-level Groups** — control access to organization-wide settings and projects.
* **Project-level Groups** — control access to resources within individual projects.
### **Organization-level Groups**
Organization-level groups define permissions for managing the overall workspace, its billing, and projects.
| **Group** | **Description** |
| :- | :- |
| **Admin** | Full access to organization settings, billing, and all projects. Can invite external users, manage organization projects, and configure access rights. |
| **Billing Manager** | Can manage billing settings and view usage statistics across the organization. Cannot access project resources or invite users. |
| **No Group** | Users added without a role at the organization level. They can later be granted access to specific project-level resources. |
#### **Organization-level Permissions**
| **Action** | **Admin** | **Billing Manager** |
| :- | :- | :- |
| **Usage & Consumption** | View | View |
| **Projects and Resources** | View, Create, Update, Delete | No Access |
| **Billing Settings** | View, Create, Update, Delete | View, Create, Update, Delete |
| **Payments** | View | View |
| **Organization Access (Users)** | View, Add, Remove | No Access |
| **Zero Data Retention Settings** | View, Change | No Access |
> [!NOTE]
>
> **Note:** Organization Admins automatically have administrative privileges across all projects in the organization.
### **Project-level Groups**
Project-level groups control access to specific project resources and operations.
| **Group** | **Description** |
| :- | :- |
| **Admin** | Full control over project resources. Can invite organization members to the project and manage their access. |
| **Member** | Can create and manage project resources but cannot invite new users or change access permissions. |
#### **Project-level Permissions**
| **Action** | **Admin** | **Member** |
| :- | :- | :- |
| **Project Access (Users)** | View, Add, Remove | No Access |
| **API Keys** | Create, Delete | Create, Delete own API keys |
| **Files API** | Full Access | Full Access |
| **Fine-tuning API** | Full Access | Full Access |
| **Batch API** | Full Access | Full Access |
| **Dedicated Endpoints API** | Full Access | Full Access |
| **Prompt Presets** | Full Access | Full Access |
| **Public Endpoints API** | Full Access | Full Access |
### **Inviting Users to Groups**
To grant access to organization or project resources:
1. Invite a user to the organization.
2. Assign the user to the appropriate **Organization Group** or **Project Group**.
For detailed instructions, see the [**User Invitations**](https://docs.tokenfactory.nebius.com/team-access/invitations) section.
# User Invitations
Source: https://docs.tokenfactory.nebius.com/team-access/invitations
Learn how to invite new users to Organization and add users to Projects
## **Inviting Users to an Organization**
Users with **Organization Admin** rights can invite new users to join the organization.\
Invitations are sent by email and remain valid for **three days**. Once accepted, the user can sign in using any available authentication method.
### **To invite a user through the Web UI**
1. In the top header, open the **Organization** dropdown and click the **cog** **icon**.
* Alternatively, click your **Profile** icon and select **Organization Settings** from the menu.
2. On the **Organization** page, open the **Team & Access** tab.
3. Click **Invite**.
4. In the dialog window, enter the **email address** of the user you want to invite.
5. (Optional) Select an **Organization Group** to assign the appropriate access level.
* You can change the user’s group at any time.
* For more details, see [**Organization Groups**](https://docs.tokenfactory.nebius.com/team-access/groups#organization-level-groups).
6. Click **Invite**.
An invitation email will be sent to the specified address.\
Once the user accepts, they can sign in and access the organization based on their assigned group.
## **Inviting Users to a Project**
Users with **Project Admin** rights can add existing members of the organization to a specific project.\
If you also have **Organization Admin** rights, you can invite new users directly to both the organization and the project.
### **To invite a user through the Web UI**
1. In the top header, open the **Project** dropdown and click the **cog** **icon**.
* Alternatively, click your **Profile** icon and select **Project Settings** from the menu.
2. On the **Project** page, open the **Team & Access** tab.
3. Click **Invite**.
4. In the dialog window, choose one of the following options:
* **Invite new users** (requires Organization Admin rights): specify the user’s email to invite them to both the organization and the project.
* **Add existing users**: select users who are already part of the organization and grant them project access.
5. (Optional) Assign the user to a **Project Group** to define their permissions.
* You can change the group assignment at any time.
* For more details, see [**Project Groups**](https://docs.tokenfactory.nebius.com/team-access/groups#project-level-groups).
6. Click **Invite**.
The user will immediately gain access to the project once added or once their invitation is accepted.
# Organizations and Projects
Source: https://docs.tokenfactory.nebius.com/team-access/org-projects
Learn how to work with Organizations and Projects in Nebius Token Factory
### **Hierarchy Overview**
The **Nebius Token Factory resource model** follows a simple hierarchical structure:
**Organization → Projects → Resources**
* At the top level, the **Organization** defines your overall workspace and user management.
* Each **Project** within an organization acts as an isolated environment for related resources and teams.
* **Resources**—such as models, endpoints, files, and datasets—exist inside a project and inherit its access settings.
```mermaid theme={null}
%%{init: {"flowchart": {"nodeSpacing": 25, "rankSpacing": 40}}}%%
flowchart LR
classDef rounded stroke:#4C37DC,fill:#1E1E1E,color:#fff,rx:15,ry:15;
Org["Organization"]
Org --> A["Project A"]
Org --> B["Project B"]
A --> A1["API Keys"]
A --> A2["Fine-tuning Jobs"]
A --> A3["Dedicated Endpoints"]
A --> A4["Files & Datasets"]
B --> B1["API Keys"]
B --> B2["Fine-tuning Jobs"]
B --> B3["Datasets"]
class Org,A,B,A1,A2,A3,A4,B1,B2,B3 rounded;
```
***
### **Organization**
An **organization** represents your primary workspace in Nebius Token Factory. It serves as a container for all your projects, access settings, and user accounts.
An organization includes:
* **Projects** that contain your compute, storage, and AI resources
* **Organization Groups** that define identity and access configurations
* **User accounts** with assigned groups and permissions
When you sign up for Nebius Token Factory, a personal organization is created automatically.\
You can also be invited to other organizations and collaborate on their projects.
To grant a user access to organizational resources, add them to the relevant **Organization Group**.
***
### **Projects**
A **project** is a logical container for your Nebius Token Factory resources. Projects help you organize assets and manage permissions within an organization.
Within a project, you can create and manage:
* **API keys**
* **Fine-tuning jobs**
* **Dedicated endpoints**
* **Files and datasets**
Each project includes **Project Groups** that control access to project resources.\
Projects can be **multi-region**, allowing you to group resources by product, team, use case, or any other organizational criteria.
When you first sign up for Nebius Token Factory, a **default project** is created automatically for your resources.
# Overview
Source: https://docs.tokenfactory.nebius.com/team-access/overview
Collaborate securely with Team Management & Role-Based Access
**Teams & Access Management** enables centralized control over user access to your resources. It ensures that only authorized users and accounts with assigned permissions can interact with your organization’s assets.
**Key Capabilities**
> [card] [Organization Management](/team-access/groups#organization-level-groups)
>
> * Manage billing details and usage across your organisation
> [card] [Team Invitations](/team-access/invitations)
>
> * Add team members to your organization or projects
> [card] [Group Assignment](/team-access/groups)
>
> * Define access levels using predefined access groups
> [card] [Scoped Projects](/team-access/org-projects)
>
> * Split your workspace into distinct projects and invite only relevant collaborators
> [card] [Granular Access Control](/team-access/groups)
>
> * Manage permissions independently for each project and the overall organization
This functionality ensures **secure, compliant, and organized collaboration** across all workspaces and is available to all users, regardless of service tier.
# Configure Single Sign-On
Source: https://docs.tokenfactory.nebius.com/team-access/sso
Learn how to configure single sign-on
A federation could be configured for the Nebius Token Factory to allow your organization's users login using a SAML 2.0 compatible single sign-on provider.
SSO is configured in two systems:
* Nebius Token Factory, where you create and configure a federation.
* Identity Provider: create an application and connect the application to the federation.
After the federation and application are set up, users can sign in to Nebius Token Factory.
Following 4 steps will guide you through the process.
## 1. Create an application in the Identity Provider
> [tab] Okta
>
> Go to Admin Console → Applications → Application and choose "Create App Integration".
>
> Choose "SAML 2.0" sign-in method and set the following parameters on the next screen:
>
> * **Single sign-on URL**: [https://auth.tokenfactory.nebius.com/login/saml2/provider/federation-id](https://auth.tokenfactory.nebius.com/login/saml2/provider/federation-id)
> * **Audience URI (SP Entity ID)**: [https://auth.tokenfactory.nebius.com/saml2/rp/federation-id](https://auth.tokenfactory.nebius.com/saml2/rp/federation-id)
> * **Name ID format**: Unspecified
> * **Application username**: Okta username
>
> Continue and tick the option "This is an internal app that we have created" on the next screen.
>
> > [!NOTE]
> >
> > **Note**
> >
> > `federation-id` is used temporarily until you create a federation and get its ID. After that, replace `federation-id` with an actual one.
## 2. Create a federation in Nebius Token Factory
> [tab] CLI
>
> 1. Install the Nebius CLI tool (an installation script works for macOS and Linux):
>
> ```
> curl -sSL https://storage.eu-north1.nebius.cloud/cli/install.sh | bash
> ```
> 2. Create a configuration profile:
>
> ```
> nebius profile create \
> --profile \
> --endpoint api.nebius.cloud \
> --federation-endpoint auth.tokenfactory.nebius.com \
> --parent-id
> ```
>
> An organization ID starts with `aitenant-` and could be found on [the organization settings page](https://tokenfactory.nebius.com/organization/projects).
> 3. Run the following command:
>
> ```
> nebius iam federation create \
> --parent-id \
> --name \
> --user-account-auto-creation=true \
> --active=true \
> --saml-settings-sso-url \
> --saml-settings-idp-issuer
>
> ```
> 4. Copy and save the federation ID. It is returned in the `metadata.id` field of the command output.
## 3. Change the SAML settings of the application
> [tab] Okta
>
> 1. Replace `federation-id` with an actual federation ID in the Okta application configuration.
> 2. Navigate to the application configuration page on the Admin Console.
> 3. Then scroll down to the "SAML Settings" section and replace `federation-id` with the created federation ID in the following fields:
> * Single Sign On URL: `https://auth.tokenfactory.nebius.com/login/saml2/provider/`
> * Recipient URL: `https://auth.tokenfactory.nebius.com/login/saml2/provider/`
> * Destination URL: `https://auth.tokenfactory.nebius.com/login/saml2/provider/`
> * Audience Restriction: `https://auth.tokenfactory.nebius.com/saml2/rp/`
## 4. Add a signing certificate to the federation
Download a certificate from the Identity Provider.
> [tab] Okta
>
> 1. Navigate to the application configuration page on the Admin Console.
> 2. Switch to the "Sign On" tab and scroll down to the "SAML Signing Certificates" section.
> 3. Push "Generate new certificate" and then "Actions → Download certificate" on a line with freshly created active certificate.
Then, add the certificate to the federation:
> [tab] CLI
>
> 1. Prepare the `certificate.json` file:
>
> ```
> {
> "metadata": {
> "parent_id": ""
> },
> "spec": {
> "description": "certificate for a federation",
> "data": "-----BEGIN CERTIFICATE-----\n\n-----END CERTIFICATE-----\n"
> }
> }
> ```
>
> Specify the certificate body from the downloaded file and the federation ID.
>
> In this file, the certificate body is split into several lines. Paste it as a single line to `federation-cert.json`.
> 2. Apply the certificate file:
>
> ```
> nebius iam federation-certificate create --file federation-cert.json
> ```
## Log in to Nebius Token Factory using the configured SSO
1. Open the Nebius Token Factory web console.
2. Click the Get started with SSO button.
3. Enter the federation ID and click the Sign in button.
A successful login means that you have correctly configured the federation and SSO.
## Assigning new users to the groups
SSO users are not included in any Access groups on first login. An organization administrator should assign them to an Access group to provide the required permissions on the platform.
# Prompt presets
Source: https://docs.tokenfactory.nebius.com/utilities/prompt-presets
Learn how to save your prompts and reuse them
[**Prompt presets**](https://tokenfactory.nebius.com/prompt-presets) let you save and reuse model setups you’ve tested in Nebius Token Factory, making it easy to manage and share configurations.
In the **Inference playground**, you can store the model parameters, system prompt, and few-shot examples as a prompt preset. Saved presets appear on the [**Prompt presets**](https://tokenfactory.nebius.com/prompt-presets) page, where you can:
* Reopen them in the playground for further testing
* Export them as code for integration into your application
* Share them with your team
### Prompt preset contents
A prompt preset is based on a single model setup from the playground and includes:
* **Text-to-text model** — Other model types are not supported.
* **Model parameters** available in the playground (e.g., temperature, max tokens). Parameters available only via API are not included.
* **System prompt** (if added in your setup).
* **Few-shot examples** — user prompts and AI responses you’ve added.
> [!WARNING]
>
> Your actual chat history with the model is not saved in the preset.
### Creating a preset
1. In the left panel, click **Save preset**.
If using Compare mode, click → **Save preset** in the panel of the desired model.
2. In the dialog, enter a name and (optional) tags.
3. Click **Save preset**.
### Using presets
You can manage all saved presets on the [**Prompt presets**](https://tokenfactory.nebius.com/prompt-presets) page.
1. **Open in playground** — Click a preset to load it back into the playground.
2. **View as code** — Click → **View code** to generate code for use in your app.
3. **Share** — Click → **Share** to copy a URL.
> [!NOTE]
>
> Recipients must have a Nebius Token Factory account to access presets and other inference features.