> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenfactory.nebius.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions and operations

Start with [Work with a Session](https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/session-model.md), [Save and resume a session](https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/sessions.md), or [Advanced: control a running sandbox](https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/operation.md).
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](https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/session-model.md#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**](https://docs.tokenfactory.nebius.com/sandboxes/sdk/python_sdk/reference/exceptions.md#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).
