Sessions and operations¶
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 contree_sdk.session.AbstractCommitPolicy[source]¶
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.
- class contree_sdk.session.AbstractSnapshotPolicy[source]¶
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.
- abstractmethod notify(event)[source]¶
Handle an execution event without blocking or performing network I/O.
- Return type:
None
- should_snapshot()[source]¶
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.
- Return type:
Future[None]- Returns:
A future shared by all readers of the current policy decision.
- class contree_sdk.session.ApiSuccessCommitPolicy[source]¶
Retain every successful API result, including a nonzero or unknown exit code.
- class contree_sdk.session.AsyncLazySession(session, *, snapshot_policy=None, snapshot_timeout=30, vm_timeout=3600)[source]¶
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.
- async abort()[source]¶
Discard unsaved work and close. An already running snapshot finishes first.
- Return type:
None
- async close(*, timeout=None)[source]¶
Save pending work and close this wrapper, retaining caller-owned resources.
- Raises:
RuntimeError – Saving failed; the cause is available as error.
TimeoutError – The caller’s wait expired; closing continues in the worker.
- Return type:
None
- property error: BaseException | None¶
- async grep(pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]¶
Search session files using the current source’s syntax and limits.
- Return type:
GrepResult- Returns:
Matching lines and the server’s truncation indicator.
- async inspect(*, timeout=None)[source]¶
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.
- Return type:
AsyncSessionInspector- Returns:
A session-bound inspector; creating it starts no VM.
- async inspect_snapshot(*, timeout=None)[source]¶
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.
- Return type:
AsyncImageInspector- Returns:
An inspector borrowing the underlying client and file transfer.
- inspection_source(*, timeout=None)[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.
- Yields:
A saved image inspector or an active operation UUID.
- Raises:
RuntimeError – The session fails or closes before inspection starts.
TimeoutError – Admission or VM startup exceeds the timeout.
- Return type:
AsyncIterator[AsyncImageInspector|str]
- keepalive_request()[source]¶
Supply a long-running main process available in the base image.
- Return type:
- Returns:
The non-disposable request used to start each VM.
- async list_dir(path='/')[source]¶
List session directory entries relative to the filesystem root.
- Return type:
DirectoryList- Returns:
Directory entries and their filesystem metadata.
- async observe(event, error)[source]¶
Observe the operation’s sole reader without depending on handle.wait().
- Return type:
None
- property phase: Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']¶
- prepare_request(request)[source]¶
Apply the wrapped session’s policy and validate shared-VM semantics.
- Return type:
- Returns:
The effective request.
- Raises:
ValueError – The request needs a disposable VM or startup-only options.
- async read_file(path)[source]¶
Read current files without stopping an active VM.
- Return type:
bytes- Returns:
The complete file as bytes.
- async run(command=None, **kwargs)[source]¶
Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
- Return type:
InstanceResult- Returns:
The subprocess result, including a nonzero exit code.
- async snapshot(*, timeout=None)[source]¶
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.
- Return type:
HistoryEntry|None- Returns:
The saved history entry, or None if no VM has run yet.
- async spawn_request(request)[source]¶
Start a subprocess; track its exit even if the caller never waits.
- Return type:
- Returns:
The subprocess handle from the operation factory.
- async write_file(path, content)¶
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.
- Return type:
None
-
session_id:
str¶
- class contree_sdk.session.AsyncOperation(client, operation_uuid, *, timeout=None, shutdown_timeout=10.0, files=(), context=None)[source]¶
Handle to a spawned instance operation, identified by its UUID.
- add_observer(observer)[source]¶
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.
- Return type:
None
- async apply_files(files)[source]¶
Apply already-uploaded files to this running VM.
- Return type:
None
- create_subprocess(spid, events_queue)[source]¶
Create a subprocess handle. Override to return a custom implementation.
- Return type:
- Returns:
A handle consuming the supplied event queue.
- async events(*, since=None, spid=None, timeout=None)[source]¶
Replay buffered events, then follow the shared reader with local filters.
timeout bounds this subscription. Expiry does not cancel the operation.
- Yields:
Events after
sincewhose process matchesspid, when specified.- Raises:
TimeoutError – The subscription did not finish before timeout.
- Return type:
AsyncIterator[OperationEvent]
- open_event_stream()[source]¶
Open the unfiltered source. Override this hook to supply custom events.
- Return type:
AsyncIterator[OperationEvent]- Returns:
The single transport stream consumed by the operation.
- async pipe_stdin(chunks, *, spid=1, close=True, chunk_size=65536)[source]¶
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.
- Return type:
- Returns:
Acknowledged bytes, EOF delivery, and observed early completion.
- Raises:
ValueError – chunk_size or spid is not positive.
- async run(command, *, shell=False, args=(), env=None, cwd=None, uid=None, gid=None, stdin=None, stdin_open=False, truncate_output_at=None)[source]¶
- Return type:
-
uuid:
str¶
-
context:
OperationContext|None¶
-
response:
OperationResponse|None¶
- class contree_sdk.session.AsyncOperationContract[source]¶
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
- add_observer(observer)[source]¶
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.
- Return type:
None
- abstractmethod events(*, since=None, spid=None, timeout=None)[source]¶
- Return type:
AsyncIterator[OperationEvent]
- abstractmethod async pipe_stdin(chunks, *, spid=1, close=True, chunk_size=65536)[source]¶
- Return type:
- abstractmethod async run(command, *, shell=False, args=(), env=None, cwd=None, uid=None, gid=None, stdin=None, stdin_open=False, truncate_output_at=None)[source]¶
- Return type:
-
uuid:
str¶
-
context:
OperationContext|None¶
-
response:
OperationResponse|None¶
- class contree_sdk.session.AsyncSubprocessContract[source]¶
Waitable event stream for one subprocess. Iteration and wait share completion state.
-
spid:
int¶
-
spid:
- class contree_sdk.session.AsyncSubprocessHandle(operation, spid, events_queue)[source]¶
Both awaitable (final result) and async-iterable (live events) for one spid.
-
spid:
int¶
-
spid:
- class contree_sdk.session.CommandCountSnapshotPolicy(limit)[source]¶
Request a snapshot after exactly limit command admissions in one VM.
- notify(event)[source]¶
Handle an execution event without blocking or performing network I/O.
- Return type:
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.
- Return type:
Future[None]- Returns:
A future shared by all readers of the current policy decision.
- class contree_sdk.session.CompositeSnapshotPolicy(*policies)[source]¶
Request a snapshot when any child policy’s future completes.
- notify(event)[source]¶
Handle an execution event without blocking or performing network I/O.
- Return type:
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.
- Return type:
Future[None]- Returns:
A future shared by all readers of the current policy decision.
- class contree_sdk.session.ContreeAsyncSession(client, *, image=None, session_id=None, node_id=None, tree_kind='session', store=None, file_transfer=None, cwd=None, env=None, commit_policy=None)[source]¶
A durable, resumable ConTree session backed by a Store.
- check_operation_endpoint(record)[source]¶
Check the recorded server before using an operation UUID.
- Raises:
ValueError – The current client targets a different endpoint.
- Return type:
None
- async commit_result(operation, *, title=None, branch=None, files=None, data=None)[source]¶
- Return type:
HistoryEntry|None
- create_file_transfer()[source]¶
Create file I/O when no component was supplied.
- Return type:
- Returns:
A file-transfer component using the session client.
- create_inspector(image_uuid)[source]¶
Create a view of one image. Override to customize inspection.
- Return type:
AsyncImageInspector- Returns:
An inspector borrowing the client’s connection and file transfer.
- create_operation(response, context)[source]¶
Construct a lifecycle implementation bound to the supplied operation context.
- Return type:
- Returns:
An implementation of the matching operation lifecycle contract.
- create_operation_record(operation)[source]¶
Serialize an operation context. Override to persist custom request fields.
- Return type:
- Returns:
A pending record without local input sources.
- Raises:
ValueError – The operation does not belong to this session.
- create_pending_run(request, *, branch=None)[source]¶
Create the awaitable/context-manager wrapper for a command.
- Return type:
- Returns:
A one-use wrapper for awaiting or entering the operation.
- create_store()[source]¶
Create the default store when none was supplied.
- Return type:
- Returns:
A new memory store owned by this session.
- async detach(operation)[source]¶
Register an already spawned operation without reading events or closing it.
- Return type:
- Returns:
Its durable record. The caller still owns the live handle.
- Raises:
ValueError – The operation does not belong to this session.
- async execute(request, *, branch=None)[source]¶
Run a request to completion and commit its effective non-disposable result.
- Return type:
InstanceResult- Returns:
The completed process result, including nonzero exit codes.
- async grep(pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]¶
Search session files using the current source’s syntax and limits.
- Return type:
GrepResult- Returns:
Matching lines and the server’s truncation indicator.
- async history()[source]¶
- Return type:
tuple[list[HistoryEntry],dict[str,list[str]]]
- async inspect()[source]¶
Pin the current saved image without starting a VM.
Pending staged attachments appear only after an operation applies them.
- Return type:
AsyncImageInspector- Returns:
A read-only view that borrows this session’s client and file transfer.
- async list_dir(path='/')[source]¶
List session directory entries relative to the filesystem root.
- Return type:
DirectoryList- Returns:
Directory entries and their filesystem metadata.
- async list_operations(*, pending_only=True)[source]¶
- Return type:
tuple[OperationRecord,...]
- Return type:
None
- Return type:
None
- async pending_files(node_id=None)[source]¶
- Return type:
tuple[StagedFile,...]
- prepare_environment(env)[source]¶
Overlay command variables on session defaults without mutating either input.
- Return type:
dict[str,str] |None- Returns:
A fresh mapping, or None when both inputs omit environment variables.
- prepare_request(request)[source]¶
Apply defaults before uploads or execution. Override to validate or transform commands.
- Return type:
- Returns:
The effective command with session defaults applied.
- async resolve_image(image)[source]¶
Resolve a base image. Override to implement an import or registry policy.
- Return type:
str- Returns:
The resolved image UUID.
- async restore_operation(operation_uuid)[source]¶
Recreate a control handle from the persisted source context.
- Return type:
- Returns:
An unentered handle. Use wait_operation to reuse a stored final result.
- restore_operation_context(record)[source]¶
Decode a stored request. Override together with create_operation_record.
- Return type:
- Returns:
Its immutable source context, ready for an operation factory or policy.
- run(command=None, *, shell=None, args=(), env=None, cwd=None, stdin=None, stdin_open=False, files=None, timeout=None, disposable=False, truncate_output_at=None, preserve_env=False, hostname=None, uid=None, gid=None, resources_limits=None, networking=None, branch=None)[source]¶
- Return type:
- async spawn(command=None, *, shell=None, args=(), env=None, cwd=None, stdin=None, stdin_open=False, files=None, timeout=None, disposable=False, truncate_output_at=None, preserve_env=False, hostname=None, uid=None, gid=None, resources_limits=None, networking=None)[source]¶
- Return type:
- async spawn_detached(command=None, **kwargs)[source]¶
Spawn and register a command; options are RunRequest fields.
- Return type:
- Returns:
A durable record whose UUID can be passed to wait_operation.
- async spawn_request(request)[source]¶
Prepare and submit a command, then construct its operation through the factory.
- Return type:
- Returns:
A bound operation whose context records the effective request.
- async submit_request(request, image_uuid, *, files, stdin)[source]¶
Submit prepared input to the transport. Override for transport-level customization.
- Return type:
InstanceSpawnResponse- Returns:
The transport response identifying the spawned operation.
- async wait_operation(operation_uuid, *, timeout=None, branch=None)[source]¶
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.
- Return type:
InstanceResult- Returns:
The stored process result, including nonzero exit codes.
- async write_file(path, content)¶
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.
- Return type:
None
-
session_id:
str¶
- class contree_sdk.session.ContreeSession(client, *, image=None, session_id=None, node_id=None, tree_kind='session', store=None, file_transfer=None, cwd=None, env=None, commit_policy=None)[source]¶
A durable, resumable ConTree session backed by a Store (sync).
- check_operation_endpoint(record)[source]¶
Check the recorded server before using an operation UUID.
- Raises:
ValueError – The current client targets a different endpoint.
- Return type:
None
- commit_result(operation, *, title=None, branch=None, files=None, data=None)[source]¶
- Return type:
HistoryEntry|None
- create_file_transfer()[source]¶
Create file I/O when no component was supplied.
- Return type:
- Returns:
A file-transfer component using the session client.
- create_inspector(image_uuid)[source]¶
Create a view of one image. Override to customize inspection.
- Return type:
ImageInspector- Returns:
An inspector borrowing the client’s connection and file transfer.
- create_operation(response, context)[source]¶
Construct a lifecycle implementation bound to the supplied operation context.
- Return type:
- Returns:
An implementation of the matching operation lifecycle contract.
- create_operation_record(operation)[source]¶
Serialize an operation context. Override to persist custom request fields.
- Return type:
- Returns:
A pending record without local input sources.
- Raises:
ValueError – The operation does not belong to this session.
- create_store()[source]¶
Create the default store when none was supplied.
- Return type:
- Returns:
A new memory store owned by this session.
- detach(operation)[source]¶
Register an already spawned operation without reading events or closing it.
- Return type:
- Returns:
Its durable record. The caller still owns the live handle.
- Raises:
ValueError – The operation does not belong to this session.
- execute(request, *, branch=None)[source]¶
Run a request to completion and commit its effective non-disposable result.
- Return type:
InstanceResult- Returns:
The completed process result, including nonzero exit codes.
- Raises:
ValueError – The operation factory returned an unbound operation.
- grep(pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]¶
Search session files using the current source’s syntax and limits.
- Return type:
GrepResult- Returns:
Matching lines and the server’s truncation indicator.
- history()[source]¶
- Return type:
tuple[list[HistoryEntry],dict[str,list[str]]]
- inspect()[source]¶
Pin the current saved image without starting a VM.
Pending staged attachments appear only after an operation applies them.
- Return type:
ImageInspector- Returns:
A read-only view that borrows this session’s client and file transfer.
- list_dir(path='/')[source]¶
List session directory entries relative to the filesystem root.
- Return type:
DirectoryList- Returns:
Directory entries and their filesystem metadata.
- list_operations(*, pending_only=True)[source]¶
- Return type:
tuple[OperationRecord,...]
- Return type:
None
- Return type:
None
- pending_files(node_id=None)[source]¶
- Return type:
tuple[StagedFile,...]
- prepare_environment(env)[source]¶
Overlay command variables on session defaults without mutating either input.
- Return type:
dict[str,str] |None- Returns:
A fresh mapping, or None when both inputs omit environment variables.
- prepare_request(request)[source]¶
Apply defaults before uploads or execution. Override to validate or transform commands.
- Return type:
- Returns:
The effective command with session defaults applied.
- resolve_image(image)[source]¶
Resolve a base image. Override to implement an import or registry policy.
- Return type:
str- Returns:
The resolved image UUID.
- restore_operation(operation_uuid)[source]¶
Recreate a control handle from the persisted source context.
- Return type:
- Returns:
An unentered handle. Use wait_operation to reuse a stored final result.
- restore_operation_context(record)[source]¶
Decode a stored request. Override together with create_operation_record.
- Return type:
- Returns:
Its immutable source context, ready for an operation factory or policy.
- run(command=None, *, shell=None, args=(), env=None, cwd=None, stdin=None, stdin_open=False, files=None, timeout=None, disposable=False, truncate_output_at=None, preserve_env=False, hostname=None, uid=None, gid=None, resources_limits=None, networking=None, branch=None)[source]¶
- Return type:
InstanceResult
- spawn(command=None, *, shell=None, args=(), env=None, cwd=None, stdin=None, stdin_open=False, files=None, timeout=None, disposable=False, truncate_output_at=None, preserve_env=False, hostname=None, uid=None, gid=None, resources_limits=None, networking=None)[source]¶
- Return type:
- spawn_detached(command=None, **kwargs)[source]¶
Spawn and register a command; options are RunRequest fields.
- Return type:
- Returns:
A durable record whose UUID can be passed to wait_operation.
- spawn_request(request)[source]¶
Prepare and submit a command, then construct its operation through the factory.
- Return type:
- Returns:
A bound operation whose context records the effective request.
- submit_request(request, image_uuid, *, files, stdin)[source]¶
Submit prepared input to the transport. Override for transport-level customization.
- Return type:
InstanceSpawnResponse- Returns:
The transport response identifying the spawned operation.
- wait_operation(operation_uuid, *, timeout=None, branch=None)[source]¶
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.
- Return type:
InstanceResult- Returns:
The stored process result, including nonzero exit codes.
- write_file(path, content)¶
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.
- Return type:
None
-
session_id:
str¶
- class contree_sdk.session.DurationSnapshotPolicy(seconds, *, timer_factory=<function _start_timer>, clock=<built-in function monotonic>)[source]¶
Request a snapshot after a fixed VM lifetime, including startup time.
- notify(event)[source]¶
Handle an execution event without blocking or performing network I/O.
- Return type:
None
- set_duration(seconds)[source]¶
Update the deadline relative to the original VM startup time.
- Raises:
ValueError – The duration is not finite and positive.
- Return type:
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.
- Return type:
Future[None]- Returns:
A future shared by all readers of the current policy decision.
- 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=<factory>)[source]¶
-
applied_files:
tuple[str,...] = ()¶
-
attachments:
tuple[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]]]¶
-
applied_files:
- class contree_sdk.session.IdleSnapshotPolicy(seconds, *, timer_factory=<function _start_timer>)[source]¶
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.
- notify(event)[source]¶
Handle an execution event without blocking or performing network I/O.
- Return type:
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.
- Return type:
Future[None]- Returns:
A future shared by all readers of the current policy decision.
- class contree_sdk.session.LazySession(session, *, snapshot_policy=None, snapshot_timeout=30, vm_timeout=3600)[source]¶
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.
- abort()[source]¶
Discard unsaved work and close. An already running snapshot finishes first.
- Return type:
None
- close(*, timeout=None)[source]¶
Save pending work and close this wrapper, retaining caller-owned resources.
- Raises:
RuntimeError – Saving failed; the cause is available as error.
TimeoutError – The caller’s wait expired; closing continues in the worker.
- Return type:
None
- property error: BaseException | None¶
- grep(pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]¶
Search session files using the current source’s syntax and limits.
- Return type:
GrepResult- Returns:
Matching lines and the server’s truncation indicator.
- inspect(*, timeout=None)[source]¶
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.
- Return type:
SessionInspector- Returns:
A session-bound inspector; creating it starts no VM.
- inspect_snapshot(*, timeout=None)[source]¶
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.
- Return type:
ImageInspector- Returns:
An inspector borrowing the underlying client and file transfer.
- inspection_source(*, timeout=None)[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.
- Yields:
A saved image inspector or an active operation UUID.
- Raises:
RuntimeError – The session fails or closes before inspection starts.
TimeoutError – Admission or VM startup exceeds the timeout.
- Return type:
Iterator[ImageInspector|str]
- keepalive_request()[source]¶
Supply a long-running main process available in the base image.
- Return type:
- Returns:
The non-disposable request used to start each VM.
- list_dir(path='/')[source]¶
List session directory entries relative to the filesystem root.
- Return type:
DirectoryList- Returns:
Directory entries and their filesystem metadata.
- observe(event, error)[source]¶
Observe the operation’s sole reader without depending on handle.wait().
- Return type:
None
- property phase: Literal['cold', 'starting', 'running', 'draining', 'snapshotting', 'failed', 'closed']¶
- prepare_request(request)[source]¶
Apply the wrapped session’s policy and validate shared-VM semantics.
- Return type:
- Returns:
The effective request.
- Raises:
ValueError – The request needs a disposable VM or startup-only options.
- read_file(path)[source]¶
Read current files without stopping an active VM.
- Return type:
bytes- Returns:
The complete file as bytes.
- run(command=None, **kwargs)[source]¶
Run a shared-VM command. Options are RunRequest fields; disposable defaults to False.
- Return type:
InstanceResult- Returns:
The subprocess result, including a nonzero exit code.
- snapshot(*, timeout=None)[source]¶
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.
- Return type:
HistoryEntry|None- Returns:
The saved history entry, or None if no VM has run yet.
- spawn_request(request)[source]¶
Start a subprocess; track its exit even if the caller never waits.
- Return type:
- Returns:
The subprocess handle from the operation factory.
- write_file(path, content)¶
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.
- Return type:
None
-
session_id:
str¶
- class contree_sdk.session.Operation(client, operation_uuid, *, timeout=None, shutdown_timeout=10.0, files=(), context=None)[source]¶
Handle to a spawned instance operation, identified by its UUID.
- add_observer(observer)[source]¶
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.
- Return type:
None
- create_subprocess(spid, events_queue)[source]¶
Create a subprocess handle. Override to return a custom implementation.
- Return type:
- Returns:
A handle consuming the supplied event queue.
- events(*, since=None, spid=None, timeout=None)[source]¶
Replay buffered events, then follow the shared reader with local filters.
timeout bounds this subscription. Expiry does not cancel the operation.
- Yields:
Events after
sincewhose process matchesspid, when specified.- Raises:
TimeoutError – The subscription did not finish before timeout.
- Return type:
Iterator[OperationEvent]
- open_event_stream()[source]¶
Open the unfiltered source. Override this hook to supply custom events.
- Return type:
Iterator[OperationEvent]- Returns:
The single transport stream consumed by the operation.
- pipe_stdin(chunks, *, spid=1, close=True, chunk_size=65536)[source]¶
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.
- Return type:
- Returns:
Acknowledged bytes, EOF delivery, and observed early completion.
- Raises:
ValueError – chunk_size or spid is not positive.
- run(command, *, shell=False, args=(), env=None, cwd=None, uid=None, gid=None, stdin=None, stdin_open=False, truncate_output_at=None)[source]¶
- Return type:
-
uuid:
str¶
-
context:
OperationContext|None¶
-
response:
OperationResponse|None¶
- class contree_sdk.session.OperationContext(request, session_id, image_uuid, parent_id, branch, files=(), attachments=(), detached=False, node_id=<factory>, created_at=<factory>, position_version=0, session_cwd=None, session_env=<factory>)[source]¶
The effective request and history position captured before remote execution.
-
attachments:
tuple[StagedFile,...] = ()¶
-
detached:
bool= False¶
-
files:
tuple[str,...] = ()¶
-
position_version:
int= 0¶
-
session_cwd:
str|None= None¶
-
request:
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]¶
-
attachments:
- class contree_sdk.session.OperationContract[source]¶
An operation lifecycle. wait stores response before returning; cleanup preserves primary errors.
- add_observer(observer)[source]¶
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.
- Return type:
None
- abstractmethod events(*, since=None, spid=None, timeout=None)[source]¶
- Return type:
Iterator[OperationEvent]
- abstractmethod run(command, *, shell=False, args=(), env=None, cwd=None, uid=None, gid=None, stdin=None, stdin_open=False, truncate_output_at=None)[source]¶
- Return type:
-
uuid:
str¶
-
context:
OperationContext|None¶
-
response:
OperationResponse|None¶
- class contree_sdk.session.OperationRecord(*, uuid, session_id, image_uuid, parent_id, branch, title, disposable, request, endpoint='', created_at=0.0, node_id='', session_cwd=None, session_env=<factory>, files=(), attachments=(), response=None, history_id=None)[source]¶
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.
-
attachments:
tuple[StagedFile,...] = ()¶
-
created_at:
float= 0.0¶
-
endpoint:
str= ''¶
-
files:
tuple[str,...] = ()¶
-
history_id:
str|None= None¶
-
node_id:
str= ''¶
- property 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= None¶
-
session_cwd:
str|None= None¶
- to_dict()[source]¶
- Return type:
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]]]
-
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]¶
-
attachments:
- class contree_sdk.session.PendingRun(session, request, *, branch=None)[source]¶
One-use execution wrapper. Await a result or enter an operation context.
- class contree_sdk.session.RunRequest(*, command=None, shell=None, args=(), env=None, cwd=None, stdin=None, stdin_open=False, files=None, timeout=None, disposable=False, truncate_output_at=None, preserve_env=False, hostname=None, uid=None, gid=None, resources_limits=None, networking=None)[source]¶
Command configuration passed through the session’s public extension hooks.
Use
dataclasses.replaceto change a request. Arguments and environment are copied at construction. File sources and stdin remain caller-owned. Exactly one ofcommandandshellmust be supplied. Results are saved by default; usedisposable=Trueto leave session history unchanged.-
args:
tuple[str,...] = ()¶
-
command:
str|None= None¶
-
cwd:
str|None= None¶
-
disposable:
bool= False¶
-
env:
Mapping[str,str] |None= None¶
-
files:
list[str|Path|UploadFileSpec] |dict[str,str|Path|bytes|UploadFileSpec] |None= None¶
-
gid:
int|None= None¶
-
hostname:
str|None= None¶
-
networking:
InstanceNetworking|None= None¶
-
preserve_env:
bool= False¶
-
resources_limits:
InstanceResourcesLimits|None= None¶
-
shell:
str|None= None¶
-
stdin:
Optional[Union[str,bytes,Path,Readable[str],Readable[bytes],AsyncReadable[str],AsyncReadable[bytes]]] = None¶
-
stdin_open:
bool= False¶
-
timeout:
float|timedelta|None= None¶
- property timeout_seconds: float | None¶
- property title: str¶
-
truncate_output_at:
int|None= None¶
-
uid:
int|None= None¶
-
args:
- class contree_sdk.session.SnapshotEvent(*values)[source]¶
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.
- RESET = 'reset'¶
- VM_STARTING = 'vm_starting'¶
- COMMAND_STARTED = 'command_started'¶
- COMMAND_FINISHED = 'command_finished'¶
- INSPECTION_STARTED = 'inspection_started'¶
- INSPECTION_FINISHED = 'inspection_finished'¶
- CLOSE = 'close'¶
- class contree_sdk.session.StdinResult(bytes_sent=0, eof_sent=False, process_exited=False)[source]¶
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.
-
bytes_sent:
int= 0¶
-
eof_sent:
bool= False¶
-
process_exited:
bool= False¶
-
bytes_sent:
- class contree_sdk.session.SubprocessContract[source]¶
Waitable event stream for one subprocess. Iteration and wait share completion state.
-
spid:
int¶
-
spid:
- class contree_sdk.session.SubprocessHandle(operation, spid, events_queue)[source]¶
Both blocking-waitable (final result) and iterable (live events) for one spid.
-
spid:
int¶
-
spid:
- class contree_sdk.session.ZeroExitCommitPolicy[source]¶
Retain a result only when its process exit code is explicitly zero.
- contree_sdk.session.instance_result(op)[source]¶
Get the operation’s InstanceResult.
- Return type:
InstanceResult- Returns:
The InstanceResult from op.metadata.result.
- Raises:
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).