Skip to main content
Start with Work with a Session, Save and resume a session, or Advanced: control a running sandbox. 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.

class 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()

required
required
bool

class 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()

Handle an execution event without blocking or performing network I/O.
required
None

should_snapshot()

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.
Future[None]
A future shared by all readers of the current policy decision.

class ApiSuccessCommitPolicy

Retain every successful API result, including a nonzero or unknown exit code.

Methods

should_commit()

required
required
bool

class AsyncLazySession

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

BaseException | None
Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']
str

Methods

abort()

Discard unsaved work and close. An already running snapshot finishes first.
None

close()

Save pending work and close this wrapper, retaining caller-owned resources.
default:"None"
None
RuntimeError – Saving failed; the cause is available as error.
TimeoutError – The caller’s wait expired; closing continues in the worker.

create_branch()

required
default:"None"
None

execute()

required
InstanceResult

grep()

Search session files using the current source’s syntax and limits.
required
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
GrepResult
Matching lines and the server’s truncation indicator.

inspect()

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.
default:"None"
AsyncSessionInspector
A session-bound inspector; creating it starts no VM.

inspect_snapshot()

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.
default:"None"
AsyncImageInspector
An inspector borrowing the underlying client and file transfer.

inspection_source()

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.
default:"None"
AsyncIterator[AsyncImageInspector | str]
A saved image inspector or an active operation UUID.
RuntimeError – The session fails or closes before inspection starts.
TimeoutError – Admission or VM startup exceeds the timeout.

keepalive_request()

Supply a long-running main process available in the base image.
RunRequest
RunRequestThe non-disposable request used to start each VM.

list_dir()

List session directory entries relative to the filesystem root.
default:"'/'"
DirectoryList
Directory entries and their filesystem metadata.

observe()

Observe the operation’s sole reader without depending on handle.wait().
required
required
None

prepare_request()

Apply the wrapped session’s policy and validate shared-VM semantics.
required
RunRequest
RunRequestThe effective request.
ValueError – The request needs a disposable VM or startup-only options.

read_file()

Read current files without stopping an active VM.
required
bytes
The complete file as bytes.

rollback()

default:"1"
None

run()

Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
default:"None"
InstanceResult
The subprocess result, including a nonzero exit code.

snapshot()

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.
default:"None"
HistoryEntry | None
HistoryEntry | NoneThe saved history entry, or None if no VM has run yet.

spawn()

default:"None"
AsyncSubprocessContract

spawn_request()

Start a subprocess; track its exit even if the caller never waits.
required
AsyncSubprocessContract
AsyncSubprocessContractThe subprocess handle from the operation factory.

switch_branch()

required
None

write_file()

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.
required
required
None

class AsyncOperation

Handle to a spawned instance operation, identified by its UUID.

Attributes

str
OperationContext | None
OperationResponse | None

Methods

add_observer()

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.
required
None

apply_files()

Apply already-uploaded files to this running VM.
required
None

cancel()

None

claim_queue()

required
Queue[OperationEvent | None]

create_subprocess()

Create a subprocess handle. Override to return a custom implementation.
required
required
AsyncSubprocessContract
AsyncSubprocessContractA handle consuming the supplied event queue.

events()

Replay buffered events, then follow the shared reader with local filters.timeout bounds this subscription. Expiry does not cancel the operation.
default:"None"
default:"None"
default:"None"
AsyncIterator[OperationEvent]
Events after since whose process matches spid, when specified.
TimeoutError – The subscription did not finish before timeout.

open_event_stream()

Open the unfiltered source. Override this hook to supply custom events.
AsyncIterator[OperationEvent]
The single transport stream consumed by the operation.

pipe_stdin()

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.
required
default:"1"
default:"True"
default:"65536"
StdinResult
StdinResultAcknowledged bytes, EOF delivery, and observed early completion.
ValueError – chunk_size or spid is not positive.

pump()

None

route_event()

required
None

run()

required
default:"False"
default:"()"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
AsyncSubprocessContract

send_stdin()

required
default:"1"
default:"True"
None

shutdown()

None

signal()

default:"None"
default:"1"
None

status()

default:"False"
OperationResponse

wait()

default:"None"
InstanceResult

class AsyncOperationContract

An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.

Attributes

str
OperationContext | None
OperationResponse | None

Methods

add_observer()

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.
required
None

apply_files()

required
None

cancel()

None

events()

default:"None"
default:"None"
default:"None"
AsyncIterator[OperationEvent]

pipe_stdin()

required
default:"1"
default:"True"
default:"65536"
StdinResult

run()

required
default:"False"
default:"()"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
AsyncSubprocessContract

send_stdin()

required
default:"1"
default:"True"
None

shutdown()

None

signal()

default:"None"
default:"1"
None

status()

default:"False"
OperationResponse

wait()

default:"None"
InstanceResult

class AsyncSubprocessContract

Waitable event stream for one subprocess. Iteration and wait share completion state.

Attributes

int

Methods

pipe_to()

default:"None"
default:"None"
InstanceResult

wait()

default:"None"
InstanceResult

class AsyncSubprocessHandle

Both awaitable (final result) and async-iterable (live events) for one spid.

Attributes

int

Methods

iterate()

AsyncIterator[OperationEvent]

pipe_to()

default:"None"
default:"None"
InstanceResult

wait()

default:"None"
InstanceResult

class CommandCountSnapshotPolicy

Request a snapshot after exactly limit command admissions in one VM.

Methods

notify()

Handle an execution event without blocking or performing network I/O.
required
None

should_snapshot()

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.
Future[None]
A future shared by all readers of the current policy decision.

class CompositeSnapshotPolicy

Request a snapshot when any child policy’s future completes.

Methods

notify()

Handle an execution event without blocking or performing network I/O.
required
None

should_snapshot()

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.
Future[None]
A future shared by all readers of the current policy decision.

class ContreeAsyncSession

A durable, resumable ConTree session backed by a Store.

Attributes

str

Methods

check_operation_endpoint()

Check the recorded server before using an operation UUID.
required
None
ValueError – The current client targets a different endpoint.

commit_result()

required
default:"None"
default:"None"
default:"None"
default:"None"
HistoryEntry | None

create_branch()

required
default:"None"
None

create_file_transfer()

Create file I/O when no component was supplied.
AsyncFileTransfer
AsyncFileTransferA file-transfer component using the session client.

create_inspector()

Create a view of one image. Override to customize inspection.
required
AsyncImageInspector
An inspector borrowing the client’s connection and file transfer.

create_operation()

Construct a lifecycle implementation bound to the supplied operation context.
required
required
AsyncOperationContract
AsyncOperationContractAn implementation of the matching operation lifecycle contract.

create_operation_record()

Serialize an operation context. Override to persist custom request fields.
required
OperationRecord
OperationRecordA pending record without local input sources.
ValueError – The operation does not belong to this session.

create_pending_run()

Create the awaitable/context-manager wrapper for a command.
required
default:"None"
PendingRun
PendingRunA one-use wrapper for awaiting or entering the operation.

create_store()

Create the default store when none was supplied.
AsyncStore
AsyncStoreA new memory store owned by this session.

delete_branch()

required
None

detach()

Register an already spawned operation without reading events or closing it.
required
OperationRecord
OperationRecordIts durable record. The caller still owns the live handle.
ValueError – The operation does not belong to this session.

ensure_ready()

None

execute()

Run a request to completion and commit its effective non-disposable result.
required
default:"None"
InstanceResult
The completed process result, including nonzero exit codes.

get_entry()

required
HistoryEntry

get_operation()

required
OperationRecord

grep()

Search session files using the current source’s syntax and limits.
required
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
GrepResult
Matching lines and the server’s truncation indicator.

history()

tuple[list[HistoryEntry], dict[str, list[str]]]
tuple[list[HistoryEntry], dict[str, list[str]]]

inspect()

Pin the current saved image without starting a VM.Pending staged attachments appear only after an operation applies them.
AsyncImageInspector
A read-only view that borrows this session’s client and file transfer.

list_branches()

list[tuple[str, bool]]

list_dir()

List session directory entries relative to the filesystem root.
default:"'/'"
DirectoryList
Directory entries and their filesystem metadata.

list_operations()

default:"True"
tuple[OperationRecord, ...]
tuple[OperationRecord, …]
required
None
default:"1"
None

pending_files()

default:"None"
tuple[StagedFile, ...]
tuple[StagedFile, …]

prepare_environment()

Overlay command variables on session defaults without mutating either input.
required
dict[str, str] | None
A fresh mapping, or None when both inputs omit environment variables.

prepare_request()

Apply defaults before uploads or execution. Override to validate or transform commands.
required
RunRequest
RunRequestThe effective command with session defaults applied.

read_file()

required
bytes

refresh_from_entry()

required
None

resolve_image()

Resolve a base image. Override to implement an import or registry policy.
required
str
The resolved image UUID.

restore_operation()

Recreate a control handle from the persisted source context.
required
AsyncOperationContract
AsyncOperationContractAn unentered handle. Use wait_operation to reuse a stored final result.

restore_operation_context()

Decode a stored request. Override together with create_operation_record.
required
OperationContext
OperationContextIts immutable source context, ready for an operation factory or policy.

rollback()

default:"1"
None

run()

default:"None"
default:"None"
default:"()"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
default:"None"
default:"False"
default:"None"
default:"False"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
PendingRun

set_cwd()

required
None

set_env()

required
None

spawn()

default:"None"
default:"None"
default:"()"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
default:"None"
default:"False"
default:"None"
default:"False"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
AsyncOperationContract

spawn_detached()

Spawn and register a command; options are RunRequest fields.
default:"None"
OperationRecord
OperationRecordA durable record whose UUID can be passed to wait_operation.

spawn_request()

Prepare and submit a command, then construct its operation through the factory.
required
AsyncOperationContract
AsyncOperationContractA bound operation whose context records the effective request.

stage_files()

required
HistoryEntry

submit_request()

Submit prepared input to the transport. Override for transport-level customization.
required
required
required
required
InstanceSpawnResponse
The transport response identifying the spawned operation.

switch_branch()

required
None

wait_operation()

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.
required
default:"None"
default:"None"
InstanceResult
The stored process result, including nonzero exit codes.

write_file()

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.
required
required
None

class ContreeSession

A durable, resumable ConTree session backed by a Store (sync).

Attributes

str

Methods

check_operation_endpoint()

Check the recorded server before using an operation UUID.
required
None
ValueError – The current client targets a different endpoint.

commit_result()

required
default:"None"
default:"None"
default:"None"
default:"None"
HistoryEntry | None

create_branch()

required
default:"None"
None

create_file_transfer()

Create file I/O when no component was supplied.
SyncFileTransfer
SyncFileTransferA file-transfer component using the session client.

create_inspector()

Create a view of one image. Override to customize inspection.
required
ImageInspector
An inspector borrowing the client’s connection and file transfer.

create_operation()

Construct a lifecycle implementation bound to the supplied operation context.
required
required
OperationContract
OperationContractAn implementation of the matching operation lifecycle contract.

create_operation_record()

Serialize an operation context. Override to persist custom request fields.
required
OperationRecord
OperationRecordA pending record without local input sources.
ValueError – The operation does not belong to this session.

create_store()

Create the default store when none was supplied.
SyncStore
SyncStoreA new memory store owned by this session.

delete_branch()

required
None

detach()

Register an already spawned operation without reading events or closing it.
required
OperationRecord
OperationRecordIts durable record. The caller still owns the live handle.
ValueError – The operation does not belong to this session.

execute()

Run a request to completion and commit its effective non-disposable result.
required
default:"None"
InstanceResult
The completed process result, including nonzero exit codes.
ValueError – The operation factory returned an unbound operation.

get_entry()

required
HistoryEntry

get_operation()

required
OperationRecord

grep()

Search session files using the current source’s syntax and limits.
required
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
GrepResult
Matching lines and the server’s truncation indicator.

history()

tuple[list[HistoryEntry], dict[str, list[str]]]
tuple[list[HistoryEntry], dict[str, list[str]]]

inspect()

Pin the current saved image without starting a VM.Pending staged attachments appear only after an operation applies them.
ImageInspector
A read-only view that borrows this session’s client and file transfer.

list_branches()

list[tuple[str, bool]]

list_dir()

List session directory entries relative to the filesystem root.
default:"'/'"
DirectoryList
Directory entries and their filesystem metadata.

list_operations()

default:"True"
tuple[OperationRecord, ...]
tuple[OperationRecord, …]
required
None
default:"1"
None

pending_files()

default:"None"
tuple[StagedFile, ...]
tuple[StagedFile, …]

prepare_environment()

Overlay command variables on session defaults without mutating either input.
required
dict[str, str] | None
A fresh mapping, or None when both inputs omit environment variables.

prepare_request()

Apply defaults before uploads or execution. Override to validate or transform commands.
required
RunRequest
RunRequestThe effective command with session defaults applied.

read_file()

required
bytes

refresh_from_entry()

required
None

resolve_image()

Resolve a base image. Override to implement an import or registry policy.
required
str
The resolved image UUID.

restore_operation()

Recreate a control handle from the persisted source context.
required
OperationContract
OperationContractAn unentered handle. Use wait_operation to reuse a stored final result.

restore_operation_context()

Decode a stored request. Override together with create_operation_record.
required
OperationContext
OperationContextIts immutable source context, ready for an operation factory or policy.

rollback()

default:"1"
None

run()

default:"None"
default:"None"
default:"()"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
default:"None"
default:"False"
default:"None"
default:"False"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
InstanceResult

set_cwd()

required
None

set_env()

required
None

spawn()

default:"None"
default:"None"
default:"()"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
default:"None"
default:"False"
default:"None"
default:"False"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
OperationContract

spawn_detached()

Spawn and register a command; options are RunRequest fields.
default:"None"
OperationRecord
OperationRecordA durable record whose UUID can be passed to wait_operation.

spawn_request()

Prepare and submit a command, then construct its operation through the factory.
required
OperationContract
OperationContractA bound operation whose context records the effective request.

stage_files()

required
HistoryEntry

submit_request()

Submit prepared input to the transport. Override for transport-level customization.
required
required
required
required
InstanceSpawnResponse
The transport response identifying the spawned operation.

switch_branch()

required
None

wait_operation()

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.
required
default:"None"
default:"None"
InstanceResult
The stored process result, including nonzero exit codes.

write_file()

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.
required
required
None

class DurationSnapshotPolicy

Request a snapshot after a fixed VM lifetime, including startup time.

Methods

expired()

required
None

notify()

Handle an execution event without blocking or performing network I/O.
required
None

schedule_timer()

None

set_duration()

Update the deadline relative to the original VM startup time.
required
None
ValueError – The duration is not finite and positive.

should_snapshot()

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.
Future[None]
A future shared by all readers of the current policy decision.

start_deferred()

Record startup time; set_duration later arms the effective deadline.
None

class HistoryEntry

Attributes

tuple[str, ...]
tuple[StagedFile, ...]
tuple[StagedFile, …]
tuple[str, ...]
str
str
str
str | None
str
str
str | None
int | None
datetime
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

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()

Handle an execution event without blocking or performing network I/O.
required
None

should_snapshot()

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.
Future[None]
A future shared by all readers of the current policy decision.

class LazySession

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

BaseException | None
Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']
str

Methods

abort()

Discard unsaved work and close. An already running snapshot finishes first.
None

close()

Save pending work and close this wrapper, retaining caller-owned resources.
default:"None"
None
RuntimeError – Saving failed; the cause is available as error.
TimeoutError – The caller’s wait expired; closing continues in the worker.

create_branch()

required
default:"None"
None

execute()

required
InstanceResult

grep()

Search session files using the current source’s syntax and limits.
required
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
GrepResult
Matching lines and the server’s truncation indicator.

inspect()

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.
default:"None"
SessionInspector
A session-bound inspector; creating it starts no VM.

inspect_snapshot()

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.
default:"None"
ImageInspector
An inspector borrowing the underlying client and file transfer.

inspection_source()

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.
default:"None"
Iterator[ImageInspector | str]
A saved image inspector or an active operation UUID.
RuntimeError – The session fails or closes before inspection starts.
TimeoutError – Admission or VM startup exceeds the timeout.

keepalive_request()

Supply a long-running main process available in the base image.
RunRequest
RunRequestThe non-disposable request used to start each VM.

list_dir()

List session directory entries relative to the filesystem root.
default:"'/'"
DirectoryList
Directory entries and their filesystem metadata.

observe()

Observe the operation’s sole reader without depending on handle.wait().
required
required
None

prepare_request()

Apply the wrapped session’s policy and validate shared-VM semantics.
required
RunRequest
RunRequestThe effective request.
ValueError – The request needs a disposable VM or startup-only options.

read_file()

Read current files without stopping an active VM.
required
bytes
The complete file as bytes.

rollback()

default:"1"
None

run()

Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
default:"None"
InstanceResult
The subprocess result, including a nonzero exit code.

snapshot()

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.
default:"None"
HistoryEntry | None
HistoryEntry | NoneThe saved history entry, or None if no VM has run yet.

spawn()

default:"None"
SubprocessContract

spawn_request()

Start a subprocess; track its exit even if the caller never waits.
required
SubprocessContract
SubprocessContractThe subprocess handle from the operation factory.

switch_branch()

required
None

write_file()

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.
required
required
None

class Operation

Handle to a spawned instance operation, identified by its UUID.

Attributes

str
OperationContext | None
OperationResponse | None

Methods

add_observer()

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.
required
None

apply_files()

Apply already-uploaded files to this running VM.
required
None

cancel()

None

claim_queue()

required
Queue[OperationEvent | None]

create_subprocess()

Create a subprocess handle. Override to return a custom implementation.
required
required
SubprocessContract
SubprocessContractA handle consuming the supplied event queue.

events()

Replay buffered events, then follow the shared reader with local filters.timeout bounds this subscription. Expiry does not cancel the operation.
default:"None"
default:"None"
default:"None"
Iterator[OperationEvent]
Events after since whose process matches spid, when specified.
TimeoutError – The subscription did not finish before timeout.

open_event_stream()

Open the unfiltered source. Override this hook to supply custom events.
Iterator[OperationEvent]
The single transport stream consumed by the operation.

pipe_stdin()

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.
required
default:"1"
default:"True"
default:"65536"
StdinResult
StdinResultAcknowledged bytes, EOF delivery, and observed early completion.
ValueError – chunk_size or spid is not positive.

pump()

None

route_event()

required
None

run()

required
default:"False"
default:"()"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
SubprocessContract

send_stdin()

required
default:"1"
default:"True"
None

shutdown()

None

signal()

default:"None"
default:"1"
None

status()

default:"False"
OperationResponse

wait()

default:"None"
InstanceResult

class OperationContext

The effective request and history position captured before remote execution.

Attributes

tuple[StagedFile, ...]
tuple[StagedFile, …]
bool
tuple[str, ...]
int
str | None
RunRequest
str
str
str | None
str | None
str
float
Mapping[str, str]

class OperationContract

An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.

Attributes

str
OperationContext | None
OperationResponse | None

Methods

add_observer()

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.
required
None

apply_files()

required
None

cancel()

None

events()

default:"None"
default:"None"
default:"None"
Iterator[OperationEvent]

pipe_stdin()

required
default:"1"
default:"True"
default:"65536"
StdinResult

run()

required
default:"False"
default:"()"
default:"None"
default:"None"
default:"None"
default:"None"
default:"None"
default:"False"
default:"None"
SubprocessContract

send_stdin()

required
default:"1"
default:"True"
None

shutdown()

None

signal()

default:"None"
default:"1"
None

status()

default:"False"
OperationResponse

wait()

default:"None"
InstanceResult

class OperationRecord

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

tuple[StagedFile, ...]
tuple[StagedFile, …]
float
str
tuple[str, ...]
str | None
str
bool
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
str | None
str
str
str
str
str
str
bool
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]]]
dict[str, str]

Methods

from_dict()

required
OperationRecord

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]]]

class PendingRun

One-use execution wrapper. Await a result or enter an operation context.

Methods

commit()

required
None

run_to_result()

InstanceResult

spawn()

AsyncOperationContract

class RunRequest

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

tuple[str, ...]
str | None
str | None
bool
Mapping[str, str] | None
list[str | Path | UploadFileSpec] | dict[str, str | Path | bytes | UploadFileSpec] | None
list[str | Path | UploadFileSpec] | dict[str, str | Path | bytes | UploadFileSpec] | None
int | None
str | None
InstanceNetworking | None
bool
InstanceResourcesLimits | None
str | None
str | bytes | Path | Readable[str] | Readable[bytes] | AsyncReadable[str] | AsyncReadable[bytes] | None
str | bytes | Path | Readable[str] | Readable[bytes] | AsyncReadable[str] | AsyncReadable[bytes] | None
bool
float | timedelta | None
float | None
str
int | None
int | None

class SnapshotEvent

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

class StdinResult

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

int
bool
bool

class SubprocessContract

Waitable event stream for one subprocess. Iteration and wait share completion state.

Attributes

int

Methods

pipe_to()

default:"None"
default:"None"
InstanceResult

wait()

default:"None"
InstanceResult

class SubprocessHandle

Both blocking-waitable (final result) and iterable (live events) for one spid.

Attributes

int

Methods

pipe_to()

default:"None"
default:"None"
InstanceResult

wait()

default:"None"
InstanceResult

class ZeroExitCommitPolicy

Retain a result only when its process exit code is explicitly zero.

Methods

should_commit()

required
required
bool

instance_result()

Get the operation’s InstanceResult.
required
InstanceResult
The InstanceResult from op.metadata.result.
InterruptedError – The operation was cancelled.
FailedOperationError – The operation itself failed with no result at all (a nonzero exit code inside a successful operation is not an error).