Models and API

The models, operations, base and spec_info modules are produced from the OpenAPI specification by the code generator. The whole API surface lives on ContreeSyncClient / ContreeAsyncClient and is identical for every transport adapter; the async interface mirrors the sync one exactly — methods are awaitable, iterators are asynchronous.

Run a command in a sandbox

response = client.spawn_instance(
    "echo hello world",
    "tag:ubuntu:latest",   # image tag, or a bare image UUID
    shell=True,
    env={"GREETING": "hi"},
    timeout=60,
)
operation_id = response.uuid
response = await client.spawn_instance(
    "echo hello world",
    "tag:ubuntu:latest",   # image tag, or a bare image UUID
    shell=True,
    env={"GREETING": "hi"},
    timeout=60,
)
operation_id = response.uuid

Parameters you do not pass are omitted from the request entirely, so the server-side defaults apply. Passing an explicit None sends a JSON null (models are tri-state: unset ... / None / value):

client.spawn_instance("/bin/true", "tag:ubuntu:latest")
# body: {"command": "/bin/true", "image": "tag:ubuntu:latest"}

client.spawn_instance("/bin/true", "tag:ubuntu:latest", env=None)
# body: {"command": "/bin/true", "image": "tag:ubuntu:latest", "env": null}
await client.spawn_instance("/bin/true", "tag:ubuntu:latest")
# body: {"command": "/bin/true", "image": "tag:ubuntu:latest"}

await client.spawn_instance("/bin/true", "tag:ubuntu:latest", env=None)
# body: {"command": "/bin/true", "image": "tag:ubuntu:latest", "env": null}

Files staged via upload can be injected into the sandbox, stdin is a StreamRepr:

from contree_client import FileSpec, StreamRepr

client.spawn_instance(
    "/bin/sh",
    "tag:ubuntu:latest",
    args=["-c", "wc -l < /work/data.txt"],
    # mode accepts the octal wire string ("0644") or a plain int
    files={"/work/data.txt": FileSpec(uuid=file_uuid, mode=0o644)},
    # StreamRepr.from_bytes()/from_text() pick the encoding for you
    stdin=StreamRepr.from_text("hello\n"),
)
from contree_client import FileSpec, StreamRepr

await client.spawn_instance(
    "/bin/sh",
    "tag:ubuntu:latest",
    args=["-c", "wc -l < /work/data.txt"],
    # mode accepts the octal wire string ("0644") or a plain int
    files={"/work/data.txt": FileSpec(uuid=file_uuid, mode=0o644)},
    # StreamRepr.from_bytes()/from_text() pick the encoding for you
    stdin=StreamRepr.from_text("hello\n"),
)

Wait for an operation

import time

from contree_client import OperationStatus

while True:
    operation = client.get_operation_status(operation_id)
    if operation.status.is_terminal():   # SUCCESS / FAILED / CANCELLED
        break
    time.sleep(1)

if operation.status is OperationStatus.SUCCESS:
    result = operation.metadata.result
    print(result.stdout.value, result.state.exit_code)
    print("result image:", operation.result_image_uuid)
import asyncio

from contree_client import OperationStatus

while True:
    operation = await client.get_operation_status(operation_id)
    if operation.status.is_terminal():   # SUCCESS / FAILED / CANCELLED
        break
    await asyncio.sleep(1)

if operation.status is OperationStatus.SUCCESS:
    result = operation.metadata.result
    print(result.stdout.value, result.state.exit_code)
    print("result image:", operation.result_image_uuid)

Stream operation events (SSE)

iter_operation_events yields typed OperationEvent objects as the server flushes them:

for event in client.iter_operation_events(operation_id, follow=True):
    match event.type:
        case "stdout" | "stderr":
            print(event.type, event.data.value)
        case "exit":
            print("exit code:", event.data.code)
        case "completion":
            print("finished:", event.data.status)
async for event in client.iter_operation_events(operation_id, follow=True):
    match event.type:
        case "stdout" | "stderr":
            print(event.type, event.data.value)
        case "exit":
            print("exit code:", event.data.code)
        case "completion":
            print("finished:", event.data.status)

Use follow_operation_events when the client must reconnect a broken event stream automatically.

Files

import hashlib

payload = b"hello world\n"
uploaded = client.upload_file(payload)           # bytes or a binary file
assert uploaded.sha256 == hashlib.sha256(payload).hexdigest()

# deduplicating upload: hashes locally, probes the server and only
# uploads on a miss (pass sha256=... when you already know the digest)
stored = client.ensure_file(payload)

client.check_file_exists(uploaded.sha256)        # True / False
info = client.get_file(uploaded.sha256)          # uuid, size, timestamps
listing = client.list_files(limit=10, since="1w")
import hashlib

payload = b"hello world\n"
uploaded = await client.upload_file(payload)     # bytes or a binary file
assert uploaded.sha256 == hashlib.sha256(payload).hexdigest()

# deduplicating upload: hashes locally (in a worker thread), probes
# the server and only uploads on a miss
stored = await client.ensure_file(payload)

await client.check_file_exists(uploaded.sha256)  # True / False
info = await client.get_file(uploaded.sha256)    # uuid, size, timestamps
listing = await client.list_files(limit=10, since="1w")

Pagination

Every listing (list_images, list_operations, list_files) mirrors the wire API: one call, one page (limit/offset). The iter_* twins paginate transparently as items are consumed — breaking out of the loop stops fetching. page_size tunes the per-request batch and limit caps the total:

for image in client.iter_images(tagged=True, page_size=500, limit=2000):
    print(image.uuid, image.tag)
async for image in client.iter_images(tagged=True, page_size=500, limit=2000):
    print(image.uuid, image.tag)

Images

from contree_client import ImageImportRegistry

# import from a registry; returns the operation id to poll/stream
operation_id = client.import_image(
    ImageImportRegistry(url="docker://docker.io/busybox:latest"),
    tag="busybox:latest",
)

# tags
image = client.update_image_tag(image_uuid, tag="my/base:latest")
client.delete_image_tag(image_uuid, tag="my/base:latest")

# inspection without spawning anything
image = client.inspect_image(image_uuid)
listing = client.inspect_image_list(image_uuid, "/etc")
content = client.inspect_image_download(image_uuid, "/etc/hosts")
exists = client.check_image_file(image_uuid, "/etc/hosts")
from contree_client import ImageImportRegistry

# import from a registry; returns the operation id to poll/stream
operation_id = await client.import_image(
    ImageImportRegistry(url="docker://docker.io/busybox:latest"),
    tag="busybox:latest",
)

# tags
image = await client.update_image_tag(image_uuid, tag="my/base:latest")
await client.delete_image_tag(image_uuid, tag="my/base:latest")

# inspection without spawning anything
image = await client.inspect_image(image_uuid)
listing = await client.inspect_image_list(image_uuid, "/etc")
content = await client.inspect_image_download(image_uuid, "/etc/hosts")
exists = await client.check_image_file(image_uuid, "/etc/hosts")

Archives can be arbitrarily large, so inspect_image_archive is stream-only. By default the chunks are a plain tar; compressed=True disables transparent decompression, yielding the body exactly as served — a ready-to-save .tar.gz when the server compresses the response:

with open("etc.tar", "wb") as archive:
    for chunk in client.inspect_image_archive(image_uuid, "/etc"):
        archive.write(chunk)

with open("etc.tar.gz", "wb") as archive:
    for chunk in client.inspect_image_archive(image_uuid, "/etc", compressed=True):
        archive.write(chunk)
with open("etc.tar", "wb") as archive:
    async for chunk in client.inspect_image_archive(image_uuid, "/etc"):
        archive.write(chunk)

with open("etc.tar.gz", "wb") as archive:
    async for chunk in client.inspect_image_archive(
        image_uuid, "/etc", compressed=True
    ):
        archive.write(chunk)

File downloads have a streaming variant too (inspect_image_download_stream).

Error handling

Every buffered response status of 400 or greater maps to APIStatusError. Known statuses use a specific subclass. The exception contains status, error, traceback, and retry_after.

from contree_client import (
    APIStatusError,
    AuthenticationError,  # 401
    GoneError,        # 410 - retry after error.retry_after seconds
    NotFoundError,    # 404
    TooEarlyError,    # 425 - not ready yet, retry after error.retry_after
)

try:
    client.inspect_image(image_uuid)
except NotFoundError:
    ...
except TooEarlyError as error:
    time.sleep(error.retry_after or 1)
except APIStatusError as error:
    print(error.status, error.error)
from contree_client import (
    APIStatusError,
    AuthenticationError,  # 401
    GoneError,        # 410 - retry after error.retry_after seconds
    NotFoundError,    # 404
    TooEarlyError,    # 425 - not ready yet, retry after error.retry_after
)

try:
    await client.inspect_image(image_uuid)
except NotFoundError:
    ...
except TooEarlyError as error:
    await asyncio.sleep(error.retry_after or 1)
except APIStatusError as error:
    print(error.status, error.error)

400 → BadRequestError, 401 → AuthenticationError, 403 → PermissionDeniedError, 404 → NotFoundError, 409 → ConflictError, 410 → GoneError, 422 → UnprocessableEntityError, 425 → TooEarlyError, 429 → RateLimitError, >=500 → ServerError. Other error statuses use APIStatusError directly.

Exception hierarchy

Normalized request failures inherit ContreeError:

ContreeError
├── APIConnectionError
└── APIStatusError
    ├── BadRequestError              # 400
    ├── AuthenticationError          # 401
    ├── PermissionDeniedError        # 403
    ├── NotFoundError                # 404
    ├── ConflictError                # 409
    ├── GoneError                    # 410
    ├── UnprocessableEntityError     # 422
    ├── TooEarlyError                # 425
    ├── RateLimitError               # 429
    └── ServerError                  # >=500

APIConnectionError covers backend failures in an adapter’s request() and stream() methods. The backend exception remains the standard Python __cause__ for diagnostics. HTTP failures use APIStatusError in both methods. timed_out is true for backend timeouts; operation deadlines are checked separately.

from contree_client import APIConnectionError

try:
    client.whoami()
except APIConnectionError as error:
    print(error)
    print(error.__cause__)

Client-side argument errors remain ValueError or TypeError. Operation helper deadlines raise TimeoutError. Cancellation, KeyboardInterrupt, and SystemExit are not wrapped.

Models

Models are plain dataclasses generated from the spec. from_dict parses wire payloads (missing key → unset ..., explicit null → None), to_dict serializes back omitting unset fields; the spec descriptions, examples and defaults are attached as dataclasses.field(metadata=...).

Text formatting

These models provide as_text(). Each model defines __str__ = as_text, so str(model) and f-strings use the default text format. repr(model) keeps the dataclass representation. Formatting does not change fields or to_dict().

Model

Text representation

GrepMatch

One path:line:text row; context uses - instead of :.

GrepResult

Rows in response order, with -- between disjoint context groups.

DirectoryList

An ls -l-style table; as_text(short=True) returns paths only.

StreamRepr

Decoded stream content.

EventDataStream

Decoded event content.

ClosableStreamRepr

Decoded stdin content; close does not affect formatting.

Grep and directory formats end nonempty output with a newline. Use print(model, end="") to avoid an extra newline. Empty collections return "". GrepResult.truncated remains separate from the formatted output.

Directory tables use the returned owner and group names, with numeric IDs as fallbacks for empty names. Modification times use UTC. Symlinks include their targets. Formatting preserves response order and adds no total header.

Stream models decode base64 as UTF-8 and replace invalid UTF-8 bytes. Invalid base64 follows the existing lenient decoder: undecodable payloads return empty text. ASCII payloads retain their text, including existing newlines. ClosableStreamRepr treats omitted encoding as ASCII. Its as_bytes(), from_bytes(), and from_text() helpers use the same rules as StreamRepr; constructors leave close unset so the server default applies.

Reference

contree_client.base

Base client classes with the full generated API surface.

Generated by codegen from the OpenAPI spec - do not edit.

contree_client.base.deadline_limits_timeout(deadline, timeout)[source]
Parameters:
Return type:

bool

contree_client.base.deadline_due(deadline, timeout_limited=False)[source]
Parameters:
  • deadline (float | None)

  • timeout_limited (bool)

Return type:

bool

class contree_client.base.ContreeClientBase(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None)[source]

Bases: object

Shared configuration, URL and header building.

Implementations replace log with a child logger named after the backend; raw request/response logging happens here so every transport reports uniformly.

Parameters:
log: Logger = <Logger contree_client (ERROR)>
UA_PRODUCT = 'contree-client/editable'
UA_TRANSPORT_LIBRARY = ''
UA_PYTHON_VERSION = 'Python/3.14.10'
UA_PLATFORM = 'Linux-7.0.0-1017-azure-x86_64-with-glibc2.39'
classmethod from_profile(profile=None, *, config_path=None, **kwargs)[source]

Create a client from a saved Contree profile.

Resolution order: explicit profile argument, then the CONTREE_PROFILE environment variable, then the active profile recorded in the config file.

Parameters:
Return type:

TClient

build_url(spec)[source]
Parameters:

spec (RequestSpec)

Return type:

str

build_headers(spec)[source]

Build the request headers as an ordered iterable of pairs.

Pairs, not a mapping: RFC 9110 allows repeated field names, which a dict cannot represent. Transports whose libraries only accept mappings collapse it themselves.

Parameters:

spec (RequestSpec)

Return type:

Iterable[tuple[str, str]]

user_agent()[source]

Compose the User-Agent from the UA_* product tokens.

The caller’s identity (constructor kwarg) leads, so an application announces itself without erasing the library and transport tokens.

Return type:

str

log_request(spec)[source]

Log the raw outgoing request; secrets are redacted.

Parameters:

spec (RequestSpec)

Return type:

None

log_response(spec, response)[source]

Log the raw buffered response.

Parameters:
Return type:

None

class contree_client.base.ContreeSyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None)[source]

Bases: ContreeClientBase, ABC

Synchronous Contree API client interface.

Backend implementations only provide request(), stream() and close().

Parameters:
abstractmethod request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

abstractmethod stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

abstractmethod close()[source]

Release the underlying transport resources.

Return type:

None

open()[source]

Eagerly initialize the underlying transport.

Called by __enter__. Backends that create their resources lazily override this; the default is a no-op.

Return type:

None

call(spec)[source]

Execute a buffered request, retrying per the client policy.

Without a policy this is a transparent single request(). Streaming requests are never routed here - SSE consumers reconnect with Last-Event-Id instead.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

operation_terminal(operation_id, deadline=None)[source]

Best-effort check that the operation reached a terminal state.

Parameters:
  • operation_id (str)

  • deadline (float | None)

Return type:

bool

wait_operation(operation_id, *, timeout=None, follow_events=None, idle_timeout=15.0)[source]

Wait for the terminal operation response.

follow_events=None follows instance events and polls image imports every 0.5 seconds. Use True to force events or False to force polling. Keep the event stream open until completion, EOF, a transport error, or a timeout. idle_timeout is the maximum gap between incoming data chunks in seconds (default 15.0; 0 disables it). Ping/keepalive traffic resets this limit; it does not extend the overall timeout. Gaps between payload events do not trigger checks. After completion, poll until the status is terminal. Return failed and cancelled responses unchanged. timeout covers the entire wait and raises TimeoutError on expiry. Sync buffered reads can delay the exception until the response ends.

Parameters:
  • operation_id (str)

  • timeout (float | None)

  • follow_events (bool | None)

  • idle_timeout (float)

Return type:

OperationResponse

follow_operation_events(operation_id, *, last_event_id=None, spid=None, since=None, timeout=None, idle_timeout=15.0)[source]

Stream operation events with transparent reconnection.

Native stream failures trigger a terminal-status probe and a reconnect from the last event id. Iteration ends at the completion event or the timeout. After a terminal status, drain the retained log without following before ending iteration. Interrupted retained reads resume from the last event id, using the configured retry policy (three attempts by default). Normal EOF also completes a filtered or explicitly resumed retained log. An unfiltered log must include completion. An unavailable or incomplete event log raises APIConnectionError. The timeout is an absolute deadline checked whenever iteration resumes. Caller code between events is not interrupted. A synchronous native read can delay TimeoutError until it returns. idle_timeout bounds gaps between incoming data in seconds (default 15.0; 0 disables it). Ping/keepalive traffic resets this limit without extending the overall timeout.

Parameters:
  • operation_id (str)

  • last_event_id (int | None)

  • spid (int | None)

  • since (int | None)

  • timeout (float | None)

  • idle_timeout (float)

Return type:

Iterator[OperationEvent]

resolve_image(ref)[source]

Resolve an image reference to a UUID.

Accepts a raw UUID, tag:NAME or a bare tag name.

Parameters:

ref (str)

Return type:

str

ensure_file(content, *, sha256=None)[source]

Upload content unless the server already stores it.

The digest (sha256 when the caller already knows it, computed locally otherwise) is probed via get_file(); only a miss uploads. Returns the stored file record either way (both shapes carry uuid, sha256 and size). Non-seekable streams cannot be hashed and rewound, so without a caller-provided sha256 they skip deduplication and upload directly.

Parameters:
Return type:

FileResponse | File

list_network_policies(*, search=None, limit=None, offset=None)[source]

List network policies.

Returns policies in your namespace and the shared namespace. Deleted policies are excluded. Reusing or restoring a policy does not change its creation time or listing position. Each entry contains the policy UUID, creation timestamp, accessible tags, and a summary with the number of IP rules. Tags are sorted by name. Your tag takes precedence over a shared tag with the same name; the overridden shared binding is omitted. Use GET /network/policies/{uuid} to retrieve the full rules. Requires spawn or spawn_disposable permission.

Search: Supply search to find active policies in your namespace and the shared namespace that allow the destination. The input determines the search type; currently only IPv4 and IPv6 addresses and CIDRs are supported. Domains and other unsupported inputs return 400. An omitted search parameter lists policies normally; an empty value returns 400.

Use [tcp://|udp://]address-or-cidr[:port]. IPv6 addresses and CIDRs must be enclosed in brackets when specifying a port, with the prefix length inside the brackets. Examples: 192.0.2.1, 192.0.2.0/24:443, tcp://192.0.2.0/24:443, and udp://[2001:db8::/64]:53. This is search syntax, not a URL. CIDRs must use their network address; host bits, scoped IPv6 addresses, and ports outside 1-65535 return 400.

A match must allow the requested protocol and port throughout the entire CIDR, not merely overlap it. An IP address is treated as a /32 or /128 CIDR. All-port rules match every requested port. If protocol or port is omitted, any single protocol/port combination covering the entire destination matches. Complementary subnets granting that same access are normalized into a covering rule. Permissions from different policies are never combined for search. Empty policies do not match. Filtering happens before pagination, and results retain the same order, summary, timestamp, and tags as the normal listing.

Parameters:
  • search (str | None) – IP or CIDR search, optionally qualified by TCP/UDP and a destination port.

  • limit (int | None) – Maximum number of results to return. Invalid values raise 400 error.

  • offset (int | None) – Number of results to skip. Invalid values raise 400 error.

Return type:

NetworkPolicyListResponse

create_network_policy(cidrs)[source]

Create a network policy.

Creates a policy with immutable rules in the caller’s namespace. Requires network_policy permission.

Rules

  • Each rule allows a CIDR for the selected protocol and ports. An empty or omitted port list allows all ports.

  • ICMP is allowed to every listed CIDR, regardless of protocol or ports.

  • An empty rules array (cidrs: []) blocks all IP egress, including ICMP and traffic to the host.

  • ARP is blocked for all policies.

Limits

The same limit of 16384 units applies before and after normalization. Sum the number of ports across all rules, counting an empty or omitted port list (all ports) as 1. The limit covers the entire policy, across all IP versions and protocols. Duplicates count toward the limit before normalization. Exceeding the limit returns 400, even if normalization would remove redundant rules or ports.

Normalization

Before storage, duplicate rules and ports are removed, CIDRs are merged per protocol and port, and rules and ports are sorted. This preserves the allowed traffic. The response contains the normalized rules.

Policy identity

Equivalent normalized policies in the same namespace reuse the same UUID, including concurrent requests. The UUID is UUIDv5 derived from the namespace and the normalized policy hash. Resubmitting a deleted policy restores it without restoring its tags. To change the rules, create a new policy.

Parameters:

cidrs (list[NetworkPolicyCIDRRule])

Return type:

NetworkPolicy

get_network_policy(uuid)[source]

Get a network policy.

Returns an accessible policy, including deleted policies. Returns 404 if the policy does not exist. Requires spawn or spawn_disposable permission.

Parameters:

uuid (str) – Network policy UUID Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

NetworkPolicy

delete_network_policy(uuid)[source]

Remove a network policy.

Removes a policy in your namespace. Requires network_policy permission. Returns 204 if the policy is removed or was already removed. Returns 404 if the policy does not exist in your namespace. Removes its tags and excludes it from listings. The policy remains accessible and usable by UUID, but cannot be assigned to tags.

Parameters:

uuid (str) – Network policy UUID Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

None

list_network_policy_tags(*, limit=None, offset=None)[source]

List network policy tags.

Returns your tags and shared tags, ordered by name. Your tag takes precedence when a shared tag has the same name. Requires spawn or spawn_disposable permission.

Parameters:
  • limit (int | None) – Maximum number of results to return. Invalid values raise 400 error.

  • offset (int | None) – Number of results to skip. Invalid values raise 400 error.

Return type:

ListNetworkPolicyTagsResponse

get_network_policy_tag(tag)[source]

Get a network policy tag.

Redirects to the policy referenced by your tag, or the shared tag if you have no tag with that name. The redirect response includes the effective tag binding as JSON. Requires spawn or spawn_disposable permission. Returns 404 if the tag or its target policy does not exist or is removed.

Parameters:

tag (str) – Network policy tag name

Return type:

NetworkPolicyTag

set_network_policy_tag(tag, uuid)[source]

Bind a tag to a network policy.

Creates or replaces your tag’s binding to an active policy in your namespace or the shared namespace. Repeating the same binding has no effect. Returns 404 if the target policy does not exist, is inaccessible, or is removed. The tag belongs to your namespace. Requires network_policy permission.

Parameters:
  • tag (str) – Network policy tag name

  • uuid (str)

Return type:

NetworkPolicyTag

delete_network_policy_tag(tag)[source]

Remove a network policy tag.

Removes your tag, including when operations use its policy. Repeated deletion succeeds. If a shared tag has the same name, it becomes visible again. Requires network_policy permission.

Parameters:

tag (str) – Network policy tag name

Return type:

None

list_images(*, limit=None, offset=None, tagged=False, tag=None, uuid=None, since=None, until=None)[source]

List publicly available images.

Returns a list of all publicly available container images.

Parameters:
  • limit (int | None) – Maximum number of images to return. Must be between 1 and 1000. Default is 100. Invalid values raise 400 error.

  • offset (int | None) – Number of images to skip before starting to collect the result set. Default is 0. Invalid values raise 400 error.

  • tagged (bool) – Example: 1.

  • tag (str | None) – A valid image tag prefix to filter images by this prefix. Only images with tags starting with. Implies tagged parameter. Example: ubuntu.

  • uuid (str | None) – Filter images by UUID Example: 12345678-9abc-baba-deda-0123456789ab.

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

Return type:

ImageListResponse

iter_images(*, tagged=False, tag=None, uuid=None, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_images() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • tagged (bool) – Example: 1.

  • tag (str | None) – A valid image tag prefix to filter images by this prefix. Only images with tags starting with. Implies tagged parameter. Example: ubuntu.

  • uuid (str | None) – Filter images by UUID Example: 12345678-9abc-baba-deda-0123456789ab.

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

Iterator[Image]

delete_image_tag(image_uuid, *, tag=None)[source]

Remove tags from an image.

Removes a tag (or all tags) from an image.

When tag query parameter is provided, only that specific tag is removed. When omitted, all tags are removed from the image.

If any public image has the same tag, tag will start tracking that public image again.

In all other cases tag will be removed and the image will be accessible only by its UUID.

Parameters:
  • image_uuid (str) – The UUID of the image to untag Example: 12345678-9abc-baba-deda-0123456789ab.

  • tag (str | None) – The tag to remove. If omitted, all tags are removed from the image. Example: busybox:latest.

Return type:

None

update_image_tag(image_uuid, tag)[source]

Add a tag to an image.

Adds a tag to an image. Tags are unique per namespace; if the requested tag is already assigned to another image, it will be moved to this image.

Assigning a tag that matches a public tag to a public image will freeze that tag to the current image - subsequent public updates to the tag will not affect it. To make the public tag track the latest public image again, remove your tag assignment.

When a tag is removed from an image that resides in the public namespace, the API returns HTTP 200 OK. response body contains the tag that now points to the public image (i.e., the image that the tag is automatically re-assigned to).

In other words, un-tagging a public image does not delete the tag; it simply moves the tag back to the public image and the caller receives that tag in the successful response.

Parameters:
  • image_uuid (str) – The UUID of the image to update Example: 12345678-9abc-baba-deda-0123456789ab.

  • tag (str) – New tag for the image Example: busybox:latest.

Return type:

Image

import_image(registry, *, tag=Ellipsis, timeout=Ellipsis)[source]

Import a container image from a registry.

Imports the OCI image filesystem content of from a specified registry.

Important limitations and behavior:

  • Only the image root filesystem (files and directories) is imported. This is like to the output of docker export and does not preserve layers metadata.

  • Most image configuration and manifest data are ignored. Metadata such as LABEL, ENTRYPOINT, CMD, WORKDIR, EXPOSE and other image configuration directives will NOT be imported or applied.

  • ENV variables defined in the image are imported and automatically applied to the instance environment when shell is set to true. When shell is false, image environment variables are not inherited and must be passed explicitly via the env field.

  • The result is a flat rootfs snapshot with preserved environment variables.

  • If the specified tag already exists in the public images, the imported image will replace it. To avoid this, you can tag the existing image with a different tag for use it later. You also can use image UUIDs it is not changing for imported and existend image.

  • In case the remote image is unchanged and already imported, the operation will complete and the same UUID will be returned without re-importing the image.

The request creates an import operation which runs asynchronously.

Parameters:
  • tag (str | None | EllipsisType) – Tag to identify the image when listing publicly available images. If omitted, the image will be private and only accessible by ID. Example: busybox:latest.

  • timeout (int | EllipsisType) – Maximum time in seconds to wait for the import operation to complete Example: 300.

  • registry (ImageImportRegistry)

Return type:

str

list_files(*, limit=None, offset=None, since=None, until=None)[source]

List uploaded files for the current namespace.

Returns a paginated list of uploaded files for the current namespace.

Parameters:
  • limit (int | None) – Maximum number of files to return

  • offset (int | None) – Number of files to skip

  • since (str | int | float | datetime | None) – Filter files created after this time

  • until (str | int | float | datetime | None) – Filter files created before this time

Return type:

FilesListResponse

iter_files(*, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_files() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • since (str | int | float | datetime | None) – Filter files created after this time

  • until (str | int | float | datetime | None) – Filter files created before this time

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

Iterator[File]

upload_file(content)[source]

Upload a file to the server. the body must be a file content.

Uploads a file to the server. The body must contain the file content.

Parameters:

content (bytes | IO[bytes]) – Raw file content: bytes or a binary stream.

Return type:

FileResponse

get_file(sha256)[source]

Get file info by SHA256.

Returns file info (uuid, sha256, created_at, updated_at).

Parameters:

sha256 (str) – SHA256 hash of the file (64 hex characters)

Return type:

File

check_file_exists(sha256)[source]

Check if a file exists for the current namespace.

Returns 200 if the file is uploaded by the current namespace, otherwise 404.

Parameters:

sha256 (str) – SHA256 hash of the file (64 hex characters)

Return type:

bool

spawn_instance(command, image, *, disposable=Ellipsis, hostname=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, preserve_env=Ellipsis, preserve_cwd=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, resources_limits=Ellipsis, networking=Ellipsis, stdin=Ellipsis, timeout=Ellipsis, truncate_output_at=Ellipsis, files=Ellipsis)[source]

Spawn a new container instance.

Creates and runs a new execution instance with the specified configuration. Requires a valid Authorization header.

Common request body rules:

  • The request body must contain at least command and image fields all other fields can be omitted.

  • If the command field is a shell expression, you must set shell field to true.

  • For specifying the shell binary, you can use env field to set SHELL variable.

  • When shell is true, environment variables defined in the image (via ENV directives) are automatically inherited. When shell is false, image environment variables are not inherited and must be passed explicitly via the env field.

Parameters:
  • command (str) – The command to execute. In case if shell is set to true, this MUST contain shell expression. For example echo hello world or ls -l /app. If shell is set to false, this must be a relative or absolute path to the executable inside the image rootfs. For example: /bin/app or /usr/bin/find. Do not forget pass necessary PATH variable to env field, by default PATH is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Example: /bin/app.

  • disposable (bool | EllipsisType) – Creates a disposable execution environment no any state will be saved.

  • hostname (str | EllipsisType) – Hostname to set when execution. Example: container-name.

  • args (list[str] | EllipsisType) – Arguments to pass to the command if shell is set to false. Example: ["arg1","arg2"].

  • shell (bool | EllipsisType) – Whether to run the command through a shell. If true, the command must be a shell expression and all values from args will be ignored. If false, the command field must be a path to an executable and args will be used. When true, environment variables from the image are automatically inherited. When false, they are not - use the env field to pass them explicitly.

  • env (dict[str, str] | None | EllipsisType) – Environment variables to set in the container. These are merged with image-defined variables when shell is true. When shell is false, only variables specified here are available - image-defined variables are not inherited. Example: {"KEY1":"value1","KEY2":"value2"}.

  • preserve_env (bool | EllipsisType) – Preserve environment variables in resulting image after execution. When true, the image’s existing environment variables from metadata/env are merged with user-provided env values (user values take priority on conflicts), and the combined result is written back to metadata/env after command execution. Setting a variable to an empty string or null removes it from the preserved environment.

  • preserve_cwd (bool | EllipsisType) – Save the resolved initial working directory as the default in the resulting image. An empty or omitted cwd resolves to the image’s current workdir, or / if none exists. The metadata file is opened for writing only when its contents differ from the new value. Directory changes made by the command do not change the saved value. Requires disposable: false to retain the metadata in a resulting image.

  • cwd (str | EllipsisType) – Path to the working directory, must be absolute or a special value the empty string. It means the default working directory of the image or server default will be used. If field is omitted it will be set to the empty string. The directory will be created automatically if it does not exist. Example: /app.

  • uid (int | EllipsisType) – User ID to run the process as. Example: 0.

  • gid (int | EllipsisType) – Group ID to run the process as. Example: 0.

  • timeout (int | EllipsisType) – Maximum execution time in seconds Example: 60.

  • truncate_output_at (int | EllipsisType) – Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect stdin delivery to the child, which always receives the complete stream regardless of this cap. Default is 1048576 (1 MiB). The maximum value is 10485760 (10 MiB). Example: 65535.

  • files (dict[str, FileSpec] | EllipsisType) – Map of absolute file paths to file metadata Example: {"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c....

  • image (str)

  • resources_limits (InstanceResourcesLimits | EllipsisType)

  • networking (InstanceNetworking | EllipsisType)

  • stdin (ClosableStreamRepr | EllipsisType)

Return type:

InstanceSpawnResponse

list_operations(*, limit=None, offset=None, status=None, kind=None, since=None, until=None)[source]

List operations.

Returns a list of running and completed operations

Parameters:
  • limit (int | None) – Maximum number of operations to return. Must be between 1 and 1000. Default is 100. Invalid values raise 400 error.

  • offset (int | None) – Number of operations to skip before starting to collect the result set. Default is 0. Invalid values raise 400 error.

  • status (OperationStatus | str | None) – Filter operations by their state

  • kind (Literal['image_import', 'instance'] | None) – Filter operations by their kind

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

Return type:

list[OperationSummary]

iter_operations(*, status=None, kind=None, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_operations() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • status (OperationStatus | str | None) – Filter operations by their state

  • kind (Literal['image_import', 'instance'] | None) – Filter operations by their kind

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

Iterator[OperationSummary]

get_operation_status(operation_id, *, inflight=False)[source]

Get an operation status.

Returns the status of an operation.

For an EXECUTING INSTANCE operation, pass ?inflight=1 to also synthesize the partial result.stdout / result.stderr from the live event log. Off by default — each fetch with inflight triggers an extra subscribe RPC to the guest and drains its current events.gz, which is wasted work for clients that only poll for status transitions.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • inflight (bool) – HTTP-flag boolean. Present without a value (?inflight) and ?inflight=1 both enable; ?inflight=0 and absence disable. When enabled and the operation is EXECUTING INSTANCE, partial stdout/stderr is synthesized from the live event log and attached under result.

Return type:

OperationResponse

cancel_operation(operation_id)[source]

Cancel an operation.

Cancels an operation

Parameters:

operation_id (str) – The ID of the import operation to cancel Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

None

iter_operation_events(operation_id, *, follow=False, spid=None, since=None, last_event_id=None, deadline=None, idle_timeout=0.0)[source]

Stream the operation event log via Server-Sent Events.

Always returns text/event-stream (SSE) on success. The body is a sequence of three kinds of lines (per RFC W3C SSE), each terminated by \n\n:

Frame shapes

Normal event frame — one OperationEvent JSON object in data:, dispatchable via event::

id: <integer event.id>
event: <OperationEventType, e.g. stdout|stderr|spawn|exit>
data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}}

event: always matches data.type. See OperationEvent and OperationEventType for the per-type payload shape. Native EventSource dispatches each frame to the matching addEventListener("<type>", ...) handler.

Server-side error frame — surfaces handler exceptions to the connected client without tearing the TCP connection down mid-stream. Sent right before the server closes the response:

: stream ended with error, retry since last event id

event: sse_error
data: <one-line exception message>

The leading SSE comment line lets pure-EventSource clients see the intent (“retry from Last-Event-Id”); the sse_error frame carries the error text for logging. Clients should treat this as a non-clean close and reconnect with the standard SSE Last-Event-Id semantics (see Resuming).

Keepalive comment — periodic : keepalive\n\n lines emitted while the stream is idle. They keep upstream proxy_read_timeout / TCP idle timers fresh and have no application meaning. Spec-compliant; EventSource and any SSE parser must ignore comment lines (those beginning with :).

follow semantics

The follow parameter controls only whether the stream stays open after the last currently-known event:

  • follow=0 (default) — the server emits everything currently available and closes the connection.

  • follow=1 — same start; if the operation is still running the server keeps the connection open and forwards new events as they appear. For terminal operations follow=1 is a no-op: there’s nothing more to subscribe to, so the connection closes after the last event just like follow=0.

Optional filters:

  • ?spid=N — only events whose spid (Spawned Process ID, the routing identity in OperationEvent) matches.

  • ?since=N — only events with id > N.

follow=1 requires SPAWN or SPAWN_DISPOSABLE on top of the baseline LIST — a long-lived subscription reserves per-operation server state. follow=0 is read-only and stays under LIST.

Resuming after a drop

Every normal frame carries id: — the canonical event id. On reconnect send the last successfully received id in the standard Last-Event-Id request header (or ?since=N on manual GETs); the server resumes from that point.

Error handling

Status

Meaning

Client action

200

Stream open

Read frames; reconnect with Last-Event-Id if the stream closes before reaching a terminal event

400

Malformed query/header (non-integer param)

Fix request

401

Missing/invalid auth

Refresh credentials

403

Auth lacks LIST (or SPAWN for follow=1)

Use a token with the right scope

404

Operation not in this namespace

Wrong UUID

410

Stream is over but the terminal artifact isn’t ready yet

Retry after Retry-After

425

Not yet ready (operation is still being prepared)

Retry after Retry-After

502

Upstream returned an error opening the stream

Retry; if persistent, escalate

504

Upstream took too long to respond

Retry

A 200 followed by an event: sse_error frame and immediate close is the in-band equivalent of “the stream broke after we already committed to a 200” — handle it the same way as 410: wait briefly, reconnect with Last-Event-Id.

See OperationEvent for the per-event shape.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • follow (bool) – HTTP-flag boolean. Present without a value (?follow) and ?follow=1 both enable; ?follow=0 and absence disable. When enabled, the SSE stream stays open after the currently-known events have been sent — for a running operation new events are forwarded as they appear; for a terminal operation it has no effect.

  • spid (int | None) – Only emit events whose spid field matches. Filter is applied server-side regardless of whether the operation is still running or already terminal.

  • since (int | None) – Only emit events with id > since (event IDs are monotonically increasing). Overridden by the Last-Event-Id header when present.

  • last_event_id (int | None) – Standard SSE resume header sent automatically by EventSource on reconnect. Treated as ?since=N; takes precedence over the query param.

  • deadline (float | None) – absolute monotonic deadline. Checked whenever iteration resumes; caller code between events is not interrupted.

  • idle_timeout (float) – seconds without incoming data before a transport timeout; 0 disables it

Return type:

Iterator[OperationEvent]

operation_subprocess_create(operation_id, command, *, resources_limits=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, stdin=Ellipsis, truncate_output_at=Ellipsis)[source]

Spawn an additional subprocess inside a running instance.

Starts a new process inside the VM that already hosts the named operation. Distinct from POST /instances, which spins up a VM: this endpoint requires a running operation (EXECUTING or ASSIGNED) and reuses the existing VM.

The body is an ExecSpec — process-execution fields only. VM-level concerns (image, hostname, files, timeout, disposable, preserve_env) are not accepted here; they were set when the parent operation was created.

resources_limits.cpu and resources_limits.memory_mib use the same names and units as operation creation. Each omitted or null subprocess limit inherits the corresponding operation limit. Values above the operation limit return 400. Limits apply at launch: memory_mib sets RLIMIT_AS for each process and memory.max for the entire process tree. They cannot be changed through this API. Guest root can modify limits; these limits do not provide security isolation between processes in one VM.

The required permission follows the parent instance: SPAWN_DISPOSABLE when it was spawned with disposable=true, SPAWN otherwise.

On success the worker assigns a fresh spid (≥2; spid=1 is the main process spawned from metadata) and the response carries it in the body plus a Location header pointing at GET /operations/{operationId}/subprocesses/{spid} — the subprocess result reconstructed from its events.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • command (str) – The command to execute. Same semantics as in InstanceSpawnRequest.command — when shell=true it is a shell expression, otherwise a path to an executable. Example: /bin/app.

  • args (list[str] | EllipsisType) – Arguments to pass to the command if shell is set to false. Example: ["arg1","arg2"].

  • shell (bool | EllipsisType) – Run command through a shell expression (args must be empty).

  • env (dict[str, str] | None | EllipsisType) – Environment variables to set in the child process.

  • cwd (str | EllipsisType) – Working directory; empty string means image / server default.

  • uid (int | EllipsisType) – User ID to run the process as.

  • gid (int | EllipsisType) – Group ID to run the process as.

  • stdin (ClosableStreamRepr | EllipsisType) – Bytes fed to the child’s stdin — honored for both the main process and exec’d subprocesses. With close=false the pipe stays open and more data can be written via POST /operations/{operationId}/subprocesses/{spid}/stdin.

  • truncate_output_at (int | EllipsisType) – Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect delivery to the child — stdin is always delivered in full regardless of this cap. Defaults to 1 MiB; capped at 10 MiB. Example: 65535.

  • resources_limits (ProcessResourcesLimits | EllipsisType)

Return type:

int

operation_subprocess(operation_id, spid)[source]

Result of one subprocess, reconstructed from its events.

Returns an InstanceResult for spid — the same shape as the parent operation’s metadata.result — folded from the subprocess’s event log (spawn / stdout / stderr / exit). Works for running and terminal operations alike. While the process is still running, state.exit_code and state.signal are -1 (unknown) and resources holds sentinel defaults; once the exit event lands they carry the real values.

stdout / stderr are consolidated and capped at the spec’s truncate_output_at. The raw event stream stays available at GET /operations/{operationId}/events?spid={spid}.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

Return type:

InstanceResult

operation_subprocess_kill(operation_id, spid, *, signal=None)[source]

Kill one subprocess.

Sends a signal to the process group of spid inside the running instance. Without the signal parameter the group gets SIGKILL. Termination is observable, not returned: the exit event lands in the event log and GET /operations/{operationId}/subprocesses/{spid} reports the terminal state (signal set, exit_code -1 when killed).

Killing spid=1 (the main process) effectively ends the operation, like letting the command fail.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

  • signal (str | None) – Signal to send instead of SIGKILL — a number (15) or a name with or without the SIG prefix (TERM, SIGTERM). Example: SIGTERM.

Return type:

None

operation_subprocess_stdin(operation_id, spid, value, *, encoding=Ellipsis, close=Ellipsis)[source]

Write to a subprocess’s stdin and/or close it.

Writes a chunk to the stdin of a live process inside the running instance — spid=1 targets the main process, ≥2 the exec’d children. Requires the process to have been started with stdin.close=false; otherwise its pipe is already at EOF and the call returns 409.

close=true (the default) signals EOF after writing value; an empty value with close=true just closes the pipe. A client that serializes its own requests gets ordered writes; concurrent requests to the same spid are safe but their order is unspecified.

A 504 means the guest write timed out mid-call — the chunk may or may not have been delivered (e.g. the process stopped reading and the pipe is full), so blind retries can duplicate data.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

  • value (str) – Content to write to stdin (may be empty for a close-only request) Example: aGVsbG8K.

  • encoding (Literal['ascii', 'base64'] | ~types.EllipsisType) – Encoding of the content

  • close (bool | EllipsisType) – true (default) closes stdin (EOF) after writing value — the pre-existing one-shot behavior. false keeps the pipe open so more data can be sent later via POST /operations/{operationId}/subprocesses/{spid}/stdin.

Return type:

None

apply_instance_file(operation_uuid, file_uuid, path, *, unpack=Ellipsis, replace=Ellipsis, merge=Ellipsis)[source]

Apply an uploaded file to a running instance.

Reads a file previously uploaded through POST /files and writes it to a running INSTANCE operation, including disposable instances. Requires LIST and the permission used to start the instance. Both the operation and the uploaded file must belong to the request namespace. Expired files are unavailable. The assigned worker streams the stored object to the guest through RPC. Init records request metadata in inspect events and the terminal publication result in file_upload, including file_uuid and byte count. File contents do not enter operation events.

With unpack omitted or false, path is the full destination filename. Missing parent directories are created. The file is published atomically after transfer and SHA256 verification. The new file has mode 0644 and is owned by the guest runtime user. With replace true, an existing leaf symlink is replaced. Directories and special files are not regular file destinations.

With unpack true, path is the destination directory. Supports tar, tar.gz and tar.bz2; compression is detected from the stored bytes. Xz is unsupported and rejected before subsequent chunks are sent. Without unpack, compressed archives are copied unchanged. Content-Type describes this JSON request and never controls extraction.

Extraction accepts regular files, directories, symlinks and hardlinks to regular files already extracted in the staging tree. Parent symlinks inside that tree are not followed. Absolute entry names and entries containing ‘..’ are rejected. procfs, sysfs, devices, FIFOs and sockets are unsupported. New directories have mode 0755; regular files retain tar permission bits (0777). Ownership and timestamps are not restored. Other entries fail explicitly. With replace omitted or false, any existing destination returns 409, including a symlink or empty directory. This condition is checked again atomically at publication. replace true permits an existing destination. With merge omitted or false, directory replacement removes the entire old tree without merging contents.

Archives are extracted into a temporary sibling directory. The destination remains unchanged until the complete stream and SHA256 have been verified. Without merge, publication uses an atomic rename or exchange, then removes the old tree. Root and mount-point replacement are unavailable. Existing open descriptors can still refer to old inodes; concurrent workload access is not a snapshot.

merge true requires both unpack true and replace true. After complete staging and verification, it combines directories and atomically replaces individual files and symlinks. Existing entries absent from the archive remain. Destination directory symlinks are not followed; directory/file conflicts fail explicitly. Same-filesystem hardlinks are retained. Crossing a destination mount requires copying file bytes and does not preserve hardlinks across filesystems. Merge is not atomic for the whole tree: errors, cancellation or timeout after application starts can leave completed changes. These changes are not rolled back.

Returns 204 only after completion. Transfers have a 300-second deadline and bounded buffers and handles. Disconnect or VM exit cancels the transfer. A lost response can leave an uncertain outcome; requests are not replayed automatically. This endpoint does not write to a completed result image.

A transfer timeout does not stop the instance. Before publication or merge starts, cancellation preserves the old destination and removes the temporary file or extraction tree. A timeout while awaiting the final response can occur after publication; it does not prove that no changes were made. An old-tree cleanup failure is reported as an error after publication; it does not roll back the new tree. The uploaded source object retains its normal lifetime. Automatically created parent directories have mode 0755 and can remain after errors.

The primary command’s timeout follows normal instance finalization: ordinary instances persist their filesystem, including successfully published uploads; disposable instances do not. Instance shutdown waits for pending upload cleanup. A timeout or crash of the execution environment can bypass this cleanup and does not produce a successfully persisted result image through normal finalization.

Parameters:
  • operation_uuid (str) – Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – Absolute guest filename, or directory when unpack is true. Missing parents are created.

  • unpack (bool | EllipsisType) – Extract tar, tar.gz or tar.bz2 instead of copying the stored bytes.

  • replace (bool | EllipsisType) – Permit an existing destination. Without merge, directories are replaced in full.

  • merge (bool | EllipsisType) – Merge verified archive contents. Requires unpack and replace. Can leave partial changes.

  • file_uuid (str)

Return type:

None

inspect_instance_download(operation_uuid, path)[source]

Download a file from a running instance.

Reads through guest RPC without recording file contents in operation events. Requires LIST and the permission used to start this instance (SPAWN or SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are unavailable. Reads do not form a snapshot. The opened inode and initial size are used; later growth is excluded. Truncation or VM exit interrupts the response. A transfer has a 300-second deadline. No result-image fallback is performed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the running instance, e.g. /etc/hosts

Return type:

bytes

inspect_instance_download_stream(operation_uuid, path)[source]

Streaming variant of inspect_instance_download().

Reads through guest RPC without recording file contents in operation events. Requires LIST and the permission used to start this instance (SPAWN or SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are unavailable. Reads do not form a snapshot. The opened inode and initial size are used; later growth is excluded. Truncation or VM exit interrupts the response. A transfer has a 300-second deadline. No result-image fallback is performed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the running instance, e.g. /etc/hosts

Return type:

Iterator[bytes]

check_instance_file(operation_uuid, path)[source]

Check if a file exists in running instance.

Checks if a file exists in the specified running instance without returning the file content

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to check inside the running instance, e.g. /etc/hosts

Return type:

bool

inspect_instance_list(operation_uuid, path)[source]

List files in running instance.

Lists guest files without recording contents in operation events. Requires LIST and the permission used to start this instance. Reads do not form a snapshot. A directory can contain at most 10000 entries. procfs and sysfs cannot be listed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the directory to inspect inside the running instance Example: /etc.

Return type:

DirectoryList

inspect_instance_archive(operation_uuid, path, *, compressed=False)[source]

Download a file or a directory from running instance as tar archive.

Streams the specified path inside the running instance root filesystem as a POSIX PAX tar archive. A directory becomes the archive root; a regular file becomes a single-entry archive. The response is chunked; total size is not known upfront. Served as an attachment, filename is the path with / replaced by _ plus .tar (e.g. /bin/true -> bin_true.tar). Requires LIST and the permission used to start this instance. Contents do not enter operation events. Reads do not form a snapshot. Traversal skips procfs and sysfs and preserves descendant symlinks. File changes or VM exit can interrupt the stream. Transfers have a 300-second deadline.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to archive inside the running instance, e.g. /etc

  • compressed (bool) – disable transparent decompression: the body is yielded exactly as served - a tar.gz stream when the server compresses the response, a plain tar otherwise.

Return type:

Iterator[bytes]

check_instance_archive(operation_uuid, path)[source]

Check if a path can be archived from running instance.

Checks if a file or a directory exists in the specified running instance without streaming the archive

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to check inside the running instance, e.g. /etc

Return type:

bool

inspect_find_image_by_tag(tag)[source]

Find image by tag.

Redirects to the image inspection endpoint for the specified tag

Parameters:

tag (str) – The tag of the image to inspect

Return type:

str

inspect_image(image_uuid)[source]

Inspect an image.

Returns image metadata

Parameters:

image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

Image

inspect_image_download(image_uuid, path)[source]

Download a file from image.

Returns file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the image, e.g. /etc/hosts

Return type:

bytes

inspect_image_download_stream(image_uuid, path)[source]

Streaming variant of inspect_image_download().

Returns file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the image, e.g. /etc/hosts

Return type:

Iterator[bytes]

check_image_file(image_uuid, path)[source]

Check if a file exists in image.

Checks if a file exists in the specified image without returning the file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to check inside the image, e.g. /etc/hosts

Return type:

bool

inspect_image_archive(image_uuid, path, *, compressed=False)[source]

Download a file or a directory from image as tar archive.

Streams the specified path inside the image root filesystem as a POSIX PAX tar archive. A directory becomes the archive root; a regular file becomes a single-entry archive. The response is chunked; total size is not known upfront. Served as an attachment, filename is the path with / replaced by _ plus .tar (e.g. /bin/true -> bin_true.tar).

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to archive inside the image, e.g. /etc

  • compressed (bool) – disable transparent decompression: the body is yielded exactly as served - a tar.gz stream when the server compresses the response, a plain tar otherwise.

Return type:

Iterator[bytes]

check_image_archive(image_uuid, path)[source]

Check if a path can be archived from image.

Checks if a file or a directory exists in the specified image without streaming the archive

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to check inside the image, e.g. /etc

Return type:

bool

inspect_image_list(image_uuid, path)[source]

List files in image.

Returns files list

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the directory to inspect inside the image Example: /etc.

Return type:

DirectoryList

inspect_instance_grep(operation_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Search file contents in running instance.

Regex content search inside the running instance’s root filesystem, through guest RPC. A Go converter translates supported Rust regex syntax to Go regexp.

Symlinks are never followed during traversal, hidden files are searched, .ignore and .gitignore rules within each search root are respected. A NUL byte in the first 64 KiB causes a file to be skipped; a later NUL ends that file’s search. Go regexp uses linear-time matching. The classes w/W, d/D, and s/S use Unicode semantics. Unicode properties and case folding are pinned to Unicode 16.0.0, matching the image engine. Scoped flags, nested class set operations, and bounded expansion of large repetitions are supported. Expanded patterns share a 1 MiB limit per request. Unsupported syntax returns 400 with a pattern index and byte offset. Unicode b/B, CRLF mode, non-ASCII byte mode, and Q…E are rejected. Use (?-u:b) for an ASCII word boundary. Smart case examines parsed literals.

Results are a flat, file-ordered list of lines. before/after request extra type: context lines around each type: match line, mirroring ripgrep’s –json message type field.

path may be repeated to search multiple roots in one call, the same way pattern/glob already can; results are concatenated in the given order and share the max_total budget across all of them. Results never enter operation events. Reads are live and do not form a snapshot. procfs, sysfs, devices, sockets, and FIFOs are not searched. Requires LIST and the permission used to start this instance. Searches have a 10-second budget per root and permit two concurrent searches per instance. Reaching the time, depth, or result limit sets truncated. Context lines count towards max_total. Display text is limited to 4096 bytes per line; matching can continue beyond this window.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • pattern (str | Sequence[str]) – Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each. Example: ^PermitRootLogin.

  • path (str | Sequence[str] | None) – File or directory to search inside the running instance. May be repeated (max 16) to search multiple roots; results are concatenated in the given order, sharing max_total across all paths. Defaults to the rootfs root. Example: /etc.

  • glob (str | Sequence[str] | None) – Glob to filter files (ripgrep -g semantics, “!” negates). May be repeated. Example: *.conf.

  • max_count (int | None) – Maximum matches per file (hard cap 10000).

  • max_total (int | None) – Maximum total matches across all files (default 1000, hard cap 10000).

  • case (Literal['sensitive', 'insensitive', 'smart'] | None) – Case sensitivity mode.

  • before (int | None) – Lines of context to include before each match (ripgrep -B semantics, hard cap 50). For symmetric context (grep -C n), pass both before and after yourself.

  • after (int | None) – Lines of context to include after each match (ripgrep -A semantics, hard cap 50).

Return type:

GrepResult

inspect_image_grep(image_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Search file contents in image.

Regex content search inside the image’s root filesystem, powered by ripgrep.

Symlinks are never followed during traversal, hidden files are searched, .gitignore-style files inside the image are ignored, and binary files (containing a NUL byte) are skipped. Rust regex syntax, linear-time matching.

Results are a flat, file-ordered list of lines. before/after request extra type: context lines around each type: match line, mirroring ripgrep’s –json message type field.

path may be repeated to search multiple roots in one call, the same way pattern/glob already can; results are concatenated in the given order and share the max_total budget across all of them.

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • pattern (str | Sequence[str]) – Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each. Example: ^PermitRootLogin.

  • path (str | Sequence[str] | None) – File or directory to search inside the image. May be repeated (max 16) to search multiple roots; results are concatenated in the given order, sharing max_total across all paths. Defaults to the rootfs root. Example: /etc.

  • glob (str | Sequence[str] | None) – Glob to filter files (ripgrep -g semantics, “!” negates). May be repeated. Example: *.conf.

  • max_count (int | None) – Maximum matches per file (hard cap 10000).

  • max_total (int | None) – Maximum total matches across all files (default 1000, hard cap 10000).

  • case (Literal['sensitive', 'insensitive', 'smart'] | None) – Case sensitivity mode.

  • before (int | None) – Lines of context to include before each match (ripgrep -B semantics, hard cap 50). For symmetric context (grep -C n), pass both before and after yourself.

  • after (int | None) – Lines of context to include after each match (ripgrep -A semantics, hard cap 50).

Return type:

GrepResult

whoami()[source]

Get current token information.

Returns information about the current authentication token, including the token UUID, expiration time, and a map of all known permissions with their granted status.

Return type:

WhoAmIResponse

class contree_client.base.ContreeAsyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None)[source]

Bases: ContreeClientBase, ABC

Asynchronous Contree API client interface.

Backend implementations only provide request(), stream() and close().

Parameters:
abstractmethod async request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

abstractmethod stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

AsyncGenerator[bytes, None]

abstractmethod async close()[source]

Release the underlying transport resources.

Return type:

None

async open()[source]

Eagerly initialize the underlying transport.

Called by __aenter__ from inside the running event loop, so backends can create loop-bound resources here (for example the aiohttp.ClientSession). The default is a no-op.

Return type:

None

async call(spec)[source]

Execute a buffered request, retrying per the client policy.

Without a policy this is a transparent single request(). Streaming requests are never routed here - SSE consumers reconnect with Last-Event-Id instead.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

async operation_terminal(operation_id, deadline=None)[source]

Best-effort check that the operation reached a terminal state.

Parameters:
  • operation_id (str)

  • deadline (float | None)

Return type:

bool

async wait_operation(operation_id, *, timeout=None, follow_events=None, idle_timeout=15.0)[source]

Wait for the terminal operation response.

follow_events=None follows instance events and polls image imports every 0.5 seconds. Use True to force events or False to force polling. Keep the event stream open until completion, EOF, a transport error, or a timeout. idle_timeout is the maximum gap between incoming data chunks in seconds (default 15.0; 0 disables it). Ping/keepalive traffic resets this limit; it does not extend the overall timeout. Gaps between payload events do not trigger checks. After completion, poll until the status is terminal. Return failed and cancelled responses unchanged. timeout covers the entire wait and raises TimeoutError on expiry.

Parameters:
  • operation_id (str)

  • timeout (float | None)

  • follow_events (bool | None)

  • idle_timeout (float)

Return type:

OperationResponse

async follow_operation_events(operation_id, *, last_event_id=None, spid=None, since=None, timeout=None, idle_timeout=15.0)[source]

Stream operation events with transparent reconnection.

Native stream failures trigger a terminal-status probe and a reconnect from the last event id. Iteration ends at the completion event or the timeout. After a terminal status, drain the retained log without following before ending iteration. Interrupted retained reads resume from the last event id, using the configured retry policy (three attempts by default). Normal EOF also completes a filtered or explicitly resumed retained log. An unfiltered log must include completion. An unavailable or incomplete event log raises APIConnectionError. The timeout is an absolute deadline checked whenever iteration resumes. Caller code between events is not interrupted. idle_timeout bounds gaps between incoming data in seconds (default 15.0; 0 disables it). Ping/keepalive traffic resets this limit without extending the overall timeout.

Parameters:
  • operation_id (str)

  • last_event_id (int | None)

  • spid (int | None)

  • since (int | None)

  • timeout (float | None)

  • idle_timeout (float)

Return type:

AsyncGenerator[OperationEvent, None]

async resolve_image(ref)[source]

Resolve an image reference to a UUID.

Accepts a raw UUID, tag:NAME or a bare tag name.

Parameters:

ref (str)

Return type:

str

async ensure_file(content, *, sha256=None)[source]

Upload content unless the server already stores it.

The digest (sha256 when the caller already knows it, computed locally in a worker thread otherwise, so a large file does not block the event loop) is probed via get_file(); only a miss uploads. Returns the stored file record either way (both shapes carry uuid, sha256 and size). Non-seekable streams cannot be hashed and rewound, so without a caller-provided sha256 they skip deduplication and upload directly.

Parameters:
Return type:

FileResponse | File

async list_network_policies(*, search=None, limit=None, offset=None)[source]

List network policies.

Returns policies in your namespace and the shared namespace. Deleted policies are excluded. Reusing or restoring a policy does not change its creation time or listing position. Each entry contains the policy UUID, creation timestamp, accessible tags, and a summary with the number of IP rules. Tags are sorted by name. Your tag takes precedence over a shared tag with the same name; the overridden shared binding is omitted. Use GET /network/policies/{uuid} to retrieve the full rules. Requires spawn or spawn_disposable permission.

Search: Supply search to find active policies in your namespace and the shared namespace that allow the destination. The input determines the search type; currently only IPv4 and IPv6 addresses and CIDRs are supported. Domains and other unsupported inputs return 400. An omitted search parameter lists policies normally; an empty value returns 400.

Use [tcp://|udp://]address-or-cidr[:port]. IPv6 addresses and CIDRs must be enclosed in brackets when specifying a port, with the prefix length inside the brackets. Examples: 192.0.2.1, 192.0.2.0/24:443, tcp://192.0.2.0/24:443, and udp://[2001:db8::/64]:53. This is search syntax, not a URL. CIDRs must use their network address; host bits, scoped IPv6 addresses, and ports outside 1-65535 return 400.

A match must allow the requested protocol and port throughout the entire CIDR, not merely overlap it. An IP address is treated as a /32 or /128 CIDR. All-port rules match every requested port. If protocol or port is omitted, any single protocol/port combination covering the entire destination matches. Complementary subnets granting that same access are normalized into a covering rule. Permissions from different policies are never combined for search. Empty policies do not match. Filtering happens before pagination, and results retain the same order, summary, timestamp, and tags as the normal listing.

Parameters:
  • search (str | None) – IP or CIDR search, optionally qualified by TCP/UDP and a destination port.

  • limit (int | None) – Maximum number of results to return. Invalid values raise 400 error.

  • offset (int | None) – Number of results to skip. Invalid values raise 400 error.

Return type:

NetworkPolicyListResponse

async create_network_policy(cidrs)[source]

Create a network policy.

Creates a policy with immutable rules in the caller’s namespace. Requires network_policy permission.

Rules

  • Each rule allows a CIDR for the selected protocol and ports. An empty or omitted port list allows all ports.

  • ICMP is allowed to every listed CIDR, regardless of protocol or ports.

  • An empty rules array (cidrs: []) blocks all IP egress, including ICMP and traffic to the host.

  • ARP is blocked for all policies.

Limits

The same limit of 16384 units applies before and after normalization. Sum the number of ports across all rules, counting an empty or omitted port list (all ports) as 1. The limit covers the entire policy, across all IP versions and protocols. Duplicates count toward the limit before normalization. Exceeding the limit returns 400, even if normalization would remove redundant rules or ports.

Normalization

Before storage, duplicate rules and ports are removed, CIDRs are merged per protocol and port, and rules and ports are sorted. This preserves the allowed traffic. The response contains the normalized rules.

Policy identity

Equivalent normalized policies in the same namespace reuse the same UUID, including concurrent requests. The UUID is UUIDv5 derived from the namespace and the normalized policy hash. Resubmitting a deleted policy restores it without restoring its tags. To change the rules, create a new policy.

Parameters:

cidrs (list[NetworkPolicyCIDRRule])

Return type:

NetworkPolicy

async get_network_policy(uuid)[source]

Get a network policy.

Returns an accessible policy, including deleted policies. Returns 404 if the policy does not exist. Requires spawn or spawn_disposable permission.

Parameters:

uuid (str) – Network policy UUID Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

NetworkPolicy

async delete_network_policy(uuid)[source]

Remove a network policy.

Removes a policy in your namespace. Requires network_policy permission. Returns 204 if the policy is removed or was already removed. Returns 404 if the policy does not exist in your namespace. Removes its tags and excludes it from listings. The policy remains accessible and usable by UUID, but cannot be assigned to tags.

Parameters:

uuid (str) – Network policy UUID Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

None

async list_network_policy_tags(*, limit=None, offset=None)[source]

List network policy tags.

Returns your tags and shared tags, ordered by name. Your tag takes precedence when a shared tag has the same name. Requires spawn or spawn_disposable permission.

Parameters:
  • limit (int | None) – Maximum number of results to return. Invalid values raise 400 error.

  • offset (int | None) – Number of results to skip. Invalid values raise 400 error.

Return type:

ListNetworkPolicyTagsResponse

async get_network_policy_tag(tag)[source]

Get a network policy tag.

Redirects to the policy referenced by your tag, or the shared tag if you have no tag with that name. The redirect response includes the effective tag binding as JSON. Requires spawn or spawn_disposable permission. Returns 404 if the tag or its target policy does not exist or is removed.

Parameters:

tag (str) – Network policy tag name

Return type:

NetworkPolicyTag

async set_network_policy_tag(tag, uuid)[source]

Bind a tag to a network policy.

Creates or replaces your tag’s binding to an active policy in your namespace or the shared namespace. Repeating the same binding has no effect. Returns 404 if the target policy does not exist, is inaccessible, or is removed. The tag belongs to your namespace. Requires network_policy permission.

Parameters:
  • tag (str) – Network policy tag name

  • uuid (str)

Return type:

NetworkPolicyTag

async delete_network_policy_tag(tag)[source]

Remove a network policy tag.

Removes your tag, including when operations use its policy. Repeated deletion succeeds. If a shared tag has the same name, it becomes visible again. Requires network_policy permission.

Parameters:

tag (str) – Network policy tag name

Return type:

None

async list_images(*, limit=None, offset=None, tagged=False, tag=None, uuid=None, since=None, until=None)[source]

List publicly available images.

Returns a list of all publicly available container images.

Parameters:
  • limit (int | None) – Maximum number of images to return. Must be between 1 and 1000. Default is 100. Invalid values raise 400 error.

  • offset (int | None) – Number of images to skip before starting to collect the result set. Default is 0. Invalid values raise 400 error.

  • tagged (bool) – Example: 1.

  • tag (str | None) – A valid image tag prefix to filter images by this prefix. Only images with tags starting with. Implies tagged parameter. Example: ubuntu.

  • uuid (str | None) – Filter images by UUID Example: 12345678-9abc-baba-deda-0123456789ab.

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

Return type:

ImageListResponse

async iter_images(*, tagged=False, tag=None, uuid=None, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_images() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • tagged (bool) – Example: 1.

  • tag (str | None) – A valid image tag prefix to filter images by this prefix. Only images with tags starting with. Implies tagged parameter. Example: ubuntu.

  • uuid (str | None) – Filter images by UUID Example: 12345678-9abc-baba-deda-0123456789ab.

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

AsyncGenerator[Image, None]

async delete_image_tag(image_uuid, *, tag=None)[source]

Remove tags from an image.

Removes a tag (or all tags) from an image.

When tag query parameter is provided, only that specific tag is removed. When omitted, all tags are removed from the image.

If any public image has the same tag, tag will start tracking that public image again.

In all other cases tag will be removed and the image will be accessible only by its UUID.

Parameters:
  • image_uuid (str) – The UUID of the image to untag Example: 12345678-9abc-baba-deda-0123456789ab.

  • tag (str | None) – The tag to remove. If omitted, all tags are removed from the image. Example: busybox:latest.

Return type:

None

async update_image_tag(image_uuid, tag)[source]

Add a tag to an image.

Adds a tag to an image. Tags are unique per namespace; if the requested tag is already assigned to another image, it will be moved to this image.

Assigning a tag that matches a public tag to a public image will freeze that tag to the current image - subsequent public updates to the tag will not affect it. To make the public tag track the latest public image again, remove your tag assignment.

When a tag is removed from an image that resides in the public namespace, the API returns HTTP 200 OK. response body contains the tag that now points to the public image (i.e., the image that the tag is automatically re-assigned to).

In other words, un-tagging a public image does not delete the tag; it simply moves the tag back to the public image and the caller receives that tag in the successful response.

Parameters:
  • image_uuid (str) – The UUID of the image to update Example: 12345678-9abc-baba-deda-0123456789ab.

  • tag (str) – New tag for the image Example: busybox:latest.

Return type:

Image

async import_image(registry, *, tag=Ellipsis, timeout=Ellipsis)[source]

Import a container image from a registry.

Imports the OCI image filesystem content of from a specified registry.

Important limitations and behavior:

  • Only the image root filesystem (files and directories) is imported. This is like to the output of docker export and does not preserve layers metadata.

  • Most image configuration and manifest data are ignored. Metadata such as LABEL, ENTRYPOINT, CMD, WORKDIR, EXPOSE and other image configuration directives will NOT be imported or applied.

  • ENV variables defined in the image are imported and automatically applied to the instance environment when shell is set to true. When shell is false, image environment variables are not inherited and must be passed explicitly via the env field.

  • The result is a flat rootfs snapshot with preserved environment variables.

  • If the specified tag already exists in the public images, the imported image will replace it. To avoid this, you can tag the existing image with a different tag for use it later. You also can use image UUIDs it is not changing for imported and existend image.

  • In case the remote image is unchanged and already imported, the operation will complete and the same UUID will be returned without re-importing the image.

The request creates an import operation which runs asynchronously.

Parameters:
  • tag (str | None | EllipsisType) – Tag to identify the image when listing publicly available images. If omitted, the image will be private and only accessible by ID. Example: busybox:latest.

  • timeout (int | EllipsisType) – Maximum time in seconds to wait for the import operation to complete Example: 300.

  • registry (ImageImportRegistry)

Return type:

str

async list_files(*, limit=None, offset=None, since=None, until=None)[source]

List uploaded files for the current namespace.

Returns a paginated list of uploaded files for the current namespace.

Parameters:
  • limit (int | None) – Maximum number of files to return

  • offset (int | None) – Number of files to skip

  • since (str | int | float | datetime | None) – Filter files created after this time

  • until (str | int | float | datetime | None) – Filter files created before this time

Return type:

FilesListResponse

async iter_files(*, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_files() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • since (str | int | float | datetime | None) – Filter files created after this time

  • until (str | int | float | datetime | None) – Filter files created before this time

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

AsyncGenerator[File, None]

async upload_file(content)[source]

Upload a file to the server. the body must be a file content.

Uploads a file to the server. The body must contain the file content.

Parameters:

content (bytes | IO[bytes]) – Raw file content: bytes or a binary stream.

Return type:

FileResponse

async get_file(sha256)[source]

Get file info by SHA256.

Returns file info (uuid, sha256, created_at, updated_at).

Parameters:

sha256 (str) – SHA256 hash of the file (64 hex characters)

Return type:

File

async check_file_exists(sha256)[source]

Check if a file exists for the current namespace.

Returns 200 if the file is uploaded by the current namespace, otherwise 404.

Parameters:

sha256 (str) – SHA256 hash of the file (64 hex characters)

Return type:

bool

async spawn_instance(command, image, *, disposable=Ellipsis, hostname=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, preserve_env=Ellipsis, preserve_cwd=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, resources_limits=Ellipsis, networking=Ellipsis, stdin=Ellipsis, timeout=Ellipsis, truncate_output_at=Ellipsis, files=Ellipsis)[source]

Spawn a new container instance.

Creates and runs a new execution instance with the specified configuration. Requires a valid Authorization header.

Common request body rules:

  • The request body must contain at least command and image fields all other fields can be omitted.

  • If the command field is a shell expression, you must set shell field to true.

  • For specifying the shell binary, you can use env field to set SHELL variable.

  • When shell is true, environment variables defined in the image (via ENV directives) are automatically inherited. When shell is false, image environment variables are not inherited and must be passed explicitly via the env field.

Parameters:
  • command (str) – The command to execute. In case if shell is set to true, this MUST contain shell expression. For example echo hello world or ls -l /app. If shell is set to false, this must be a relative or absolute path to the executable inside the image rootfs. For example: /bin/app or /usr/bin/find. Do not forget pass necessary PATH variable to env field, by default PATH is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Example: /bin/app.

  • disposable (bool | EllipsisType) – Creates a disposable execution environment no any state will be saved.

  • hostname (str | EllipsisType) – Hostname to set when execution. Example: container-name.

  • args (list[str] | EllipsisType) – Arguments to pass to the command if shell is set to false. Example: ["arg1","arg2"].

  • shell (bool | EllipsisType) – Whether to run the command through a shell. If true, the command must be a shell expression and all values from args will be ignored. If false, the command field must be a path to an executable and args will be used. When true, environment variables from the image are automatically inherited. When false, they are not - use the env field to pass them explicitly.

  • env (dict[str, str] | None | EllipsisType) – Environment variables to set in the container. These are merged with image-defined variables when shell is true. When shell is false, only variables specified here are available - image-defined variables are not inherited. Example: {"KEY1":"value1","KEY2":"value2"}.

  • preserve_env (bool | EllipsisType) – Preserve environment variables in resulting image after execution. When true, the image’s existing environment variables from metadata/env are merged with user-provided env values (user values take priority on conflicts), and the combined result is written back to metadata/env after command execution. Setting a variable to an empty string or null removes it from the preserved environment.

  • preserve_cwd (bool | EllipsisType) – Save the resolved initial working directory as the default in the resulting image. An empty or omitted cwd resolves to the image’s current workdir, or / if none exists. The metadata file is opened for writing only when its contents differ from the new value. Directory changes made by the command do not change the saved value. Requires disposable: false to retain the metadata in a resulting image.

  • cwd (str | EllipsisType) – Path to the working directory, must be absolute or a special value the empty string. It means the default working directory of the image or server default will be used. If field is omitted it will be set to the empty string. The directory will be created automatically if it does not exist. Example: /app.

  • uid (int | EllipsisType) – User ID to run the process as. Example: 0.

  • gid (int | EllipsisType) – Group ID to run the process as. Example: 0.

  • timeout (int | EllipsisType) – Maximum execution time in seconds Example: 60.

  • truncate_output_at (int | EllipsisType) – Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect stdin delivery to the child, which always receives the complete stream regardless of this cap. Default is 1048576 (1 MiB). The maximum value is 10485760 (10 MiB). Example: 65535.

  • files (dict[str, FileSpec] | EllipsisType) – Map of absolute file paths to file metadata Example: {"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c....

  • image (str)

  • resources_limits (InstanceResourcesLimits | EllipsisType)

  • networking (InstanceNetworking | EllipsisType)

  • stdin (ClosableStreamRepr | EllipsisType)

Return type:

InstanceSpawnResponse

async list_operations(*, limit=None, offset=None, status=None, kind=None, since=None, until=None)[source]

List operations.

Returns a list of running and completed operations

Parameters:
  • limit (int | None) – Maximum number of operations to return. Must be between 1 and 1000. Default is 100. Invalid values raise 400 error.

  • offset (int | None) – Number of operations to skip before starting to collect the result set. Default is 0. Invalid values raise 400 error.

  • status (OperationStatus | str | None) – Filter operations by their state

  • kind (Literal['image_import', 'instance'] | None) – Filter operations by their kind

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

Return type:

list[OperationSummary]

async iter_operations(*, status=None, kind=None, since=None, until=None, page_size=1000, limit=None)[source]

Iterate over list_operations() results across pages.

Offset pagination happens transparently as items are consumed; breaking out of the loop stops fetching. Note that offset pagination is not a snapshot - records created or deleted between page fetches may shift, so items can repeat or be skipped under concurrent modification.

Parameters:
  • status (OperationStatus | str | None) – Filter operations by their state

  • kind (Literal['image_import', 'instance'] | None) – Filter operations by their kind

  • since (str | int | float | datetime | None) – Show only results created after the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1w.

  • until (str | int | float | datetime | None) – Show only results created before the given date/time or interval. Accepts a Unix timestamp or interval string. Interval format: 600s/15m/2h/3d/1w means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively). For example: * 2025-01-01T12:00:00+00:00 means January 1st, 2025 at 12:00 UTC * 600s means 600 seconds ago * 15m means 15 minutes ago Invalid values raise 400 error. Example: 1h.

  • page_size (int) – how many records to fetch per request (the server caps a page at 1000)

  • limit (int | None) – stop after this many records in total; None iterates everything

Return type:

AsyncGenerator[OperationSummary, None]

async get_operation_status(operation_id, *, inflight=False)[source]

Get an operation status.

Returns the status of an operation.

For an EXECUTING INSTANCE operation, pass ?inflight=1 to also synthesize the partial result.stdout / result.stderr from the live event log. Off by default — each fetch with inflight triggers an extra subscribe RPC to the guest and drains its current events.gz, which is wasted work for clients that only poll for status transitions.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • inflight (bool) – HTTP-flag boolean. Present without a value (?inflight) and ?inflight=1 both enable; ?inflight=0 and absence disable. When enabled and the operation is EXECUTING INSTANCE, partial stdout/stderr is synthesized from the live event log and attached under result.

Return type:

OperationResponse

async cancel_operation(operation_id)[source]

Cancel an operation.

Cancels an operation

Parameters:

operation_id (str) – The ID of the import operation to cancel Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

None

async iter_operation_events(operation_id, *, follow=False, spid=None, since=None, last_event_id=None, deadline=None, idle_timeout=0.0)[source]

Stream the operation event log via Server-Sent Events.

Always returns text/event-stream (SSE) on success. The body is a sequence of three kinds of lines (per RFC W3C SSE), each terminated by \n\n:

Frame shapes

Normal event frame — one OperationEvent JSON object in data:, dispatchable via event::

id: <integer event.id>
event: <OperationEventType, e.g. stdout|stderr|spawn|exit>
data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}}

event: always matches data.type. See OperationEvent and OperationEventType for the per-type payload shape. Native EventSource dispatches each frame to the matching addEventListener("<type>", ...) handler.

Server-side error frame — surfaces handler exceptions to the connected client without tearing the TCP connection down mid-stream. Sent right before the server closes the response:

: stream ended with error, retry since last event id

event: sse_error
data: <one-line exception message>

The leading SSE comment line lets pure-EventSource clients see the intent (“retry from Last-Event-Id”); the sse_error frame carries the error text for logging. Clients should treat this as a non-clean close and reconnect with the standard SSE Last-Event-Id semantics (see Resuming).

Keepalive comment — periodic : keepalive\n\n lines emitted while the stream is idle. They keep upstream proxy_read_timeout / TCP idle timers fresh and have no application meaning. Spec-compliant; EventSource and any SSE parser must ignore comment lines (those beginning with :).

follow semantics

The follow parameter controls only whether the stream stays open after the last currently-known event:

  • follow=0 (default) — the server emits everything currently available and closes the connection.

  • follow=1 — same start; if the operation is still running the server keeps the connection open and forwards new events as they appear. For terminal operations follow=1 is a no-op: there’s nothing more to subscribe to, so the connection closes after the last event just like follow=0.

Optional filters:

  • ?spid=N — only events whose spid (Spawned Process ID, the routing identity in OperationEvent) matches.

  • ?since=N — only events with id > N.

follow=1 requires SPAWN or SPAWN_DISPOSABLE on top of the baseline LIST — a long-lived subscription reserves per-operation server state. follow=0 is read-only and stays under LIST.

Resuming after a drop

Every normal frame carries id: — the canonical event id. On reconnect send the last successfully received id in the standard Last-Event-Id request header (or ?since=N on manual GETs); the server resumes from that point.

Error handling

Status

Meaning

Client action

200

Stream open

Read frames; reconnect with Last-Event-Id if the stream closes before reaching a terminal event

400

Malformed query/header (non-integer param)

Fix request

401

Missing/invalid auth

Refresh credentials

403

Auth lacks LIST (or SPAWN for follow=1)

Use a token with the right scope

404

Operation not in this namespace

Wrong UUID

410

Stream is over but the terminal artifact isn’t ready yet

Retry after Retry-After

425

Not yet ready (operation is still being prepared)

Retry after Retry-After

502

Upstream returned an error opening the stream

Retry; if persistent, escalate

504

Upstream took too long to respond

Retry

A 200 followed by an event: sse_error frame and immediate close is the in-band equivalent of “the stream broke after we already committed to a 200” — handle it the same way as 410: wait briefly, reconnect with Last-Event-Id.

See OperationEvent for the per-event shape.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • follow (bool) – HTTP-flag boolean. Present without a value (?follow) and ?follow=1 both enable; ?follow=0 and absence disable. When enabled, the SSE stream stays open after the currently-known events have been sent — for a running operation new events are forwarded as they appear; for a terminal operation it has no effect.

  • spid (int | None) – Only emit events whose spid field matches. Filter is applied server-side regardless of whether the operation is still running or already terminal.

  • since (int | None) – Only emit events with id > since (event IDs are monotonically increasing). Overridden by the Last-Event-Id header when present.

  • last_event_id (int | None) – Standard SSE resume header sent automatically by EventSource on reconnect. Treated as ?since=N; takes precedence over the query param.

  • deadline (float | None) – absolute monotonic deadline. Checked whenever iteration resumes; caller code between events is not interrupted.

  • idle_timeout (float) – seconds without incoming data before a transport timeout; 0 disables it

Return type:

AsyncGenerator[OperationEvent, None]

async operation_subprocess_create(operation_id, command, *, resources_limits=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, stdin=Ellipsis, truncate_output_at=Ellipsis)[source]

Spawn an additional subprocess inside a running instance.

Starts a new process inside the VM that already hosts the named operation. Distinct from POST /instances, which spins up a VM: this endpoint requires a running operation (EXECUTING or ASSIGNED) and reuses the existing VM.

The body is an ExecSpec — process-execution fields only. VM-level concerns (image, hostname, files, timeout, disposable, preserve_env) are not accepted here; they were set when the parent operation was created.

resources_limits.cpu and resources_limits.memory_mib use the same names and units as operation creation. Each omitted or null subprocess limit inherits the corresponding operation limit. Values above the operation limit return 400. Limits apply at launch: memory_mib sets RLIMIT_AS for each process and memory.max for the entire process tree. They cannot be changed through this API. Guest root can modify limits; these limits do not provide security isolation between processes in one VM.

The required permission follows the parent instance: SPAWN_DISPOSABLE when it was spawned with disposable=true, SPAWN otherwise.

On success the worker assigns a fresh spid (≥2; spid=1 is the main process spawned from metadata) and the response carries it in the body plus a Location header pointing at GET /operations/{operationId}/subprocesses/{spid} — the subprocess result reconstructed from its events.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • command (str) – The command to execute. Same semantics as in InstanceSpawnRequest.command — when shell=true it is a shell expression, otherwise a path to an executable. Example: /bin/app.

  • args (list[str] | EllipsisType) – Arguments to pass to the command if shell is set to false. Example: ["arg1","arg2"].

  • shell (bool | EllipsisType) – Run command through a shell expression (args must be empty).

  • env (dict[str, str] | None | EllipsisType) – Environment variables to set in the child process.

  • cwd (str | EllipsisType) – Working directory; empty string means image / server default.

  • uid (int | EllipsisType) – User ID to run the process as.

  • gid (int | EllipsisType) – Group ID to run the process as.

  • stdin (ClosableStreamRepr | EllipsisType) – Bytes fed to the child’s stdin — honored for both the main process and exec’d subprocesses. With close=false the pipe stays open and more data can be written via POST /operations/{operationId}/subprocesses/{spid}/stdin.

  • truncate_output_at (int | EllipsisType) – Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect delivery to the child — stdin is always delivered in full regardless of this cap. Defaults to 1 MiB; capped at 10 MiB. Example: 65535.

  • resources_limits (ProcessResourcesLimits | EllipsisType)

Return type:

int

async operation_subprocess(operation_id, spid)[source]

Result of one subprocess, reconstructed from its events.

Returns an InstanceResult for spid — the same shape as the parent operation’s metadata.result — folded from the subprocess’s event log (spawn / stdout / stderr / exit). Works for running and terminal operations alike. While the process is still running, state.exit_code and state.signal are -1 (unknown) and resources holds sentinel defaults; once the exit event lands they carry the real values.

stdout / stderr are consolidated and capped at the spec’s truncate_output_at. The raw event stream stays available at GET /operations/{operationId}/events?spid={spid}.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

Return type:

InstanceResult

async operation_subprocess_kill(operation_id, spid, *, signal=None)[source]

Kill one subprocess.

Sends a signal to the process group of spid inside the running instance. Without the signal parameter the group gets SIGKILL. Termination is observable, not returned: the exit event lands in the event log and GET /operations/{operationId}/subprocesses/{spid} reports the terminal state (signal set, exit_code -1 when killed).

Killing spid=1 (the main process) effectively ends the operation, like letting the command fail.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

  • signal (str | None) – Signal to send instead of SIGKILL — a number (15) or a name with or without the SIG prefix (TERM, SIGTERM). Example: SIGTERM.

Return type:

None

async operation_subprocess_stdin(operation_id, spid, value, *, encoding=Ellipsis, close=Ellipsis)[source]

Write to a subprocess’s stdin and/or close it.

Writes a chunk to the stdin of a live process inside the running instance — spid=1 targets the main process, ≥2 the exec’d children. Requires the process to have been started with stdin.close=false; otherwise its pipe is already at EOF and the call returns 409.

close=true (the default) signals EOF after writing value; an empty value with close=true just closes the pipe. A client that serializes its own requests gets ordered writes; concurrent requests to the same spid are safe but their order is unspecified.

A 504 means the guest write timed out mid-call — the chunk may or may not have been delivered (e.g. the process stopped reading and the pipe is full), so blind retries can duplicate data.

Parameters:
  • operation_id (str) – The ID of the operation Example: 12345678-9abc-baba-deda-0123456789ab.

  • spid (int) – Spawn id (1 = main process; ≥2 = exec’d children).

  • value (str) – Content to write to stdin (may be empty for a close-only request) Example: aGVsbG8K.

  • encoding (Literal['ascii', 'base64'] | ~types.EllipsisType) – Encoding of the content

  • close (bool | EllipsisType) – true (default) closes stdin (EOF) after writing value — the pre-existing one-shot behavior. false keeps the pipe open so more data can be sent later via POST /operations/{operationId}/subprocesses/{spid}/stdin.

Return type:

None

async apply_instance_file(operation_uuid, file_uuid, path, *, unpack=Ellipsis, replace=Ellipsis, merge=Ellipsis)[source]

Apply an uploaded file to a running instance.

Reads a file previously uploaded through POST /files and writes it to a running INSTANCE operation, including disposable instances. Requires LIST and the permission used to start the instance. Both the operation and the uploaded file must belong to the request namespace. Expired files are unavailable. The assigned worker streams the stored object to the guest through RPC. Init records request metadata in inspect events and the terminal publication result in file_upload, including file_uuid and byte count. File contents do not enter operation events.

With unpack omitted or false, path is the full destination filename. Missing parent directories are created. The file is published atomically after transfer and SHA256 verification. The new file has mode 0644 and is owned by the guest runtime user. With replace true, an existing leaf symlink is replaced. Directories and special files are not regular file destinations.

With unpack true, path is the destination directory. Supports tar, tar.gz and tar.bz2; compression is detected from the stored bytes. Xz is unsupported and rejected before subsequent chunks are sent. Without unpack, compressed archives are copied unchanged. Content-Type describes this JSON request and never controls extraction.

Extraction accepts regular files, directories, symlinks and hardlinks to regular files already extracted in the staging tree. Parent symlinks inside that tree are not followed. Absolute entry names and entries containing ‘..’ are rejected. procfs, sysfs, devices, FIFOs and sockets are unsupported. New directories have mode 0755; regular files retain tar permission bits (0777). Ownership and timestamps are not restored. Other entries fail explicitly. With replace omitted or false, any existing destination returns 409, including a symlink or empty directory. This condition is checked again atomically at publication. replace true permits an existing destination. With merge omitted or false, directory replacement removes the entire old tree without merging contents.

Archives are extracted into a temporary sibling directory. The destination remains unchanged until the complete stream and SHA256 have been verified. Without merge, publication uses an atomic rename or exchange, then removes the old tree. Root and mount-point replacement are unavailable. Existing open descriptors can still refer to old inodes; concurrent workload access is not a snapshot.

merge true requires both unpack true and replace true. After complete staging and verification, it combines directories and atomically replaces individual files and symlinks. Existing entries absent from the archive remain. Destination directory symlinks are not followed; directory/file conflicts fail explicitly. Same-filesystem hardlinks are retained. Crossing a destination mount requires copying file bytes and does not preserve hardlinks across filesystems. Merge is not atomic for the whole tree: errors, cancellation or timeout after application starts can leave completed changes. These changes are not rolled back.

Returns 204 only after completion. Transfers have a 300-second deadline and bounded buffers and handles. Disconnect or VM exit cancels the transfer. A lost response can leave an uncertain outcome; requests are not replayed automatically. This endpoint does not write to a completed result image.

A transfer timeout does not stop the instance. Before publication or merge starts, cancellation preserves the old destination and removes the temporary file or extraction tree. A timeout while awaiting the final response can occur after publication; it does not prove that no changes were made. An old-tree cleanup failure is reported as an error after publication; it does not roll back the new tree. The uploaded source object retains its normal lifetime. Automatically created parent directories have mode 0755 and can remain after errors.

The primary command’s timeout follows normal instance finalization: ordinary instances persist their filesystem, including successfully published uploads; disposable instances do not. Instance shutdown waits for pending upload cleanup. A timeout or crash of the execution environment can bypass this cleanup and does not produce a successfully persisted result image through normal finalization.

Parameters:
  • operation_uuid (str) – Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – Absolute guest filename, or directory when unpack is true. Missing parents are created.

  • unpack (bool | EllipsisType) – Extract tar, tar.gz or tar.bz2 instead of copying the stored bytes.

  • replace (bool | EllipsisType) – Permit an existing destination. Without merge, directories are replaced in full.

  • merge (bool | EllipsisType) – Merge verified archive contents. Requires unpack and replace. Can leave partial changes.

  • file_uuid (str)

Return type:

None

async inspect_instance_download(operation_uuid, path)[source]

Download a file from a running instance.

Reads through guest RPC without recording file contents in operation events. Requires LIST and the permission used to start this instance (SPAWN or SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are unavailable. Reads do not form a snapshot. The opened inode and initial size are used; later growth is excluded. Truncation or VM exit interrupts the response. A transfer has a 300-second deadline. No result-image fallback is performed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the running instance, e.g. /etc/hosts

Return type:

bytes

async inspect_instance_download_stream(operation_uuid, path)[source]

Streaming variant of inspect_instance_download().

Reads through guest RPC without recording file contents in operation events. Requires LIST and the permission used to start this instance (SPAWN or SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are unavailable. Reads do not form a snapshot. The opened inode and initial size are used; later growth is excluded. Truncation or VM exit interrupts the response. A transfer has a 300-second deadline. No result-image fallback is performed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the running instance, e.g. /etc/hosts

Return type:

AsyncGenerator[bytes, None]

async check_instance_file(operation_uuid, path)[source]

Check if a file exists in running instance.

Checks if a file exists in the specified running instance without returning the file content

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to check inside the running instance, e.g. /etc/hosts

Return type:

bool

async inspect_instance_list(operation_uuid, path)[source]

List files in running instance.

Lists guest files without recording contents in operation events. Requires LIST and the permission used to start this instance. Reads do not form a snapshot. A directory can contain at most 10000 entries. procfs and sysfs cannot be listed.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the directory to inspect inside the running instance Example: /etc.

Return type:

DirectoryList

async inspect_instance_archive(operation_uuid, path, *, compressed=False)[source]

Download a file or a directory from running instance as tar archive.

Streams the specified path inside the running instance root filesystem as a POSIX PAX tar archive. A directory becomes the archive root; a regular file becomes a single-entry archive. The response is chunked; total size is not known upfront. Served as an attachment, filename is the path with / replaced by _ plus .tar (e.g. /bin/true -> bin_true.tar). Requires LIST and the permission used to start this instance. Contents do not enter operation events. Reads do not form a snapshot. Traversal skips procfs and sysfs and preserves descendant symlinks. File changes or VM exit can interrupt the stream. Transfers have a 300-second deadline.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to archive inside the running instance, e.g. /etc

  • compressed (bool) – disable transparent decompression: the body is yielded exactly as served - a tar.gz stream when the server compresses the response, a plain tar otherwise.

Return type:

AsyncGenerator[bytes, None]

async check_instance_archive(operation_uuid, path)[source]

Check if a path can be archived from running instance.

Checks if a file or a directory exists in the specified running instance without streaming the archive

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to check inside the running instance, e.g. /etc

Return type:

bool

async inspect_find_image_by_tag(tag)[source]

Find image by tag.

Redirects to the image inspection endpoint for the specified tag

Parameters:

tag (str) – The tag of the image to inspect

Return type:

str

async inspect_image(image_uuid)[source]

Inspect an image.

Returns image metadata

Parameters:

image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

Return type:

Image

async inspect_image_download(image_uuid, path)[source]

Download a file from image.

Returns file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the image, e.g. /etc/hosts

Return type:

bytes

async inspect_image_download_stream(image_uuid, path)[source]

Streaming variant of inspect_image_download().

Returns file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to inspect inside the image, e.g. /etc/hosts

Return type:

AsyncGenerator[bytes, None]

async check_image_file(image_uuid, path)[source]

Check if a file exists in image.

Checks if a file exists in the specified image without returning the file content

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file to check inside the image, e.g. /etc/hosts

Return type:

bool

async inspect_image_archive(image_uuid, path, *, compressed=False)[source]

Download a file or a directory from image as tar archive.

Streams the specified path inside the image root filesystem as a POSIX PAX tar archive. A directory becomes the archive root; a regular file becomes a single-entry archive. The response is chunked; total size is not known upfront. Served as an attachment, filename is the path with / replaced by _ plus .tar (e.g. /bin/true -> bin_true.tar).

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to archive inside the image, e.g. /etc

  • compressed (bool) – disable transparent decompression: the body is yielded exactly as served - a tar.gz stream when the server compresses the response, a plain tar otherwise.

Return type:

AsyncGenerator[bytes, None]

async check_image_archive(image_uuid, path)[source]

Check if a path can be archived from image.

Checks if a file or a directory exists in the specified image without streaming the archive

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the file or directory to check inside the image, e.g. /etc

Return type:

bool

async inspect_image_list(image_uuid, path)[source]

List files in image.

Returns files list

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • path (str) – The path of the directory to inspect inside the image Example: /etc.

Return type:

DirectoryList

async inspect_instance_grep(operation_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Search file contents in running instance.

Regex content search inside the running instance’s root filesystem, through guest RPC. A Go converter translates supported Rust regex syntax to Go regexp.

Symlinks are never followed during traversal, hidden files are searched, .ignore and .gitignore rules within each search root are respected. A NUL byte in the first 64 KiB causes a file to be skipped; a later NUL ends that file’s search. Go regexp uses linear-time matching. The classes w/W, d/D, and s/S use Unicode semantics. Unicode properties and case folding are pinned to Unicode 16.0.0, matching the image engine. Scoped flags, nested class set operations, and bounded expansion of large repetitions are supported. Expanded patterns share a 1 MiB limit per request. Unsupported syntax returns 400 with a pattern index and byte offset. Unicode b/B, CRLF mode, non-ASCII byte mode, and Q…E are rejected. Use (?-u:b) for an ASCII word boundary. Smart case examines parsed literals.

Results are a flat, file-ordered list of lines. before/after request extra type: context lines around each type: match line, mirroring ripgrep’s –json message type field.

path may be repeated to search multiple roots in one call, the same way pattern/glob already can; results are concatenated in the given order and share the max_total budget across all of them. Results never enter operation events. Reads are live and do not form a snapshot. procfs, sysfs, devices, sockets, and FIFOs are not searched. Requires LIST and the permission used to start this instance. Searches have a 10-second budget per root and permit two concurrent searches per instance. Reaching the time, depth, or result limit sets truncated. Context lines count towards max_total. Display text is limited to 4096 bytes per line; matching can continue beyond this window.

Parameters:
  • operation_uuid (str) – The UUID of the running instance to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • pattern (str | Sequence[str]) – Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each. Example: ^PermitRootLogin.

  • path (str | Sequence[str] | None) – File or directory to search inside the running instance. May be repeated (max 16) to search multiple roots; results are concatenated in the given order, sharing max_total across all paths. Defaults to the rootfs root. Example: /etc.

  • glob (str | Sequence[str] | None) – Glob to filter files (ripgrep -g semantics, “!” negates). May be repeated. Example: *.conf.

  • max_count (int | None) – Maximum matches per file (hard cap 10000).

  • max_total (int | None) – Maximum total matches across all files (default 1000, hard cap 10000).

  • case (Literal['sensitive', 'insensitive', 'smart'] | None) – Case sensitivity mode.

  • before (int | None) – Lines of context to include before each match (ripgrep -B semantics, hard cap 50). For symmetric context (grep -C n), pass both before and after yourself.

  • after (int | None) – Lines of context to include after each match (ripgrep -A semantics, hard cap 50).

Return type:

GrepResult

async inspect_image_grep(image_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Search file contents in image.

Regex content search inside the image’s root filesystem, powered by ripgrep.

Symlinks are never followed during traversal, hidden files are searched, .gitignore-style files inside the image are ignored, and binary files (containing a NUL byte) are skipped. Rust regex syntax, linear-time matching.

Results are a flat, file-ordered list of lines. before/after request extra type: context lines around each type: match line, mirroring ripgrep’s –json message type field.

path may be repeated to search multiple roots in one call, the same way pattern/glob already can; results are concatenated in the given order and share the max_total budget across all of them.

Parameters:
  • image_uuid (str) – The UUID of the image to inspect Example: 12345678-9abc-baba-deda-0123456789ab.

  • pattern (str | Sequence[str]) – Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each. Example: ^PermitRootLogin.

  • path (str | Sequence[str] | None) – File or directory to search inside the image. May be repeated (max 16) to search multiple roots; results are concatenated in the given order, sharing max_total across all paths. Defaults to the rootfs root. Example: /etc.

  • glob (str | Sequence[str] | None) – Glob to filter files (ripgrep -g semantics, “!” negates). May be repeated. Example: *.conf.

  • max_count (int | None) – Maximum matches per file (hard cap 10000).

  • max_total (int | None) – Maximum total matches across all files (default 1000, hard cap 10000).

  • case (Literal['sensitive', 'insensitive', 'smart'] | None) – Case sensitivity mode.

  • before (int | None) – Lines of context to include before each match (ripgrep -B semantics, hard cap 50). For symmetric context (grep -C n), pass both before and after yourself.

  • after (int | None) – Lines of context to include after each match (ripgrep -A semantics, hard cap 50).

Return type:

GrepResult

async whoami()[source]

Get current token information.

Returns information about the current authentication token, including the token UUID, expiration time, and a map of all known permissions with their granted status.

Return type:

WhoAmIResponse

contree_client.models

Data models for the Contree API.

Generated by codegen from the OpenAPI spec - do not edit.

contree_client.models.parse_datetime(value)[source]

Parse an ISO 8601 timestamp, tolerating Z suffix and nanoseconds.

Parameters:

value (str)

Return type:

datetime

contree_client.models.wire_value(value)[source]

Recursively encode a value to its JSON-compatible wire form.

Models, datetime and Enum are converted wherever they sit - directly in a field or nested inside lists and mappings.

Parameters:

value (Any)

Return type:

Any

contree_client.models.omitted_dict(items)[source]

dict_factory for dataclasses.asdict used by to_dict().

Fields left unset (…) are omitted entirely so the server-side defaults apply, while an explicit None is serialized as JSON null; datetime and enum values become JSON-friendly at any nesting depth.

Parameters:

items (list[tuple[str, Any]])

Return type:

dict[str, Any]

class contree_client.models.ContreeModel[source]

Bases: object

Base model with the default wire (de)serialization.

to_dict uses each field’s wire name and omits unset (…) fields while keeping explicit None as JSON null. from_dict builds the model from parse_fields; models whose fields need conversion (nested models, datetimes, discriminated unions) override parse_fields only.

classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

classmethod from_dict(data)[source]
Parameters:

data (dict[str, Any])

Return type:

TModel

to_dict()[source]
Return type:

dict[str, Any]

class contree_client.models.OperationStatus(*values)[source]

Bases: str, Enum

Operation lifecycle state.

PENDING = 'PENDING'
ASSIGNED = 'ASSIGNED'
EXECUTING = 'EXECUTING'
SUCCESS = 'SUCCESS'
FAILED = 'FAILED'
CANCELLED = 'CANCELLED'
is_terminal()[source]

True for statuses that will never change again.

Return type:

bool

classmethod terminal()[source]

Statuses that will never change again.

Return type:

frozenset[OperationStatus]

classmethod active()[source]

Statuses of operations that are still in flight.

Return type:

frozenset[OperationStatus]

class contree_client.models.FileItem(size: 'int', path: 'str', owner: 'str | int', group: 'str | int', uid: 'int', gid: 'int', mode: 'int', mtime: 'int', nlink: 'int', is_dir: 'bool', is_regular: 'bool', is_symlink: 'bool', is_socket: 'bool', is_fifo: 'bool', symlink_to: 'str')[source]

Bases: ContreeModel

Fields:

  • size - File size in bytes Example: 1024.

  • path - File name (relative to the directory being listed) Example: passwd.

  • owner - File owner name or UID Example: root.

  • group - File group name or GID Example: root.

  • uid - User ID of the file owner Example: 0.

  • gid - Group ID of the file Example: 0.

  • mode - File mode/permissions as integer (octal representation) Example: 33188.

  • mtime - Last modification time as Unix timestamp Example: 1640995200.

  • nlink - Number of hard links Example: 1.

  • is_dir - True if the item is a directory Example: false.

  • is_regular - True if the item is a regular file Example: true.

  • is_symlink - True if the item is a symbolic link Example: false.

  • is_socket - True if the item is a socket Example: false.

  • is_fifo - True if the item is a FIFO/named pipe Example: false.

  • symlink_to - Target path if the item is a symbolic link, empty string otherwise

Parameters:
size: int
path: str
owner: str | int
group: str | int
uid: int
gid: int
mode: int
mtime: int
is_dir: bool
is_regular: bool
is_socket: bool
is_fifo: bool
class contree_client.models.DirectoryList(path: 'str', files: 'list[FileItem]')[source]

Bases: ContreeModel

Fields:

  • path - The directory path that was listed Example: /etc.

  • files - List of files and directories in the specified path

Parameters:
path: str
files: list[FileItem]
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

as_text(short=False)[source]

Format entries like ls -l, or return one path per line with short=True.

Parameters:

short (bool)

Return type:

str

class contree_client.models.GrepSubmatch(text: 'str', start: 'int', end: 'int')[source]

Bases: ContreeModel

Fields:

  • text - The matched text Example: PermitRootLogin.

  • start - Byte offset of the match start within the line Example: 1.

  • end - Byte offset of the match end within the line Example: 16.

Parameters:
text: str
start: int
end: int
class contree_client.models.GrepMatch(path: 'str', line_number: 'int', absolute_offset: 'int', line_text: 'str', line_bytes: 'int', submatches: 'list[GrepSubmatch]', type: "Literal['match', 'context']")[source]

Bases: ContreeModel

Fields:

  • path - File path relative to the image rootfs Example: /etc/ssh/sshd_config.

  • line_number - 1-based line number of the match Example: 57.

  • absolute_offset - Byte offset of the line from the start of the file Example: 1712.

  • line_text - The matching line, including the line terminator (truncated at 4096 bytes) Example: #PermitRootLogin prohibit-password.

  • line_bytes - Real byte length of the matching line; greater than line_text length when the line was capped Example: 8192.

  • submatches - Empty for context lines (they carry no submatches)

  • type - Mirrors ripgrep’s –json message type: “match” is an actual match, “context” is a before/after context line requested via before/after. Example: match.

Parameters:
path: str
line_number: int
absolute_offset: int
line_text: str
line_bytes: int
submatches: list[GrepSubmatch]
type: Literal['match', 'context']
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

as_text()[source]

Format one grep row with its path, line number, and trailing newline.

Return type:

str

class contree_client.models.GrepResult(path: 'str', patterns: 'list[str]', matches: 'list[GrepMatch]', truncated: 'bool')[source]

Bases: ContreeModel

Fields:

  • path - The first path inside the image that was searched. When path was repeated, see each row’s own path for which root it actually came from. Example: /etc.

  • patterns - The patterns that were searched for Example: ["^PermitRootLogin"].

  • matches - File-ordered lines; each is a match or (when before/after are set) surrounding context

  • truncated - True when max_total or the search deadline stopped the search early Example: false.

Parameters:
path: str
patterns: list[str]
matches: list[GrepMatch]
truncated: bool
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

as_text()[source]

Format grep rows in response order, separating disjoint context groups.

Return type:

str

class contree_client.models.ImageImportRegistryCredentials(username: 'str | EllipsisType' = Ellipsis, password: 'str | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • username - Username for the registry authentication Example: myuser.

  • password - Password for the registry authentication Example: secret.

Parameters:
username: str | EllipsisType = Ellipsis
password: str | EllipsisType = Ellipsis
class contree_client.models.ImageImportRegistry(url: 'str', credentials: 'ImageImportRegistryCredentials | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • url - URL of the container registry Example: docker://docker.io/busybox:latest.

Parameters:
url: str
credentials: ImageImportRegistryCredentials | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.ImageImportRequest(registry: 'ImageImportRegistry', tag: 'str | None | EllipsisType' = Ellipsis, timeout: 'int | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • tag - Tag to identify the image when listing publicly available images. If omitted, the image will be private and only accessible by ID. Example: busybox:latest.

  • timeout - Maximum time in seconds to wait for the import operation to complete Default: 300. Example: 300.

Parameters:
registry: ImageImportRegistry
tag: str | None | EllipsisType = Ellipsis
timeout: int | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.Image(uuid: 'str | EllipsisType' = Ellipsis, tag: 'str | None | EllipsisType' = Ellipsis, created_at: 'str | EllipsisType' = Ellipsis, operation_uuid: 'str | None | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • tag - Tag to identify the image Example: busybox:latest.

  • created_at - ISO 8601 formatted timestamp of when the image was created Example: 2024-01-01T12:00:00+00:00.

  • operation_uuid - UUID of the operation that created this image. Returns null when the image belongs to a different namespace (e.g. public images) or when the image was not created by an operation (e.g. shared images).

Parameters:
uuid: str | EllipsisType = Ellipsis
tag: str | None | EllipsisType = Ellipsis
created_at: str | EllipsisType = Ellipsis
operation_uuid: str | None | EllipsisType = Ellipsis
class contree_client.models.ImageListResponse(images: 'list[Image] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • images - List of publicly available images

Parameters:

images (list[Image] | EllipsisType)

images: list[Image] | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.ImageImportMetadataRegistryCredentials(username: 'str | EllipsisType' = Ellipsis, password: 'str | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • username - Username for the registry authentication Example: myuser.

  • password - Always masked in the response is present Example: <MASKED>.

Parameters:
username: str | EllipsisType = Ellipsis
password: str | EllipsisType = Ellipsis
class contree_client.models.ImageImportMetadataRegistry(url: 'str | EllipsisType' = Ellipsis, credentials: 'ImageImportMetadataRegistryCredentials | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • url - URL of the container registry Example: docker://docker.io/busybox:latest.

Parameters:
url: str | EllipsisType = Ellipsis
credentials: ImageImportMetadataRegistryCredentials | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.ImageImportMetadata(registry: 'ImageImportMetadataRegistry | EllipsisType' = Ellipsis, tag: 'str | None | EllipsisType' = Ellipsis, timeout: 'int | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • timeout - Maximum time in seconds to wait for the import operation to complete Default: 300. Example: 300.

Parameters:
registry: ImageImportMetadataRegistry | EllipsisType = Ellipsis
tag: str | None | EllipsisType = Ellipsis
timeout: int | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.StreamRepr(value: 'str', encoding: "Literal['ascii', 'base64']", truncated: 'bool | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • value - Content of the stream Example: Y29tbWFuZCBvdXRwdXQK.

  • encoding - Encoding of the content Example: base64.

  • truncated - Whether the output was truncated Example: false.

Parameters:
value: str
encoding: Literal['ascii', 'base64']
truncated: bool | EllipsisType = Ellipsis
as_bytes()[source]

The payload decoded to raw bytes.

base64 values are decoded; ascii text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream.

Return type:

bytes

as_text()[source]

The payload decoded to text (UTF-8, errors replaced).

Return type:

str

classmethod from_bytes(value)[source]

Build a payload from raw bytes.

Printable ASCII (plus tab/newline/carriage return) is stored as ascii; anything else is base64-encoded - the same rule the server applies on its side.

Parameters:

value (bytes)

Return type:

StreamRepr

classmethod from_text(value)[source]

Build a payload from text (UTF-8 encoded unless ASCII).

Parameters:

value (str)

Return type:

StreamRepr

class contree_client.models.ClosableStreamRepr(value, encoding=Ellipsis, close=Ellipsis)[source]

Bases: ContreeModel

Stdin payload. Delivery to the child is always complete —.

stdin is never truncated on its way to the process. Only the recorded stdin events in the subprocess event log are capped by truncate_output_at, same as stdout/stderr. This schema also carries a close flag controlling the pipe’s EOF.

Fields:

  • value - Content to write to stdin (may be empty for a close-only request) Example: aGVsbG8K.

  • encoding - Encoding of the content Default: 'ascii'.

  • close - true (default) closes stdin (EOF) after writing value — the pre-existing one-shot behavior. false keeps the pipe open so more data can be sent later via POST /operations/{operationId}/subprocesses/{spid}/stdin. Default: True.

Parameters:
value: str
encoding: Literal['ascii', 'base64'] | EllipsisType = Ellipsis
close: bool | EllipsisType = Ellipsis
as_bytes()[source]

The payload decoded to raw bytes.

base64 values are decoded; ascii text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream.

Return type:

bytes

as_text()[source]

The payload decoded to text (UTF-8, errors replaced).

Return type:

str

classmethod from_bytes(value)[source]

Build a payload from raw bytes.

Printable ASCII (plus tab/newline/carriage return) is stored as ascii; anything else is base64-encoded - the same rule the server applies on its side.

Parameters:

value (bytes)

Return type:

ClosableStreamRepr

classmethod from_text(value)[source]

Build a payload from text (UTF-8 encoded unless ASCII).

Parameters:

value (str)

Return type:

ClosableStreamRepr

class contree_client.models.InstanceResourcesLimits(cpu=Ellipsis, memory_mib=Ellipsis, max_layer_bytes=Ellipsis)[source]

Bases: ContreeModel

Launch-time limits. CPU sets the VM’s vCPU count. memory_mib limits.

each process’s address space (RLIMIT_AS, soft and hard) and the whole process tree’s memory (cgroup memory.max). A request for 1 MiB is valid and enforces that limit on the workload. The backend independently selects a minimum VM RAM allocation for guest boot, networking and runtime services, for example 128 or 256 MiB. This minimum is an implementation detail and can change. It does not increase the requested workload limit. A small address-space limit can prevent the executable or runtime from loading. It includes stacks, libraries and reserved mappings; allocations can fail with ENOMEM even with overcommit enabled. Guest kernel and runtime consume part of VM RAM. Limits are maxima, not reservations. Guest root retains permission to modify cgroups.

Fields:

  • cpu - Number of guest vCPUs. Default: 4.

  • memory_mib - Per-process address-space and process-tree memory limit in MiB (1048576 bytes). Default: 4096.

  • max_layer_bytes - Maximum writable layer size in bytes. Default: 12884901888. Example: 1073741824.

Parameters:
cpu: int | EllipsisType = Ellipsis
memory_mib: int | EllipsisType = Ellipsis
max_layer_bytes: int | EllipsisType = Ellipsis
class contree_client.models.ProcessResourcesLimits(cpu=Ellipsis, memory_mib=Ellipsis)[source]

Bases: ContreeModel

Launch-time limits for a subprocess and its descendants. Each omitted.

or null field inherits the requested operation limit, not the VM’s minimum boot memory. CPU/RAM cannot exceed the parent operation. Limits are maxima, not reservations. Concurrent processes share VM resources and can exhaust the aggregate budget. memory_mib sets RLIMIT_AS (soft and hard) before exec and memory.max for the tree. RLIMIT_AS includes reserved mappings, stacks and libraries; allocation or executable loading can fail with ENOMEM. Descendants inherit it. A local cgroup OOM kills this process tree. A VM-wide OOM can affect other processes. Guest root retains permission to modify cgroups.

Fields:

  • cpu - Number of guest vCPUs available to the process tree. The runtime selects CPU affinity; CPU sets can overlap between subprocesses.

  • memory_mib - Per-process RLIMIT_AS and tree memory.max in MiB. Swap is disabled for this group.

Parameters:
cpu: int | None | EllipsisType = Ellipsis
memory_mib: int | None | EllipsisType = Ellipsis
class contree_client.models.InstanceNetworking(enabled: 'bool | EllipsisType' = Ellipsis, policy: 'list[str] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • enabled - Enable network access for the instance. When false, the VM starts without a guest network interface. Default: True.

  • policy - Network policies to apply, referenced by UUID or by tag prefixed with tag:. References - You can use your own policies and shared policies. - Your tag takes precedence over a shared tag with the same name. - Duplicate references and resolved policy UUIDs are removed while preserving first occurrence order. - Unknown or unavailable references return 404. - Deleted policies remain usable by UUID. Permissions Using policies requires only the permission to create the instance; network_policy is not required. Limits - At most 512 references may be supplied, including duplicates. - Before and after merging, the rules are limited to 16384 units in total: sum the number of ports across all rules, counting an all-port rule as 1. All IP versions and protocols share this limit. Repeated rules and ports across policies count again before merging. - Exceeding either limit returns 400. No policies Omitting this field or passing policy: [] allows all IPv4 destinations and global unicast IPv6 destinations on all ports. The API adds four explicit rules to effective_policy: TCP and UDP for IPv4 0.0.0.0/0 and IPv6 2000::/3, each with ports: [] (all ports). ICMP is also allowed to these destinations. IPv6 destinations outside 2000::/3, including unique-local and link-local addresses, require explicit policy rules. Empty policies A selected policy with no rules ({"cidrs": []}) allows nothing. If all selected policies are empty, effective_policy is {"cidrs": []} and all network traffic is denied. An empty policy combined with non-empty policies adds no permissions; the other policies’ rules still apply. Effective policy effective_policy contains the final combined network rules that will be applied to the operation. Rules are combined by merging CIDRs per protocol and port, then grouping ports for matching CIDRs and protocols. Default: []. Example: ["12345678-9abc-baba-deda-0123456789ab","tag:github"].

Parameters:
enabled: bool | EllipsisType = Ellipsis
policy: list[str] | EllipsisType = Ellipsis
class contree_client.models.NetworkPolicyCIDRRule(cidr: 'str', proto: "Literal['tcp', 'udp']", ports: 'list[int] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • cidr - IPv4 or IPv6 destination network in CIDR notation. Example: 192.0.2.0/24.

  • ports - Allowed destination ports. Omitted or empty means all ports. Default: [].

Parameters:
cidr: str
proto: Literal['tcp', 'udp']
ports: list[int] | EllipsisType = Ellipsis
class contree_client.models.NetworkPolicyCreateRequest(cidrs)[source]

Bases: ContreeModel

An allowlist of destination networks, protocols, and ports. A policy with {"cidrs": []}.

allows nothing. Selecting only empty policies denies all network traffic. This differs from selecting no policies (networking.policy: []), which allows all IPv4 destinations (0.0.0.0/0) and global unicast IPv6 destinations (2000::/3) on all ports and adds these explicit rules to effective_policy.

Parameters:

cidrs (list[NetworkPolicyCIDRRule])

cidrs: list[NetworkPolicyCIDRRule]
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.InstanceNetworkingResponse(enabled: 'bool | EllipsisType' = Ellipsis, policy: 'list[str] | EllipsisType' = Ellipsis, effective_policy: 'NetworkPolicyCreateRequest | None | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • enabled - Enable network access for the instance. When false, the VM starts without a guest network interface. Default: True.

  • policy - Unique applied policy UUIDs in first occurrence order. Tag references are returned as UUIDs.

  • effective_policy - The final combined network rules that will be applied to the operation. New instances always include an explicit effective policy, including when no policy references are specified. Omitting networking.policy or passing policy: [] allows all IPv4 and global unicast IPv6 destinations on all ports: this field contains four rules, TCP and UDP for both 0.0.0.0/0 (IPv4) and 2000::/3 (IPv6), with ports: [] on each rule. ICMP is also allowed to these destinations. IPv6 destinations outside 2000::/3 require explicit policy rules. Selecting only empty policies ({"cidrs": []}) instead produces {"cidrs": []}, which denies all network traffic. Empty policies add no permissions when combined with non-empty policies. Historical instance metadata may omit this field or contain null.

Parameters:
enabled: bool | EllipsisType = Ellipsis
policy: list[str] | EllipsisType = Ellipsis
effective_policy: NetworkPolicyCreateRequest | None | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.NetworkPolicyTag(tag: 'str', uuid: 'str')[source]

Bases: ContreeModel

Fields:

  • tag - Network policy tag name

Parameters:
tag: str
uuid: str
class contree_client.models.NetworkPolicy(uuid: 'str', cidrs: 'list[NetworkPolicyCIDRRule]')[source]

Bases: ContreeModel

Parameters:
uuid: str
cidrs: list[NetworkPolicyCIDRRule]
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.NetworkPolicyListItemSummary(cidrs: 'int')[source]

Bases: ContreeModel

Fields:

  • cidrs - Number of CIDR rules in the policy, including repeated CIDRs.

Parameters:

cidrs (int)

cidrs: int
class contree_client.models.NetworkPolicyListItem(uuid: 'str', created_at: 'datetime', tags: 'list[str]', summary: 'NetworkPolicyListItemSummary')[source]

Bases: ContreeModel

Fields:

  • created_at - Time when the policy was created.

  • tags - Accessible tag names resolving to this policy, sorted by name. Empty when none exist.

Parameters:
uuid: str
created_at: datetime
tags: list[str]
summary: NetworkPolicyListItemSummary
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.NetworkPolicyListResponse(policies: 'list[NetworkPolicyListItem]')[source]

Bases: ContreeModel

Parameters:

policies (list[NetworkPolicyListItem])

policies: list[NetworkPolicyListItem]
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.ExecSpec(command, resources_limits=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, stdin=Ellipsis, truncate_output_at=Ellipsis)[source]

Bases: ContreeModel

Process-execution surface shared between InstanceSpawnRequest.

(the main process) and POST /operations/{operationId}/subprocesses (additional subprocesses). VM-level concerns (image, hostname, disk limits, files, timeout, disposable, preserve_env) live on InstanceSpawnRequest only.

Fields:

  • command - The command to execute. Same semantics as in InstanceSpawnRequest.command — when shell=true it is a shell expression, otherwise a path to an executable. Example: /bin/app.

  • args - Arguments to pass to the command if shell is set to false. Default: []. Example: ["arg1","arg2"].

  • shell - Run command through a shell expression (args must be empty). Default: False.

  • env - Environment variables to set in the child process.

  • cwd - Working directory; empty string means image / server default. Default: ''.

  • uid - User ID to run the process as. Default: 0.

  • gid - Group ID to run the process as. Default: 0.

  • stdin - Bytes fed to the child’s stdin — honored for both the main process and exec’d subprocesses. With close=false the pipe stays open and more data can be written via POST /operations/{operationId}/subprocesses/{spid}/stdin.

  • truncate_output_at - Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect delivery to the child — stdin is always delivered in full regardless of this cap. Defaults to 1 MiB; capped at 10 MiB. Default: 1048576. Example: 65535.

Parameters:
command: str
resources_limits: ProcessResourcesLimits | EllipsisType = Ellipsis
args: list[str] | EllipsisType = Ellipsis
shell: bool | EllipsisType = Ellipsis
env: dict[str, str] | None | EllipsisType = Ellipsis
cwd: str | EllipsisType = Ellipsis
uid: int | EllipsisType = Ellipsis
gid: int | EllipsisType = Ellipsis
stdin: ClosableStreamRepr | EllipsisType = Ellipsis
truncate_output_at: int | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.FileSpec(uuid: 'str | EllipsisType' = Ellipsis, uid: 'int | EllipsisType' = Ellipsis, gid: 'int | EllipsisType' = Ellipsis, mode: 'str | int | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • uid - User ID Example: 0.

  • gid - Group ID Example: 0.

  • mode - File mode in octal format (e.g., “0644”) Example: 0644.

Parameters:
uuid: str | EllipsisType = Ellipsis
uid: int | EllipsisType = Ellipsis
gid: int | EllipsisType = Ellipsis
mode: str | int | EllipsisType = Ellipsis
class contree_client.models.InstanceSpawnRequest(command: 'str', image: 'str', disposable: 'bool | EllipsisType' = Ellipsis, hostname: 'str | EllipsisType' = Ellipsis, args: 'list[str] | EllipsisType' = Ellipsis, shell: 'bool | EllipsisType' = Ellipsis, env: 'dict[str, str] | None | EllipsisType' = Ellipsis, preserve_env: 'bool | EllipsisType' = Ellipsis, preserve_cwd: 'bool | EllipsisType' = Ellipsis, cwd: 'str | EllipsisType' = Ellipsis, uid: 'int | EllipsisType' = Ellipsis, gid: 'int | EllipsisType' = Ellipsis, resources_limits: 'InstanceResourcesLimits | EllipsisType' = Ellipsis, networking: 'InstanceNetworking | EllipsisType' = Ellipsis, stdin: 'ClosableStreamRepr | EllipsisType' = Ellipsis, timeout: 'int | EllipsisType' = Ellipsis, truncate_output_at: 'int | EllipsisType' = Ellipsis, files: 'dict[str, FileSpec] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • command - The command to execute. In case if shell is set to true, this MUST contain shell expression. For example echo hello world or ls -l /app. If shell is set to false, this must be a relative or absolute path to the executable inside the image rootfs. For example: /bin/app or /usr/bin/find. Do not forget pass necessary PATH variable to env field, by default PATH is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Example: /bin/app.

  • disposable - Creates a disposable execution environment no any state will be saved. Default: False.

  • hostname - Hostname to set when execution. Default: 'linuxkit'. Example: container-name.

  • args - Arguments to pass to the command if shell is set to false. Default: []. Example: ["arg1","arg2"].

  • shell - Whether to run the command through a shell. If true, the command must be a shell expression and all values from args will be ignored. If false, the command field must be a path to an executable and args will be used. When true, environment variables from the image are automatically inherited. When false, they are not - use the env field to pass them explicitly. Default: False.

  • env - Environment variables to set in the container. These are merged with image-defined variables when shell is true. When shell is false, only variables specified here are available - image-defined variables are not inherited. Example: {"KEY1":"value1","KEY2":"value2"}.

  • preserve_env - Preserve environment variables in resulting image after execution. When true, the image’s existing environment variables from metadata/env are merged with user-provided env values (user values take priority on conflicts), and the combined result is written back to metadata/env after command execution. Setting a variable to an empty string or null removes it from the preserved environment. Default: False.

  • preserve_cwd - Save the resolved initial working directory as the default in the resulting image. An empty or omitted cwd resolves to the image’s current workdir, or / if none exists. The metadata file is opened for writing only when its contents differ from the new value. Directory changes made by the command do not change the saved value. Requires disposable: false to retain the metadata in a resulting image. Default: False.

  • cwd - Path to the working directory, must be absolute or a special value the empty string. It means the default working directory of the image or server default will be used. If field is omitted it will be set to the empty string. The directory will be created automatically if it does not exist. Default: ''. Example: /app.

  • uid - User ID to run the process as. Default: 0. Example: 0.

  • gid - Group ID to run the process as. Default: 0. Example: 0.

  • timeout - Maximum execution time in seconds Example: 60.

  • truncate_output_at - Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect stdin delivery to the child, which always receives the complete stream regardless of this cap. Default is 1048576 (1 MiB). The maximum value is 10485760 (10 MiB). Default: 1048576. Example: 65535.

  • files - Map of absolute file paths to file metadata Example: {"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c....

Parameters:
command: str
image: str
disposable: bool | EllipsisType = Ellipsis
hostname: str | EllipsisType = Ellipsis
args: list[str] | EllipsisType = Ellipsis
shell: bool | EllipsisType = Ellipsis
env: dict[str, str] | None | EllipsisType = Ellipsis
preserve_env: bool | EllipsisType = Ellipsis
preserve_cwd: bool | EllipsisType = Ellipsis
cwd: str | EllipsisType = Ellipsis
uid: int | EllipsisType = Ellipsis
gid: int | EllipsisType = Ellipsis
resources_limits: InstanceResourcesLimits | EllipsisType = Ellipsis
networking: InstanceNetworking | EllipsisType = Ellipsis
stdin: ClosableStreamRepr | EllipsisType = Ellipsis
timeout: int | EllipsisType = Ellipsis
truncate_output_at: int | EllipsisType = Ellipsis
files: dict[str, FileSpec] | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.InstanceResultResources(block_input: 'int | EllipsisType' = Ellipsis, block_output: 'int | EllipsisType' = Ellipsis, cost: 'float | EllipsisType' = Ellipsis, elapsed_time: 'float | EllipsisType' = Ellipsis, involuntary_switches: 'int | EllipsisType' = Ellipsis, max_rss: 'int | EllipsisType' = Ellipsis, monotonic_time: 'float | EllipsisType' = Ellipsis, page_faults: 'int | EllipsisType' = Ellipsis, page_faults_io: 'int | EllipsisType' = Ellipsis, shared_memory: 'int | EllipsisType' = Ellipsis, signals: 'int | EllipsisType' = Ellipsis, swaps: 'int | EllipsisType' = Ellipsis, system_cpu_time: 'float | EllipsisType' = Ellipsis, unshared_memory: 'int | EllipsisType' = Ellipsis, user_cpu_time: 'float | EllipsisType' = Ellipsis, voluntary_switches: 'int | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • block_input - Block input operations

  • block_output - Block output operations

  • cost - Operation cost

  • elapsed_time - Elapsed wall time

  • involuntary_switches - Number of involuntary context switches

  • max_rss - Maximum resident set size in KB

  • monotonic_time - Monotonic time measurement

  • page_faults - Number of page faults

  • page_faults_io - Number of page faults requiring I/O

  • shared_memory - Shared memory size

  • signals - Number of signals received

  • swaps - Number of swaps

  • system_cpu_time - System CPU time used

  • unshared_memory - Unshared memory size

  • user_cpu_time - User CPU time used

  • voluntary_switches - Number of voluntary context switches

Parameters:
block_input: int | EllipsisType = Ellipsis
block_output: int | EllipsisType = Ellipsis
cost: float | EllipsisType = Ellipsis
elapsed_time: float | EllipsisType = Ellipsis
involuntary_switches: int | EllipsisType = Ellipsis
max_rss: int | EllipsisType = Ellipsis
monotonic_time: float | EllipsisType = Ellipsis
page_faults: int | EllipsisType = Ellipsis
page_faults_io: int | EllipsisType = Ellipsis
shared_memory: int | EllipsisType = Ellipsis
signals: int | EllipsisType = Ellipsis
swaps: int | EllipsisType = Ellipsis
system_cpu_time: float | EllipsisType = Ellipsis
unshared_memory: int | EllipsisType = Ellipsis
user_cpu_time: float | EllipsisType = Ellipsis
voluntary_switches: int | EllipsisType = Ellipsis
class contree_client.models.InstanceResultState(continued: 'bool | EllipsisType' = Ellipsis, core_dump: 'bool | EllipsisType' = Ellipsis, exit_code: 'int | EllipsisType' = Ellipsis, pid: 'int | EllipsisType' = Ellipsis, signal: 'int | EllipsisType' = Ellipsis, stopped: 'bool | EllipsisType' = Ellipsis, timed_out: 'bool | EllipsisType' = Ellipsis, oom_killed: 'bool | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • continued - Whether the process was continued from a stop

  • core_dump - Whether a core dump was generated

  • exit_code - Process exit code

  • pid - Process ID

  • signal - Signal that caused termination, if any

  • stopped - Whether the process was stopped

  • timed_out - Whether process had been killed because operation timeout was reached

  • oom_killed - Whether an OOM kill was observed in the process tree’s cgroup. Default: False.

Parameters:
continued: bool | EllipsisType = Ellipsis
core_dump: bool | EllipsisType = Ellipsis
exit_code: int | EllipsisType = Ellipsis
pid: int | EllipsisType = Ellipsis
signal: int | EllipsisType = Ellipsis
stopped: bool | EllipsisType = Ellipsis
timed_out: bool | EllipsisType = Ellipsis
oom_killed: bool | EllipsisType = Ellipsis
class contree_client.models.InstanceResult(resources=Ellipsis, state=Ellipsis, stdout=Ellipsis, stderr=Ellipsis)[source]

Bases: ContreeModel

Result of an instance execution.

Parameters:
resources: InstanceResultResources | EllipsisType = Ellipsis
state: InstanceResultState | EllipsisType = Ellipsis
stdout: StreamRepr | EllipsisType = Ellipsis
stderr: StreamRepr | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.InstanceSpawnResponse(uuid: 'str | EllipsisType' = Ellipsis, command: 'str | EllipsisType' = Ellipsis, image: 'str | EllipsisType' = Ellipsis, hostname: 'str | EllipsisType' = Ellipsis, args: 'list[str] | EllipsisType' = Ellipsis, shell: 'bool | EllipsisType' = Ellipsis, env: 'dict[str, str] | None | EllipsisType' = Ellipsis, preserve_env: 'bool | EllipsisType' = Ellipsis, cwd: 'str | EllipsisType' = Ellipsis, uid: 'int | EllipsisType' = Ellipsis, gid: 'int | EllipsisType' = Ellipsis, resources_limits: 'InstanceResourcesLimits | EllipsisType' = Ellipsis, networking: 'InstanceNetworkingResponse | EllipsisType' = Ellipsis, stdin: 'ClosableStreamRepr | EllipsisType' = Ellipsis, timeout: 'int | EllipsisType' = Ellipsis, truncate_output_at: 'int | EllipsisType' = Ellipsis, disposable: 'bool | EllipsisType' = Ellipsis, files: 'dict[str, FileSpec] | EllipsisType' = Ellipsis, result: 'InstanceResult | None | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Parameters:
uuid: str | EllipsisType = Ellipsis
command: str | EllipsisType = Ellipsis
image: str | EllipsisType = Ellipsis
hostname: str | EllipsisType = Ellipsis
args: list[str] | EllipsisType = Ellipsis
shell: bool | EllipsisType = Ellipsis
env: dict[str, str] | None | EllipsisType = Ellipsis
preserve_env: bool | EllipsisType = Ellipsis
cwd: str | EllipsisType = Ellipsis
uid: int | EllipsisType = Ellipsis
gid: int | EllipsisType = Ellipsis
resources_limits: InstanceResourcesLimits | EllipsisType = Ellipsis
networking: InstanceNetworkingResponse | EllipsisType = Ellipsis
stdin: ClosableStreamRepr | EllipsisType = Ellipsis
timeout: int | EllipsisType = Ellipsis
truncate_output_at: int | EllipsisType = Ellipsis
disposable: bool | EllipsisType = Ellipsis
files: dict[str, FileSpec] | EllipsisType = Ellipsis
result: InstanceResult | None | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.OperationSummary(uuid: 'str | EllipsisType' = Ellipsis, kind: "Literal['image_import', 'instance'] | EllipsisType" = Ellipsis, status: 'OperationStatus | EllipsisType' = Ellipsis, error: 'str | None | EllipsisType' = Ellipsis, created_at: 'str | EllipsisType' = Ellipsis, duration: 'float | None | EllipsisType' = Ellipsis, image_size: 'int | None | EllipsisType' = Ellipsis, consumed_cpu: 'float | None | EllipsisType' = Ellipsis, consumed_memory: 'int | None | EllipsisType' = Ellipsis, image_uuid: 'str | None | EllipsisType' = Ellipsis, result_image_uuid: 'str | None | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • kind - Type of the operation

  • status - Current state of the instance operation Example: success.

  • error - Error message if the operation failed Example: Container image not found.

  • created_at - ISO 8601 formatted timestamp when the operation was created Example: 2024-01-01T12:00:00+00:00.

  • duration - Operation duration in seconds

  • image_size - Bytes written for the resulting image/layer(s). null when not measured (e.g. disposable instance, non-SUCCESS operations).

  • consumed_cpu - Total CPU time consumed by the operation, in seconds. null when not measured.

  • consumed_memory - Peak resident memory used by the operation’s execution environment, in KiB. null when not measured. Shared resident pages are included.

  • image_uuid - UUID of the source image this operation was run on. Set for INSTANCE operations, null for IMAGE_IMPORT.

  • result_image_uuid - UUID of the image produced by this operation. Only set for completed (SUCCESS) operations, null otherwise.

Parameters:
uuid: str | EllipsisType = Ellipsis
kind: Literal['image_import', 'instance'] | EllipsisType = Ellipsis
status: OperationStatus | EllipsisType = Ellipsis
error: str | None | EllipsisType = Ellipsis
created_at: str | EllipsisType = Ellipsis
duration: float | None | EllipsisType = Ellipsis
image_size: int | None | EllipsisType = Ellipsis
consumed_cpu: float | None | EllipsisType = Ellipsis
consumed_memory: int | None | EllipsisType = Ellipsis
image_uuid: str | None | EllipsisType = Ellipsis
result_image_uuid: str | None | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.OperationInstanceMetadata(command: 'str', image: 'str', disposable: 'bool | EllipsisType' = Ellipsis, hostname: 'str | EllipsisType' = Ellipsis, args: 'list[str] | EllipsisType' = Ellipsis, shell: 'bool | EllipsisType' = Ellipsis, env: 'dict[str, str] | None | EllipsisType' = Ellipsis, preserve_env: 'bool | EllipsisType' = Ellipsis, preserve_cwd: 'bool | EllipsisType' = Ellipsis, cwd: 'str | EllipsisType' = Ellipsis, uid: 'int | EllipsisType' = Ellipsis, gid: 'int | EllipsisType' = Ellipsis, resources_limits: 'InstanceResourcesLimits | EllipsisType' = Ellipsis, networking: 'InstanceNetworkingResponse | EllipsisType' = Ellipsis, stdin: 'ClosableStreamRepr | EllipsisType' = Ellipsis, timeout: 'int | EllipsisType' = Ellipsis, truncate_output_at: 'int | EllipsisType' = Ellipsis, files: 'dict[str, FileSpec] | EllipsisType' = Ellipsis, result: 'InstanceResult | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • command - The command to execute. In case if shell is set to true, this MUST contain shell expression. For example echo hello world or ls -l /app. If shell is set to false, this must be a relative or absolute path to the executable inside the image rootfs. For example: /bin/app or /usr/bin/find. Do not forget pass necessary PATH variable to env field, by default PATH is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Example: /bin/app.

  • disposable - Creates a disposable execution environment no any state will be saved. Default: False.

  • hostname - Hostname to set when execution. Default: 'linuxkit'. Example: container-name.

  • args - Arguments to pass to the command if shell is set to false. Default: []. Example: ["arg1","arg2"].

  • shell - Whether to run the command through a shell. If true, the command must be a shell expression and all values from args will be ignored. If false, the command field must be a path to an executable and args will be used. When true, environment variables from the image are automatically inherited. When false, they are not - use the env field to pass them explicitly. Default: False.

  • env - Environment variables to set in the container. These are merged with image-defined variables when shell is true. When shell is false, only variables specified here are available - image-defined variables are not inherited. Example: {"KEY1":"value1","KEY2":"value2"}.

  • preserve_env - Preserve environment variables in resulting image after execution. When true, the image’s existing environment variables from metadata/env are merged with user-provided env values (user values take priority on conflicts), and the combined result is written back to metadata/env after command execution. Setting a variable to an empty string or null removes it from the preserved environment. Default: False.

  • preserve_cwd - Save the resolved initial working directory as the default in the resulting image. An empty or omitted cwd resolves to the image’s current workdir, or / if none exists. The metadata file is opened for writing only when its contents differ from the new value. Directory changes made by the command do not change the saved value. Requires disposable: false to retain the metadata in a resulting image. Default: False.

  • cwd - Path to the working directory, must be absolute or a special value the empty string. It means the default working directory of the image or server default will be used. If field is omitted it will be set to the empty string. The directory will be created automatically if it does not exist. Default: ''. Example: /app.

  • uid - User ID to run the process as. Default: 0. Example: 0.

  • gid - Group ID to run the process as. Default: 0. Example: 0.

  • timeout - Maximum execution time in seconds Example: 60.

  • truncate_output_at - Maximum number of bytes to keep per stream (stdout, stderr, and stdin) in the subprocess event log. Does not affect stdin delivery to the child, which always receives the complete stream regardless of this cap. Default is 1048576 (1 MiB). The maximum value is 10485760 (10 MiB). Default: 1048576. Example: 65535.

  • files - Map of absolute file paths to file metadata Example: {"/root/hello.txt":{"uuid":"a9165a5d-5c86-4bd8-8ee4-ae46c....

Parameters:
command: str
image: str
disposable: bool | EllipsisType = Ellipsis
hostname: str | EllipsisType = Ellipsis
args: list[str] | EllipsisType = Ellipsis
shell: bool | EllipsisType = Ellipsis
env: dict[str, str] | None | EllipsisType = Ellipsis
preserve_env: bool | EllipsisType = Ellipsis
preserve_cwd: bool | EllipsisType = Ellipsis
cwd: str | EllipsisType = Ellipsis
uid: int | EllipsisType = Ellipsis
gid: int | EllipsisType = Ellipsis
resources_limits: InstanceResourcesLimits | EllipsisType = Ellipsis
networking: InstanceNetworkingResponse | EllipsisType = Ellipsis
stdin: ClosableStreamRepr | EllipsisType = Ellipsis
timeout: int | EllipsisType = Ellipsis
truncate_output_at: int | EllipsisType = Ellipsis
files: dict[str, FileSpec] | EllipsisType = Ellipsis
result: InstanceResult | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.OperationResult(image=Ellipsis, tag=Ellipsis)[source]

Bases: ContreeModel

Result of the operation, if any.

Fields:

  • tag - Tag assigned to the imported image Example: busybox:latest.

Parameters:
image: str | None | EllipsisType = Ellipsis
tag: str | None | EllipsisType = Ellipsis
class contree_client.models.OperationResponse(uuid: 'str | EllipsisType' = Ellipsis, kind: "Literal['image_import', 'instance'] | EllipsisType" = Ellipsis, status: 'OperationStatus | EllipsisType' = Ellipsis, error: 'str | None | EllipsisType' = Ellipsis, created_at: 'str | EllipsisType' = Ellipsis, duration: 'float | None | EllipsisType' = Ellipsis, image_size: 'int | None | EllipsisType' = Ellipsis, consumed_cpu: 'float | None | EllipsisType' = Ellipsis, consumed_memory: 'int | None | EllipsisType' = Ellipsis, image_uuid: 'str | None | EllipsisType' = Ellipsis, result_image_uuid: 'str | None | EllipsisType' = Ellipsis, metadata: 'OperationInstanceMetadata | ImageImportMetadata | EllipsisType' = Ellipsis, result: 'OperationResult | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • kind - Type of the operation

  • created_at - ISO 8601 formatted timestamp when the operation was created Example: 2024-01-01T12:00:00+00:00.

  • image_size - Bytes written for the resulting image/layer(s). null when not measured (e.g. disposable instance, non-SUCCESS operations).

  • consumed_cpu - Total CPU time consumed by the operation, in seconds. null when not measured.

  • consumed_memory - Peak resident memory used by the operation’s execution environment, in KiB. null when not measured. Shared resident pages are included.

  • image_uuid - UUID of the source image this operation was run on. Set for INSTANCE operations, null for IMAGE_IMPORT.

  • result_image_uuid - UUID of the image produced by this operation. Only set for completed (SUCCESS) operations, null otherwise.

  • result - Result of the operation, if any

Parameters:
uuid: str | EllipsisType = Ellipsis
kind: Literal['image_import', 'instance'] | EllipsisType = Ellipsis
status: OperationStatus | EllipsisType = Ellipsis
error: str | None | EllipsisType = Ellipsis
created_at: str | EllipsisType = Ellipsis
duration: float | None | EllipsisType = Ellipsis
image_size: int | None | EllipsisType = Ellipsis
consumed_cpu: float | None | EllipsisType = Ellipsis
consumed_memory: int | None | EllipsisType = Ellipsis
image_uuid: str | None | EllipsisType = Ellipsis
result_image_uuid: str | None | EllipsisType = Ellipsis
metadata: OperationInstanceMetadata | ImageImportMetadata | EllipsisType = Ellipsis
result: OperationResult | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.Error(error: 'Any', status: 'int | EllipsisType' = Ellipsis, traceback: 'list[str] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • error - Error message or structured validation errors Example: Some error occurred, this is an example of error message.

  • status - HTTP status code Example: 500.

Parameters:
error: Any
status: int | EllipsisType = Ellipsis
traceback: list[str] | EllipsisType = Ellipsis
class contree_client.models.FileResponse(uuid: 'str', sha256: 'str', size: 'int')[source]

Bases: ContreeModel

Fields:

  • sha256 - SHA256 hash of the file content Example: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7....

  • size - File size in bytes; -1 if unknown Example: 1024.

Parameters:
uuid: str
sha256: str
size: int
class contree_client.models.File(uuid: 'str', sha256: 'str', size: 'int', created_at: 'datetime', updated_at: 'datetime')[source]

Bases: ContreeModel

Fields:

  • sha256 - SHA256 hash of the file content

  • size - File size in bytes; -1 if unknown Example: 1024.

  • created_at - When the file was first uploaded by this namespace

  • updated_at - Updated on each upload of the same file

Parameters:
uuid: str
sha256: str
size: int
created_at: datetime
updated_at: datetime
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.FilesListResponse(files: 'list[File] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Parameters:

files (list[File] | EllipsisType)

files: list[File] | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.WhoAmIResponse(token_uuid: 'str', token_expiration: 'int | None', permissions: 'dict[str, bool]', operations_stat: 'dict[str, int]', limits: 'dict[str, int] | EllipsisType' = Ellipsis)[source]

Bases: ContreeModel

Fields:

  • token_uuid - UUID of the authentication token Example: a1b2c3d4-e5f6-7890-abcd-ef1234567890.

  • token_expiration - Token expiration time as Unix timestamp, or null if not set Example: 1735689600.

  • permissions - Map of all known permission names to their granted status. Keys are permission names (e.g., import, spawn, list), values indicate whether the token has the permission. Example: {"import":true,"spawn":true,"spawn_disposable":false,"lis....

  • operations_stat - Operation statistics (reserved for future use)

  • limits - Map of resource limit names to their values for the current token. Example: {"instance_max_timeout":3600,"instance_max_concurrency":1....

Parameters:
token_uuid: str
token_expiration: int | None
permissions: dict[str, bool]
operations_stat: dict[str, int]
limits: dict[str, int] | EllipsisType = Ellipsis
class contree_client.models.OperationEvent(id, ts, type, data, spid=Ellipsis)[source]

Bases: ContreeModel

One event in the operation’s event log.

Process events carry a Spawned Process ID (spid) as their routing identity: spid=0 is the daemon (init / network / shutdown / size_cap, plus any synthetic stderr emitted before a child existed), spid=1 is the main process from InstanceMetadata, and spid>=2 are exec’d children (Phase 3+). Spids are Registry-assigned, monotonic, and never recycled within an operation; the kernel PID (when needed for debugging) lives inside the per-type data payload.

System events (completion) describe the operation as a whole, not a specific child process — they omit spid entirely.

Fields:

  • id - Sequential id assigned at append time. Strictly increasing within a single operation’s event log; gaps are possible (rare, after a transient producer-side serialization failure). Use this with Last-Event-Id / ?since= to resume a dropped SSE stream. Example: 42.

  • ts - UTC wall-clock time when the event was emitted. Example: 2026-06-08T20:00:00.123456789Z.

  • data - Per-type payload. Clients should switch on type and validate data against the corresponding schema below.

  • spid - Spawned Process ID — present on process-scoped events (init, spawn, stdin, stdout, stderr, exit, truncated, size_cap, network, shutdown, inspect, file_upload). Absent on operation-scoped system events (completion), which don’t tie to a specific child. Example: 1.

Parameters:
id: int
ts: datetime
type: Literal['init', 'spawn', 'stdin', 'stdout', 'stderr', 'exit', 'truncated', 'size_cap', 'network', 'shutdown', 'inspect', 'file_upload', 'completion']
data: EventDataInit | EventDataSpawn | EventDataStream | EventDataExit | EventDataTruncated | EventDataSizeCap | EventDataNetwork | EventDataShutdown | EventDataInspect | EventDataFileUpload | EventDataCompletion | dict[str, Any]
spid: int | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventInspectParametersOptions(patterns: 'list[str] | None', globs: 'list[str] | None', case: 'str', max_count: 'int', max_total: 'int', before: 'int', after: 'int')[source]

Bases: ContreeModel

Parameters:
patterns: list[str] | None
globs: list[str] | None
case: str
max_count: int
max_total: int
before: int
after: int
class contree_client.models.EventInspectParameters(path=Ellipsis, file_uuid=Ellipsis, unpack=Ellipsis, replace=Ellipsis, merge=Ellipsis, handle=Ellipsis, offset=Ellipsis, size=Ellipsis, options=Ellipsis)[source]

Bases: ContreeModel

Parameters for the method named in EventDataInspect. Path methods.

(stat/list/open/archive/grep/upload) record path. Grep also records options. Upload records file_uuid, unpack, replace, and merge. Read/write record handle, offset, and size; write size is the input chunk length, not an acknowledgement. Close/finish record handle. Binary payloads are excluded.

Parameters:
path: str | EllipsisType = Ellipsis
file_uuid: str | EllipsisType = Ellipsis
unpack: bool | EllipsisType = Ellipsis
replace: bool | EllipsisType = Ellipsis
merge: bool | EllipsisType = Ellipsis
handle: str | EllipsisType = Ellipsis
offset: int | EllipsisType = Ellipsis
size: int | EllipsisType = Ellipsis
options: EventInspectParametersOptions | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataInspect(request_id, method, phase, params=Ellipsis, status=Ellipsis, error=Ellipsis, handle=Ellipsis, bytes=Ellipsis, eof=Ellipsis)[source]

Bases: ContreeModel

Metadata for a guest inspect RPC. Init emits a started/completed pair.

with the same request_id. Event IDs order the starts independently of completion order. A returned handle links subsequent reads, writes, finish, close, and file_upload events. All events use spid=0. Request parameters are recorded even when the method rejects them. A successful open/upload only allocates a handle; it does not complete the transfer. Read events report RPC bytes, not HTTP client receipt. File contents, directory listings, and grep matches are never recorded. Events are flushed to the journal and bypass the stream size cap. A missing completion can indicate an interrupted or lost event. These records support a future replay implementation; replay is not automatic.

Fields:

  • request_id - Opaque identifier shared by the request and result events.

  • error - Error category only; null on success. No exception text or file contents.

  • handle - Present after a successful open, archive, grep, or upload.

  • bytes - Bytes returned by a successful read.

  • eof - Present after a successful read; true at the end of its stream.

Parameters:
request_id: str
method: Literal['stat', 'list', 'open', 'archive', 'grep', 'read', 'close', 'upload', 'write', 'finish']
phase: Literal['started', 'completed']
params: EventInspectParameters | EllipsisType = Ellipsis
status: Literal['success', 'error', 'cancelled', 'timeout'] | EllipsisType = Ellipsis
error: str | None | EllipsisType = Ellipsis
handle: str | EllipsisType = Ellipsis
bytes: int | EllipsisType = Ellipsis
eof: bool | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataFileUpload(handle, file_uuid, path, unpack, replace, merge, bytes, status, error)[source]

Bases: ContreeModel

Init emits this event once after publication or cleanup of an accepted.

upload. It is emitted even if the host disconnects or Finish loses its response. A rejected upload has only its inspect request/result pair. Success means publication finished. Error or cancellation can leave a partially applied merge, as specified by the upload endpoint. The event contains metadata only, uses spid=0, bypasses the stream size cap, and is flushed before shutdown. Recording does not extend the source file’s TTL or guarantee its availability for future replay.

Fields:

  • path - Clean absolute destination path.

  • bytes - Source bytes consumed from the upload pipe, including on failure. For an archive, counts compressed/source bytes, not extracted bytes. This is not a count of bytes successfully published to the destination.

  • error - Error category only; null on success.

Parameters:
  • handle (str)

  • file_uuid (str)

  • path (str)

  • unpack (bool)

  • replace (bool)

  • merge (bool)

  • bytes (int)

  • status (Literal['success', 'error', 'cancelled', 'timeout'])

  • error (str | None)

handle: str
file_uuid: str
path: str
unpack: bool
replace: bool
merge: bool
bytes: int
status: Literal['success', 'error', 'cancelled', 'timeout']
error: str | None
class contree_client.models.EventDataInit(started_at, runtime_path, verbose, init_pid, hostname=Ellipsis, kernel=Ellipsis, machine=Ellipsis, boot_id=Ellipsis)[source]

Bases: ContreeModel

Operation-level startup snapshot. hostname, kernel,.

machine, boot_id are best-effort — omitted if the environment couldn’t provide them.

Fields:

  • started_at - Example: 2026-06-08T20:00:00.000000000Z.

  • runtime_path - Internal runtime directory for the operation. Example: /run/contreeinitd.

  • verbose - Example: false.

  • init_pid - PID of the operation’s init process. Example: 1.

  • hostname - Example: vm-abc123.

  • kernel - uname release + version, space-separated. Example: 6.10.0-generic #1 SMP PREEMPT.

  • machine - Example: x86_64.

  • boot_id - Operation-unique boot identifier. Example: 5e0a3f24-7c2d-4f50-8e1d-9b3c8d7e6a4f.

Parameters:
started_at: datetime
runtime_path: str
verbose: bool
init_pid: int
hostname: str | EllipsisType = Ellipsis
kernel: str | EllipsisType = Ellipsis
machine: str | EllipsisType = Ellipsis
boot_id: str | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataSpawn(pid, command, args, shell, cwd, uid, gid, timeout, truncate_at, resources_limits=Ellipsis, cpu_affinity=Ellipsis, env=Ellipsis)[source]

Bases: ContreeModel

Process spawn parameters. env values for keys ending in.

TOKEN/SECRET/PASSWORD/API_KEY/CREDENTIALS/AUTHORIZATION are replaced with the literal string <MASKED> before emission.

Fields:

  • pid - PID assigned to the process. Example: 4242.

  • command - Example: /bin/sh.

  • args - Example: ["-c","echo hi"].

  • shell - If true, the command is wrapped in <shell> -c <command> (so the args / command may differ from the user’s input). Example: true.

  • cwd - Example: /work.

  • uid - Example: 1000.

  • gid - Example: 1000.

  • timeout - Per-process SIGKILL deadline in seconds. Example: 60.

  • truncate_at - Per-stream cap (bytes) above which stdout/stderr/stdin chunks stop being emitted and the stream’s truncated event fires on EOF. Example: 1048576.

  • cpu_affinity - Effective guest vCPU IDs available to this process tree.

  • env - Environment as passed to the process. Values for secret-suffix keys are replaced with <MASKED>. Example: {"PATH":"/usr/bin:/bin","DATABASE_PASSWORD":"<MASKED>"}.

Parameters:
pid: int
command: str
args: list[str]
shell: bool
cwd: str
uid: int
gid: int
timeout: int
truncate_at: int
resources_limits: ProcessResourcesLimits | EllipsisType = Ellipsis
cpu_affinity: list[int] | EllipsisType = Ellipsis
env: dict[str, str] | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataStream(value, encoding, truncated=Ellipsis)[source]

Bases: ContreeModel

Payload for stdin / stdout / stderr events. Encoding.

is ascii when every byte is printable plus \\n / \\r / \\t; base64 otherwise. Chunks are at most a few KB each — the natural read granularity from a pipe.

Fields:

  • value - Example: hello world.

  • encoding - Example: ascii.

  • truncated - Always false on per-chunk stream events. When a stream crosses its per-stream cap a separate truncated-type event is emitted on EOF carrying the cumulative emitted/dropped totals. Example: false.

Parameters:
value: str
encoding: Literal['ascii', 'base64']
truncated: bool | EllipsisType = Ellipsis
as_bytes()[source]

The payload decoded to raw bytes.

base64 values are decoded; ascii text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream.

Return type:

bytes

as_text()[source]

The payload decoded to text (UTF-8, errors replaced).

Return type:

str

classmethod from_bytes(value)[source]

Build a payload from raw bytes.

Printable ASCII (plus tab/newline/carriage return) is stored as ascii; anything else is base64-encoded - the same rule the server applies on its side.

Parameters:

value (bytes)

Return type:

EventDataStream

classmethod from_text(value)[source]

Build a payload from text (UTF-8 encoded unless ASCII).

Parameters:

value (str)

Return type:

EventDataStream

class contree_client.models.EventResources(user_time_us, sys_time_us, max_rss_kb, shared_memory, unshared_memory, swaps, minor_faults, major_faults, voluntary_ctx_switches, involuntary_ctx_switches, block_input_ops, block_output_ops, ipc_msgs_sent, ipc_msgs_received, signals_received)[source]

Bases: ContreeModel

Resource usage snapshot for the process. Time fields are.

in microseconds; memory in kilobytes (max_rss_kb) or platform-specific units (shared_memory / unshared_memory). Some kernels populate fewer fields than others; expect zeroes for unsupported counters.

Parameters:
  • user_time_us (int)

  • sys_time_us (int)

  • max_rss_kb (int)

  • shared_memory (int)

  • unshared_memory (int)

  • swaps (int)

  • minor_faults (int)

  • major_faults (int)

  • voluntary_ctx_switches (int)

  • involuntary_ctx_switches (int)

  • block_input_ops (int)

  • block_output_ops (int)

  • ipc_msgs_sent (int)

  • ipc_msgs_received (int)

  • signals_received (int)

user_time_us: int
sys_time_us: int
max_rss_kb: int
shared_memory: int
unshared_memory: int
swaps: int
minor_faults: int
major_faults: int
voluntary_ctx_switches: int
involuntary_ctx_switches: int
block_input_ops: int
block_output_ops: int
ipc_msgs_sent: int
ipc_msgs_received: int
signals_received: int
class contree_client.models.EventDataExit(pid, code, signal, timed_out, duration_ms, resources, oom_killed=Ellipsis, core_dump=Ellipsis)[source]

Bases: ContreeModel

Process lifecycle close-out. Carries the exit code OR the.

kill signal (signal = -1 means normal exit), the timed_out flag (true only when the process’s per-process timeout fired — distinguishes from an external signal/kill), wall-clock duration, and a snapshot of resource usage.

Fields:

  • pid - PID of the process that just exited. Example: 4242.

  • code - Exit code (0..255) if the process exited normally; -1 if killed by signal. Example: 0.

  • signal - Signal number if killed by signal; -1 if normal exit. Example: -1.

  • timed_out - True only if the process’s own timeout fired the kill. An externally-driven kill (signal / kill / cancel) leaves timed_out=false. Example: false.

  • duration_ms - Wall-clock time from spawn to exit. Example: 1234.

  • oom_killed - An OOM kill was observed in this process tree. Missing in older events. Default: False.

  • core_dump - True when the terminating signal produced a core dump. Absent in events recorded before the field was added — treat missing as false. Example: false.

Parameters:
pid: int
code: int
signal: int
timed_out: bool
duration_ms: int
resources: EventResources
oom_killed: bool | EllipsisType = Ellipsis
core_dump: bool | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataTruncated(stream, bytes_emitted, bytes_dropped)[source]

Bases: ContreeModel

Per-stream summary emitted once on stream EOF when the.

stream’s truncate_at cap was crossed during its lifetime. Carries the final cumulative emitted/dropped totals (not partial numbers at cap-hit time). Absent if the stream never crossed the cap.

Fields:

  • stream - Example: stdout.

  • bytes_emitted - Bytes that were delivered before the cap kicked in. Example: 1048576.

  • bytes_dropped - Bytes consumed from the producer but suppressed by the cap. Example: 4096.

Parameters:
  • stream (Literal['stdin', 'stdout', 'stderr'])

  • bytes_emitted (int)

  • bytes_dropped (int)

stream: Literal['stdin', 'stdout', 'stderr']
bytes_emitted: int
bytes_dropped: int
class contree_client.models.EventDataSizeCap(limit_bytes, file_size)[source]

Bases: ContreeModel

Emitted at most once per operation when the cumulative.

event-log size approached its budget. After this marker, further stream events (stdin / stdout / stderr) are dropped; service events continue so the lifecycle stays observable.

Fields:

  • limit_bytes - Size budget at which dropping kicked in. Example: 104857600.

  • file_size - Approximate cumulative event-log size at cap-hit. Example: 104800000.

Parameters:
  • limit_bytes (int)

  • file_size (int)

limit_bytes: int
file_size: int
class contree_client.models.NetworkInterface(name: 'str', rx_bytes: 'int', rx_packets: 'int', rx_errs: 'int', rx_drop: 'int', tx_bytes: 'int', tx_packets: 'int', tx_errs: 'int', tx_drop: 'int')[source]

Bases: ContreeModel

Fields:

  • name - Example: eth0.

Parameters:
name: str
rx_bytes: int
rx_packets: int
rx_errs: int
rx_drop: int
tx_bytes: int
tx_packets: int
tx_errs: int
tx_drop: int
class contree_client.models.EventDataNetworkConfigured(ip4=Ellipsis, ip4_gw=Ellipsis, ip6=Ellipsis, ip6_gw=Ellipsis, gw_mac=Ellipsis, nameserver=Ellipsis)[source]

Bases: ContreeModel

Subset of network params that were applied — empty keys.

are omitted, so the object only carries what was requested.

Fields:

  • ip4 - Example: 10.0.0.5/24.

  • ip4_gw - Example: 10.0.0.1.

  • ip6 - Example: fc10:c0::33/64.

  • ip6_gw - Example: fc10:c0::1.

  • gw_mac - Gateway MAC address. Example: ee:d0:a7:48:b5:98.

  • nameserver - Example: 8.8.8.8.

Parameters:
ip4: str | EllipsisType = Ellipsis
ip4_gw: str | EllipsisType = Ellipsis
ip6: str | EllipsisType = Ellipsis
ip6_gw: str | EllipsisType = Ellipsis
gw_mac: str | EllipsisType = Ellipsis
nameserver: str | EllipsisType = Ellipsis
class contree_client.models.EventDataNetwork(interfaces, configured=Ellipsis, error=Ellipsis)[source]

Bases: ContreeModel

Per-interface counters plus the configured network state.

Emitted once at the end of the network setup phase, so the counters represent the initial baseline. Absent entirely for network-less operations.

Fields:

  • configured - Subset of network params that were applied — empty keys are omitted, so the object only carries what was requested.

  • error - Set if the per-interface counter read failed; interfaces then holds an empty list. Best-effort — failure does not block shutdown.

Parameters:
interfaces: list[NetworkInterface]
configured: EventDataNetworkConfigured | EllipsisType = Ellipsis
error: str | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataShutdown(stopped_at, reason)[source]

Bases: ContreeModel

Stream-terminating marker emitted right before the operation.

winds down. Distinct from the network event so consumers can recognize a clean shutdown without parsing payload- specific data.

Fields:

  • stopped_at - Example: 2026-06-08T20:01:34.567890123Z.

  • reason - Short categorical reason for the shutdown: * job_complete — process exited normally; * timeout — the operation timeout fired; * spawn_failed — the process couldn’t be started; * signal — terminated by an external signal. Additional categories may be added.

Parameters:
  • stopped_at (datetime)

  • reason (Literal['job_complete', 'timeout', 'spawn_failed', 'signal'])

stopped_at: datetime
reason: Literal['job_complete', 'timeout', 'spawn_failed', 'signal']
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.EventDataCompletion(status, duration_ms, result_image_uuid=Ellipsis, error=Ellipsis, image_size_bytes=Ellipsis, consumed_cpu=Ellipsis, consumed_memory=Ellipsis)[source]

Bases: ContreeModel

Terminal system-event payload, emitted once when the.

operation reaches one of SUCCESS, FAILED, CANCELLED. Carries the operation outcome and rollup counters for the log + image artifacts. Always the last event in the log; the event itself has no spid (operation-scoped, not process-scoped).

Fields:

  • status - Terminal operation status.

  • duration_ms - Wall-clock duration of the handler in milliseconds. Example: 4327.

  • result_image_uuid - UUID of the result image the operation produced. Present on every SUCCESS that persists an image — for runs that wrote no new layer, this is the image UUID the operation was spawned from (per the spec). Distinct from the spec uuid only when persist produced a new image. null for disposable runs (no image was persisted at all) and for FAILED / CANCELLED outcomes. Example: 019eef27-7ecb-7771-8184-aaf5fa596ce2.

  • error - Short human-readable error message when status is FAILED or CANCELLED. null on success. Example: spawn failed: exec /run/entrypoint: no such file.

  • image_size_bytes - Size of the result image’s runtime layer in bytes. 0 for failed/cancelled operations and for disposables (no image persisted). Example: 134217728.

  • consumed_cpu - Total CPU time consumed by the operation, in seconds; null when unmeasured.

  • consumed_memory - Peak resident memory used by the operation’s execution environment, in KiB; null when unmeasured.

Parameters:
status: OperationStatus
duration_ms: int
result_image_uuid: str | None | EllipsisType = Ellipsis
error: str | None | EllipsisType = Ellipsis
image_size_bytes: int | EllipsisType = Ellipsis
consumed_cpu: float | None | EllipsisType = Ellipsis
consumed_memory: int | None | EllipsisType = Ellipsis
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

class contree_client.models.ListNetworkPolicyTagsResponse(tags: 'list[NetworkPolicyTag]')[source]

Bases: ContreeModel

Parameters:

tags (list[NetworkPolicyTag])

tags: list[NetworkPolicyTag]
classmethod parse_fields(data)[source]
Parameters:

data (dict[str, Any])

Return type:

dict[str, Any]

contree_client.models.parse_event_data(event_type, data)[source]

Decode a per-type event payload.

Unknown event types and payloads that do not match the documented schema - a non-mapping body included - are returned as-is instead of failing the stream.

Parameters:
Return type:

EventDataInit | EventDataSpawn | EventDataStream | EventDataExit | EventDataTruncated | EventDataSizeCap | EventDataNetwork | EventDataShutdown | EventDataInspect | EventDataFileUpload | EventDataCompletion | Any

contree_client.models.decode_chunk(data)[source]

Decode a stdout/stderr event payload to raw bytes.

Typed payloads delegate to EventDataStream.as_bytes(); the raw dict a lenient event parse may leave behind is decoded the same way, and anything else becomes empty bytes instead of failing a live stream.

Parameters:

data (object)

Return type:

bytes

contree_client.models.decode_stream(stream)[source]

Decode a StreamRepr payload (model or raw dict) to a string.

Parameters:

stream (StreamRepr | dict[str, Any] | None)

Return type:

str

contree_client.exceptions

Public exceptions raised by the Contree API client.

exception contree_client.exceptions.ContreeError[source]

Bases: Exception

Base class for normalized API client errors.

exception contree_client.exceptions.APIConnectionError(message, *, timed_out=False)[source]

Bases: ContreeError

A connection failed or a response body was interrupted.

timed_out identifies a timeout without exposing a backend type.

Parameters:
Return type:

None

exception contree_client.exceptions.APIStatusError(status, error, *, traceback=None, retry_after=None)[source]

Bases: ContreeError

A request or stream received HTTP status 400 or greater.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.BadRequestError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 400 Bad Request.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.AuthenticationError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 401 Unauthorized.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.PermissionDeniedError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 403 Forbidden.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.NotFoundError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 404 Not Found.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.ConflictError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 409 Conflict.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.GoneError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 410 Gone.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.UnprocessableEntityError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 422 Unprocessable Entity.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.TooEarlyError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 425 Too Early.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.RateLimitError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned HTTP 429 Too Many Requests.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

exception contree_client.exceptions.ServerError(status, error, *, traceback=None, retry_after=None)[source]

Bases: APIStatusError

The API returned an HTTP status of 500 or greater.

Parameters:
  • status (int)

  • error (Any)

  • traceback (list[str] | None)

  • retry_after (int | None)

Return type:

None

contree_client.operations

Request builders and response parsers for the Contree API.

Generated by codegen from the OpenAPI spec - do not edit.

contree_client.operations.build_list_network_policies(*, search=None, limit=None, offset=None)[source]

Build the request for GET /network/policies.

Parameters:
  • search (str | None)

  • limit (int | None)

  • offset (int | None)

Return type:

RequestSpec

contree_client.operations.parse_list_network_policies(response)[source]

Parse the response of GET /network/policies.

Parameters:

response (ResponseData)

Return type:

NetworkPolicyListResponse

contree_client.operations.build_create_network_policy(cidrs)[source]

Build the request for POST /network/policies.

Parameters:

cidrs (list[NetworkPolicyCIDRRule])

Return type:

RequestSpec

contree_client.operations.parse_create_network_policy(response)[source]

Parse the response of POST /network/policies.

Parameters:

response (ResponseData)

Return type:

NetworkPolicy

contree_client.operations.build_get_network_policy(uuid)[source]

Build the request for GET /network/policies/{uuid}.

Parameters:

uuid (str)

Return type:

RequestSpec

contree_client.operations.parse_get_network_policy(response)[source]

Parse the response of GET /network/policies/{uuid}.

Parameters:

response (ResponseData)

Return type:

NetworkPolicy

contree_client.operations.build_delete_network_policy(uuid)[source]

Build the request for DELETE /network/policies/{uuid}.

Parameters:

uuid (str)

Return type:

RequestSpec

contree_client.operations.parse_delete_network_policy(response)[source]

Parse the response of DELETE /network/policies/{uuid}.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_list_network_policy_tags(*, limit=None, offset=None)[source]

Build the request for GET /network/tags.

Parameters:
  • limit (int | None)

  • offset (int | None)

Return type:

RequestSpec

contree_client.operations.parse_list_network_policy_tags(response)[source]

Parse the response of GET /network/tags.

Parameters:

response (ResponseData)

Return type:

ListNetworkPolicyTagsResponse

contree_client.operations.build_get_network_policy_tag(tag)[source]

Build the request for GET /network/tags/{tag}.

Parameters:

tag (str)

Return type:

RequestSpec

contree_client.operations.parse_get_network_policy_tag(response)[source]

Parse the response of GET /network/tags/{tag}.

Parameters:

response (ResponseData)

Return type:

NetworkPolicyTag

contree_client.operations.build_set_network_policy_tag(tag, uuid)[source]

Build the request for PUT /network/tags/{tag}.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_set_network_policy_tag(response)[source]

Parse the response of PUT /network/tags/{tag}.

Parameters:

response (ResponseData)

Return type:

NetworkPolicyTag

contree_client.operations.build_delete_network_policy_tag(tag)[source]

Build the request for DELETE /network/tags/{tag}.

Parameters:

tag (str)

Return type:

RequestSpec

contree_client.operations.parse_delete_network_policy_tag(response)[source]

Parse the response of DELETE /network/tags/{tag}.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_list_images(*, limit=None, offset=None, tagged=False, tag=None, uuid=None, since=None, until=None)[source]

Build the request for GET /images.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_list_images(response)[source]

Parse the response of GET /images.

Parameters:

response (ResponseData)

Return type:

ImageListResponse

contree_client.operations.build_delete_image_tag(image_uuid, *, tag=None)[source]

Build the request for DELETE /images/{imageUUID}/tag.

Parameters:
  • image_uuid (str)

  • tag (str | None)

Return type:

RequestSpec

contree_client.operations.parse_delete_image_tag(response)[source]

Parse the response of DELETE /images/{imageUUID}/tag.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_update_image_tag(image_uuid, tag)[source]

Build the request for PATCH /images/{imageUUID}/tag.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_update_image_tag(response)[source]

Parse the response of PATCH /images/{imageUUID}/tag.

Parameters:

response (ResponseData)

Return type:

Image

contree_client.operations.build_import_image(registry, *, tag=Ellipsis, timeout=Ellipsis)[source]

Build the request for POST /images/import.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_import_image(response)[source]

Parse the response of POST /images/import.

Parameters:

response (ResponseData)

Return type:

str

contree_client.operations.build_list_files(*, limit=None, offset=None, since=None, until=None)[source]

Build the request for GET /files.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_list_files(response)[source]

Parse the response of GET /files.

Parameters:

response (ResponseData)

Return type:

FilesListResponse

contree_client.operations.build_upload_file(content)[source]

Build the request for POST /files.

Parameters:

content (bytes | IO[bytes])

Return type:

RequestSpec

contree_client.operations.parse_upload_file(response)[source]

Parse the response of POST /files.

Parameters:

response (ResponseData)

Return type:

FileResponse

contree_client.operations.build_get_file(sha256)[source]

Build the request for GET /files/{sha256}.

Parameters:

sha256 (str)

Return type:

RequestSpec

contree_client.operations.parse_get_file(response)[source]

Parse the response of GET /files/{sha256}.

Parameters:

response (ResponseData)

Return type:

File

contree_client.operations.build_check_file_exists(sha256)[source]

Build the request for HEAD /files/{sha256}.

Parameters:

sha256 (str)

Return type:

RequestSpec

contree_client.operations.parse_check_file_exists(response)[source]

Parse the response of HEAD /files/{sha256}.

Parameters:

response (ResponseData)

Return type:

bool

contree_client.operations.build_spawn_instance(command, image, *, disposable=Ellipsis, hostname=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, preserve_env=Ellipsis, preserve_cwd=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, resources_limits=Ellipsis, networking=Ellipsis, stdin=Ellipsis, timeout=Ellipsis, truncate_output_at=Ellipsis, files=Ellipsis)[source]

Build the request for POST /instances.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_spawn_instance(response)[source]

Parse the response of POST /instances.

Parameters:

response (ResponseData)

Return type:

InstanceSpawnResponse

contree_client.operations.build_list_operations(*, limit=None, offset=None, status=None, kind=None, since=None, until=None)[source]

Build the request for GET /operations.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_list_operations(response)[source]

Parse the response of GET /operations.

Parameters:

response (ResponseData)

Return type:

list[OperationSummary]

contree_client.operations.build_get_operation_status(operation_id, *, inflight=False)[source]

Build the request for GET /operations/{operationId}.

Parameters:
  • operation_id (str)

  • inflight (bool)

Return type:

RequestSpec

contree_client.operations.parse_get_operation_status(response)[source]

Parse the response of GET /operations/{operationId}.

Parameters:

response (ResponseData)

Return type:

OperationResponse

contree_client.operations.build_cancel_operation(operation_id)[source]

Build the request for DELETE /operations/{operationId}.

Parameters:

operation_id (str)

Return type:

RequestSpec

contree_client.operations.parse_cancel_operation(response)[source]

Parse the response of DELETE /operations/{operationId}.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_iter_operation_events(operation_id, *, follow=False, spid=None, since=None, last_event_id=None)[source]

Build the request for GET /operations/{operationId}/events.

Parameters:
  • operation_id (str)

  • follow (bool)

  • spid (int | None)

  • since (int | None)

  • last_event_id (int | None)

Return type:

RequestSpec

contree_client.operations.build_operation_subprocess_create(operation_id, command, *, resources_limits=Ellipsis, args=Ellipsis, shell=Ellipsis, env=Ellipsis, cwd=Ellipsis, uid=Ellipsis, gid=Ellipsis, stdin=Ellipsis, truncate_output_at=Ellipsis)[source]

Build the request for POST /operations/{operationId}/subprocesses.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_operation_subprocess_create(response)[source]

Parse the response of POST /operations/{operationId}/subprocesses.

Parameters:

response (ResponseData)

Return type:

int

contree_client.operations.build_operation_subprocess(operation_id, spid)[source]

Build the request for GET /operations/{operationId}/subprocesses/{spid}.

Parameters:
  • operation_id (str)

  • spid (int)

Return type:

RequestSpec

contree_client.operations.parse_operation_subprocess(response)[source]

Parse the response of GET /operations/{operationId}/subprocesses/{spid}.

Parameters:

response (ResponseData)

Return type:

InstanceResult

contree_client.operations.build_operation_subprocess_kill(operation_id, spid, *, signal=None)[source]

Build the request for DELETE /operations/{operationId}/subprocesses/{spid}.

Parameters:
  • operation_id (str)

  • spid (int)

  • signal (str | None)

Return type:

RequestSpec

contree_client.operations.parse_operation_subprocess_kill(response)[source]

Parse the response of DELETE /operations/{operationId}/subprocesses/{spid}.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_operation_subprocess_stdin(operation_id, spid, value, *, encoding=Ellipsis, close=Ellipsis)[source]

Build the request for POST /operations/{operationId}/subprocesses/{spid}/stdin.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_operation_subprocess_stdin(response)[source]

Parse the response of POST /operations/{operationId}/subprocesses/{spid}/stdin.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_apply_instance_file(operation_uuid, file_uuid, path, *, unpack=Ellipsis, replace=Ellipsis, merge=Ellipsis)[source]

Build the request for POST /operations/{operation_uuid}/files.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_apply_instance_file(response)[source]

Parse the response of POST /operations/{operation_uuid}/files.

Parameters:

response (ResponseData)

Return type:

None

contree_client.operations.build_inspect_instance_download(operation_uuid, path)[source]

Build the request for GET /operations/{operation_uuid}/inspect/download.

Parameters:
  • operation_uuid (str)

  • path (str)

Return type:

RequestSpec

contree_client.operations.parse_inspect_instance_download(response)[source]

Parse the response of GET /operations/{operation_uuid}/inspect/download.

Parameters:

response (ResponseData)

Return type:

bytes

contree_client.operations.build_check_instance_file(operation_uuid, path)[source]

Build the request for HEAD /operations/{operation_uuid}/inspect/download.

Parameters:
  • operation_uuid (str)

  • path (str)

Return type:

RequestSpec

contree_client.operations.parse_check_instance_file(response)[source]

Parse the response of HEAD /operations/{operation_uuid}/inspect/download.

Parameters:

response (ResponseData)

Return type:

bool

contree_client.operations.build_inspect_instance_list(operation_uuid, path)[source]

Build the request for GET /operations/{operation_uuid}/inspect/list.

Parameters:
  • operation_uuid (str)

  • path (str)

Return type:

RequestSpec

contree_client.operations.parse_inspect_instance_list(response)[source]

Parse the response of GET /operations/{operation_uuid}/inspect/list.

Parameters:

response (ResponseData)

Return type:

DirectoryList

contree_client.operations.build_inspect_instance_archive(operation_uuid, path)[source]

Build the request for GET /operations/{operation_uuid}/inspect/archive.

Parameters:
  • operation_uuid (str)

  • path (str)

Return type:

RequestSpec

contree_client.operations.build_check_instance_archive(operation_uuid, path)[source]

Build the request for HEAD /operations/{operation_uuid}/inspect/archive.

Parameters:
  • operation_uuid (str)

  • path (str)

Return type:

RequestSpec

contree_client.operations.parse_check_instance_archive(response)[source]

Parse the response of HEAD /operations/{operation_uuid}/inspect/archive.

Parameters:

response (ResponseData)

Return type:

bool

contree_client.operations.build_inspect_find_image_by_tag(tag)[source]

Build the request for GET /inspect/.

Parameters:

tag (str)

Return type:

RequestSpec

contree_client.operations.parse_inspect_find_image_by_tag(response)[source]

Parse the response of GET /inspect/.

Parameters:

response (ResponseData)

Return type:

str

contree_client.operations.build_inspect_image(image_uuid)[source]

Build the request for GET /inspect/{image_uuid}/.

Parameters:

image_uuid (str)

Return type:

RequestSpec

contree_client.operations.parse_inspect_image(response)[source]

Parse the response of GET /inspect/{image_uuid}/.

Parameters:

response (ResponseData)

Return type:

Image

contree_client.operations.build_inspect_image_download(image_uuid, path)[source]

Build the request for GET /inspect/{image_uuid}/download.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_inspect_image_download(response)[source]

Parse the response of GET /inspect/{image_uuid}/download.

Parameters:

response (ResponseData)

Return type:

bytes

contree_client.operations.build_check_image_file(image_uuid, path)[source]

Build the request for HEAD /inspect/{image_uuid}/download.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_check_image_file(response)[source]

Parse the response of HEAD /inspect/{image_uuid}/download.

Parameters:

response (ResponseData)

Return type:

bool

contree_client.operations.build_inspect_image_archive(image_uuid, path)[source]

Build the request for GET /inspect/{image_uuid}/archive.

Parameters:
Return type:

RequestSpec

contree_client.operations.build_check_image_archive(image_uuid, path)[source]

Build the request for HEAD /inspect/{image_uuid}/archive.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_check_image_archive(response)[source]

Parse the response of HEAD /inspect/{image_uuid}/archive.

Parameters:

response (ResponseData)

Return type:

bool

contree_client.operations.build_inspect_image_list(image_uuid, path)[source]

Build the request for GET /inspect/{image_uuid}/list.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_inspect_image_list(response)[source]

Parse the response of GET /inspect/{image_uuid}/list.

Parameters:

response (ResponseData)

Return type:

DirectoryList

contree_client.operations.build_inspect_instance_grep(operation_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Build the request for GET /operations/{operation_uuid}/inspect/grep.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_inspect_instance_grep(response)[source]

Parse the response of GET /operations/{operation_uuid}/inspect/grep.

Parameters:

response (ResponseData)

Return type:

GrepResult

contree_client.operations.build_inspect_image_grep(image_uuid, pattern, *, path=None, glob=None, max_count=None, max_total=None, case=None, before=None, after=None)[source]

Build the request for GET /inspect/{image_uuid}/grep.

Parameters:
Return type:

RequestSpec

contree_client.operations.parse_inspect_image_grep(response)[source]

Parse the response of GET /inspect/{image_uuid}/grep.

Parameters:

response (ResponseData)

Return type:

GrepResult

contree_client.operations.build_whoami()[source]

Build the request for GET /whoami.

Return type:

RequestSpec

contree_client.operations.parse_whoami(response)[source]

Parse the response of GET /whoami.

Parameters:

response (ResponseData)

Return type:

WhoAmIResponse

contree_client.spec_info

The OpenAPI specification this package was generated from.

Generated by codegen from the OpenAPI spec - do not edit.

openapi: 3.0.0
info:
  title: Contree API
  description: |
    Contree is a container management system combining virtual machine isolation with container operational efficiency.
    Designed for security-sensitive workloads requiring hardware-enforced boundaries while maintaining
    container workflow compatibility.
  version: 1.0.0

servers:
  - url: '{baseUrl}/v1'
    description: |
      Nebius IAM-fronted endpoint (use `IAMBearerAuth` + `IAMProjectHeader`).
      Override `baseUrl` to point at a different deployment.
    variables:
      baseUrl:
        default: https://api.tokenfactory.nebius.com/sandboxes
        description: |
          Base URL of the contree service. Defaults to the public Nebius
          IAM-fronted endpoint; set to your self-hosted contree origin
          (e.g. `https://contree.example.com`) when running elsewhere.

tags:
  - name: images
    description: Operations related to container images
  - name: files
    description: Operations related to file uploads
  - name: instances
    description: Operations related to container instances
  - name: inspect
    description: Operations related to inspecting container images
  - name: operations
    description: Operations related to long-running operations
  - name: auth
    description: Authentication and token introspection
  - name: network
    description: Network policies

paths:
  /network/policies:
    post:
      summary: Create a network policy
      description: |
        Creates a policy with immutable rules in the caller's namespace.
        Requires `network_policy` permission.

        **Rules**

        - Each rule allows a CIDR for the selected protocol and ports. An empty or
          omitted port list allows all ports.
        - ICMP is allowed to every listed CIDR, regardless of protocol or ports.
        - An empty rules array (`cidrs: []`) blocks all IP egress, including ICMP
          and traffic to the host.
        - ARP is blocked for all policies.

        **Limits**

        The same limit of 16384 units applies before and after normalization.
        Sum the number of ports across all rules, counting an empty or omitted
        port list (all ports) as 1. The limit covers the entire policy, across
        all IP versions and protocols.
        Duplicates count toward the limit before normalization. Exceeding the
        limit returns 400, even if normalization would remove redundant rules or ports.

        **Normalization**

        Before storage, duplicate rules and ports are removed, CIDRs are merged
        per protocol and port, and rules and ports are sorted. This preserves the
        allowed traffic. The response contains the normalized rules.

        **Policy identity**

        Equivalent normalized policies in the same namespace reuse the same UUID,
        including concurrent requests. The UUID is UUIDv5 derived from the namespace
        and the normalized policy hash. Resubmitting a deleted policy restores it
        without restoring its tags. To change the rules, create a new policy.
      operationId: createNetworkPolicy
      tags:
        - network
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NetworkPolicyCreateRequest'
      responses:
        '201':
          description: Network policy created, reused, or restored
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NetworkPolicy'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

    get:
      summary: List network policies
      description: |
        Returns policies in your namespace and the shared namespace. Deleted policies are excluded.
        Reusing or restoring a policy does not change its creation time or listing position.
        Each entry contains the policy UUID, creation timestamp, accessible tags, and a summary
        with the number of IP rules. Tags are sorted by name. Your tag takes precedence over
        a shared tag with the same name; the overridden shared binding is omitted.
        Use `GET /network/policies/{uuid}` to retrieve the full rules.
        Requires `spawn` or `spawn_disposable` permission.

        Search:
        Supply `search` to find active policies in your namespace and the shared namespace
        that allow the destination. The input determines the search type; currently only IPv4
        and IPv6 addresses and CIDRs are supported. Domains and other unsupported inputs
        return 400. An omitted search parameter lists policies normally; an empty value
        returns 400.

        Use `[tcp://|udp://]address-or-cidr[:port]`. IPv6 addresses and CIDRs must be
        enclosed in brackets when specifying a port, with the prefix length inside
        the brackets. Examples: `192.0.2.1`, `192.0.2.0/24:443`,
        `tcp://192.0.2.0/24:443`, and `udp://[2001:db8::/64]:53`.
        This is search syntax, not a URL. CIDRs must use their network address;
        host bits, scoped IPv6 addresses, and ports outside 1–65535 return 400.

        A match must allow the requested protocol and port throughout the entire CIDR,
        not merely overlap it. An IP address is treated as a /32 or /128 CIDR.
        All-port rules match every requested port. If protocol or port is omitted,
        any single protocol/port combination covering the entire destination matches.
        Complementary subnets granting that same access are normalized into a covering
        rule. Permissions from different policies are never combined for search.
        Empty policies do not match. Filtering happens before pagination, and results
        retain the same order, summary, timestamp, and tags as the normal listing.
      operationId: listNetworkPolicies
      tags:
        - network
      parameters:
        - name: search
          in: query
          required: false
          description: IP or CIDR search, optionally qualified by TCP/UDP and a destination port.
          schema:
            type: string
            minLength: 1
            maxLength: 256
          examples:
            ip:
              value: '192.0.2.1'
            cidrAndPort:
              value: 'tcp://192.0.2.0/24:443'
            ipv6:
              value: 'udp://[2001:db8::/64]:53'
        - name: limit
          in: query
          required: false
          description: Maximum number of results to return. Invalid values raise 400 error.
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
        - name: offset
          in: query
          required: false
          description: Number of results to skip. Invalid values raise 400 error.
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Accessible active network policies
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NetworkPolicyListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /network/policies/{uuid}:
    get:
      summary: Get a network policy
      description: |
        Returns an accessible policy, including deleted policies.
        Returns 404 if the policy does not exist.
        Requires `spawn` or `spawn_disposable` permission.
      operationId: getNetworkPolicy
      tags:
        - network
      parameters:
        - name: uuid
          in: path
          required: true
          description: Network policy UUID
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      responses:
        '200':
          description: Network policy
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NetworkPolicy'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      summary: Remove a network policy
      description: |
        Removes a policy in your namespace. Requires `network_policy` permission.
        Returns 204 if the policy is removed or was already removed.
        Returns 404 if the policy does not exist in your namespace.
        Removes its tags and excludes it from listings. The policy remains accessible
        and usable by UUID, but cannot be assigned to tags.
      operationId: deleteNetworkPolicy
      tags:
        - network
      parameters:
        - name: uuid
          in: path
          required: true
          description: Network policy UUID
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      responses:
        '204':
          description: Network policy removed or already removed
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /network/tags:
    get:
      summary: List network policy tags
      description: |
        Returns your tags and shared tags, ordered by name. Your tag takes precedence
        when a shared tag has the same name. Requires `spawn` or `spawn_disposable` permission.
      operationId: listNetworkPolicyTags
      tags:
        - network
      parameters:
        - name: limit
          in: query
          required: false
          description: Maximum number of results to return. Invalid values raise 400 error.
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
        - name: offset
          in: query
          required: false
          description: Number of results to skip. Invalid values raise 400 error.
          schema:
            type: integer
            minimum: 0
            default: 0
      responses:
        '200':
          description: Accessible active network policy tag bindings
          content:
            application/json:
              schema:
                type: object
                required:
                  - tags
                properties:
                  tags:
                    type: array
                    items:
                      $ref: '#/components/schemas/NetworkPolicyTag'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /network/tags/{tag}:
    get:
      summary: Get a network policy tag
      description: |
        Redirects to the policy referenced by your tag, or the shared tag if you have no tag with that name.
        The redirect response includes the effective tag binding as JSON.
        Requires `spawn` or `spawn_disposable` permission. Returns 404 if the tag or its target
        policy does not exist or is removed.
      operationId: getNetworkPolicyTag
      tags:
        - network
      parameters:
        - name: tag
          in: path
          required: true
          description: Network policy tag name
          schema:
            type: string
      responses:
        '302':
          description: Redirect to the resolved policy, with the effective tag binding in the body
          headers:
            Location:
              description: URL of the resolved network policy
              schema:
                type: string
                example: /v1/network/policies/01900000-0000-7000-8000-000000000001
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NetworkPolicyTag'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      summary: Remove a network policy tag
      description: |
        Removes your tag, including when operations use its policy. Repeated deletion succeeds.
        If a shared tag has the same name, it becomes visible again.
        Requires `network_policy` permission.
      operationId: deleteNetworkPolicyTag
      tags:
        - network
      parameters:
        - name: tag
          in: path
          required: true
          description: Network policy tag name
          schema:
            type: string
      responses:
        '204':
          description: Network policy tag removed
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

    put:
      summary: Bind a tag to a network policy
      description: |
        Creates or replaces your tag's binding to an active policy in your namespace or the shared namespace.
        Repeating the same binding has no effect. Returns 404 if the target policy
        does not exist, is inaccessible, or is removed. The tag belongs to your namespace.
        Requires `network_policy` permission.
      operationId: setNetworkPolicyTag
      tags:
        - network
      parameters:
        - name: tag
          in: path
          required: true
          description: Network policy tag name
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [uuid]
              properties:
                uuid:
                  $ref: '#/components/schemas/UUIDSchema'
      responses:
        '200':
          description: Network policy tag binding
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NetworkPolicyTag'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /images:
    get:
      summary: List publicly available images
      description: |
        Returns a list of all publicly available container images.
      operationId: listImages
      tags:
        - images
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
          description: |
            Maximum number of images to return. Must be between 1 and 1000.
            Default is 100. Invalid values raise 400 error.
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            minimum: 0
            default: 0
          description: |
            Number of images to skip before starting to collect the result set.
            Default is 0. Invalid values raise 400 error.
        - name: tagged
          in: query
          required: false
          schema:
            type: string
            description: |
              If not `0` only images with tags will be listed. May be avoided or set to `0` to list all images.
              If no value is provided (like `?tagged`, it is considered as `1`.
          example: "1"
        - name: tag
          in: query
          required: false
          schema:
            type: string
          description: |
              A valid image tag prefix to filter images by this prefix. Only images with tags starting with. Implies `tagged` parameter.
          example: "ubuntu"
        - name: uuid
          in: query
          required: false
          schema:
            $ref: '#/components/schemas/UUIDSchema'
          description: Filter images by UUID
        - $ref: '#/components/parameters/SinceParameter'
        - $ref: '#/components/parameters/UntilParameter'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /images/{imageUUID}/tag:
    delete:
      summary: Remove tags from an image
      description: |
        Removes a tag (or all tags) from an image.

        When `tag` query parameter is provided, only that specific tag is removed.
        When omitted, all tags are removed from the image.

        If any public image has the same tag, tag will start tracking that public image again.

        In all other cases tag will be removed and the image will be accessible only by its UUID.
      operationId: deleteImageTag
      tags:
          - images
      parameters:
        - name: imageUUID
          in: path
          required: true
          description: The UUID of the image to untag
          schema:
              $ref: '#/components/schemas/UUIDSchema'
        - name: tag
          in: query
          required: false
          description: >
            The tag to remove. If omitted, all tags are removed from the image.
          schema:
            type: string
            example: busybox:latest
      responses:
          '204':
            description: Tags removed successfully
          '401':
            $ref: '#/components/responses/Unauthorized'
          '403':
            $ref: '#/components/responses/Forbidden'
          '404':
            $ref: '#/components/responses/NotFound'
    patch:
      summary: Add a tag to an image
      description: |
        Adds a tag to an image. Tags are unique per namespace; if the requested tag is already
        assigned to another image, it will be moved to this image.

        Assigning a tag that matches a public tag to a public image will freeze that tag
        to the current image - subsequent public updates to the tag will not affect it.
        To make the public tag track the latest public image again, remove your tag assignment.

        When a tag is removed from an image that resides in the public namespace, the API returns HTTP 200 OK.
        response body contains the tag that now points to the public image
        (i.e., the image that the tag is automatically re‑assigned to).

        In other words, un‑tagging a public image does not delete the tag; it simply moves the tag back to the public
        image and the caller receives that tag in the successful response.
      operationId: updateImageTag
      tags:
        - images
      parameters:
        - name: imageUUID
          in: path
          required: true
          description: The UUID of the image to update
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - tag
              properties:
                tag:
                  type: string
                  description: New tag for the image
                  example: busybox:latest
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Image'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /images/import:
    post:
      summary: Import a container image from a registry
      description: |
        Imports the OCI image filesystem content of from a specified registry.

        Important limitations and behavior:

        - Only the image root filesystem (files and directories) is imported. This is like to the output of
          `docker export` and does not preserve layers metadata.
        - Most image configuration and manifest data are ignored. Metadata such as `LABEL`,
          `ENTRYPOINT`, `CMD`, `WORKDIR`, `EXPOSE` and other image configuration directives
          will **NOT be imported or applied**.
        - `ENV` variables defined in the image **are imported** and automatically applied to the
          instance environment when `shell` is set to `true`. When `shell` is `false`, image
          environment variables are not inherited and must be passed explicitly via the `env` field.
        - The result is a flat rootfs snapshot with preserved environment variables.
        - If the specified tag already exists in the public images, the imported image will replace it.
          To avoid this, you can tag the existing image with a different tag for use it later.
          You also can use image UUIDs it is not changing for imported and existend image.
        - In case the remote image is unchanged and already imported, the operation will complete and the same UUID
          will be returned without re-importing the image.

        The request creates an import operation which runs asynchronously.
      operationId: importImage
      tags:
        - images
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ImageImportRequest'
      responses:
        '201':
          description: Created - The request has been accepted for processing
          headers:
            Location:
              schema:
                type: string
              description: URL to check the operation status
              example: /v1/operations/12345678-9abc-baba-deda-0123456789ab
          content:
            application/json:
              schema:
                type: object
                required:
                  - uuid
                properties:
                  uuid:
                    $ref: '#/components/schemas/UUIDSchema'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /files:
    post:
      summary: Upload a file to the server. the body must be a file content.
      description: Uploads a file to the server. The body must contain the file content.
      operationId: uploadFile
      tags:
        - files
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema:
              type: string
              format: binary
      responses:
        '201':
          description: Created - The file has been successfully uploaded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
    get:
      summary: List uploaded files for the current namespace
      description: Returns a paginated list of uploaded files for the current namespace.
      tags:
        - files
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            default: 100
            minimum: 1
            maximum: 1000
          description: Maximum number of files to return
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            default: 0
            minimum: 0
          description: Number of files to skip
        - name: since
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: Filter files created after this time
        - name: until
          in: query
          required: false
          schema:
            type: string
            format: date-time
          description: Filter files created before this time
      responses:
        '200':
          description: List of uploaded files
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilesListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /files/{sha256}:
    parameters:
      - name: sha256
        in: path
        required: true
        description: SHA256 hash of the file (64 hex characters)
        schema:
          type: string
          pattern: '^[0-9a-fA-F]{64}$'
    head:
      summary: Check if a file exists for the current namespace
      description: Returns 200 if the file is uploaded by the current namespace, otherwise 404.
      operationId: checkFileExists
      tags:
        - files
      responses:
        '200':
          description: OK - The file exists
        '401':
          description: Unauthorized - Invalid or missing authentication credentials
        '403':
          description: Forbidden - Token does not have sufficient permissions
        '404':
          description: Not Found - The file does not exist
    get:
      summary: Get file info by SHA256
      description: Returns file info (uuid, sha256, created_at, updated_at).
      tags:
        - files
      responses:
        '200':
          description: File info
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/File'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /instances:
    post:
      summary: Spawn a new container instance
      description: |
        Creates and runs a new execution instance with the specified configuration.
        Requires a valid `Authorization` header.

        Common request body rules:

          * The request body must contain at least `command` and `image` fields all other fields can be omitted.
          * If the `command` field is a shell expression, you must set `shell` field to `true`.
          * For specifying the shell binary, you can use `env` field to set `SHELL` variable.
          * When `shell` is `true`, environment variables defined in the image (via `ENV` directives) are
            automatically inherited. When `shell` is `false`, image environment variables are not inherited
            and must be passed explicitly via the `env` field.
      operationId: spawnInstance
      tags:
        - instances
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InstanceSpawnRequest'
      responses:
        '201':
          description: >
            Created - The instance has been successfully created and its execution has been queued.
            When operation created successfully, the response will contain `Location` header with URL to check the operation status.
            and the body will contain the parsed request body with additional `uuid` field.
          headers:
            Location:
              schema:
                type: string
              description: URL to check the operation status
              example: /v1/operations/12345678-9abc-baba-deda-0123456789ab
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InstanceSpawnResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /operations:
    get:
      summary: List operations
      description: Returns a list of running and completed operations
      operationId: listOperations
      tags:
        - operations
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 1000
            default: 100
          description: |
            Maximum number of operations to return. Must be between 1 and 1000.
            Default is 100. Invalid values raise 400 error.
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            minimum: 0
            default: 0
          description: |
            Number of operations to skip before starting to collect the result set.
            Default is 0. Invalid values raise 400 error.
        - name: status
          in: query
          required: false
          schema:
            type: string
            enum: [ PENDING, EXECUTING, SUCCESS, FAILED, CANCELLED, ASSIGNED ]
          description: Filter operations by their state
        - name: kind
          in: query
          required: false
          schema:
            type: string
            enum: [ image_import, instance ]
          description: Filter operations by their kind
        - $ref: '#/components/parameters/SinceParameter'
        - $ref: '#/components/parameters/UntilParameter'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/OperationSummary'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /operations/{operationId}:
    get:
      summary: Get an operation status
      description: |
        Returns the status of an operation.

        For an EXECUTING INSTANCE operation, pass `?inflight=1` to
        also synthesize the partial `result.stdout` / `result.stderr`
        from the live event log.  Off by default — each fetch with
        `inflight` triggers an extra subscribe RPC to the guest and
        drains its current events.gz, which is wasted work for
        clients that only poll for status transitions.
      operationId: getOperationStatus
      tags:
        - operations
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: inflight
          in: query
          required: false
          allowEmptyValue: true
          description: |
            HTTP-flag boolean.  Present without a value (`?inflight`)
            and `?inflight=1` both enable; `?inflight=0` and absence
            disable.  When enabled and the operation is EXECUTING
            INSTANCE, partial stdout/stderr is synthesized from the
            live event log and attached under `result`.
          schema:
            type: string
            enum: ["", "0", "1"]
            default: "0"
      responses:
        '200':
          description: OK
          headers:
            Retry-After:
              schema:
                type: integer
              description: Recommended time in seconds to wait before the next status check
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OperationResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

    delete:
      summary: Cancel an operation
      description: Cancels an operation
      operationId: cancelOperation
      tags:
        - operations
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the import operation to cancel
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      responses:
        '202':
          description: Accepted - The cancellation request has been accepted
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/Conflict'

  /operations/{operationId}/events:
    get:
      summary: Stream the operation event log via Server-Sent Events
      description: |
        Always returns `text/event-stream` (SSE) on success.  The body
        is a sequence of three kinds of lines (per RFC W3C SSE), each
        terminated by `\n\n`:

        ### Frame shapes

        **Normal event frame** — one `OperationEvent` JSON object in
        `data:`, dispatchable via `event:`:
        ```
        id: <integer event.id>
        event: <OperationEventType, e.g. stdout|stderr|spawn|exit>
        data: {"id": N, "ts": "...", "spid": ..., "type": "...", "data": {...}}
        ```
        `event:` always matches `data.type`.  See `OperationEvent` and
        `OperationEventType` for the per-type payload shape.  Native
        `EventSource` dispatches each frame to the matching
        `addEventListener("<type>", ...)` handler.

        **Server-side error frame** — surfaces handler exceptions to
        the connected client without tearing the TCP connection down
        mid-stream.  Sent right before the server closes the response:
        ```
        : stream ended with error, retry since last event id

        event: sse_error
        data: <one-line exception message>
        ```
        The leading SSE comment line lets pure-EventSource clients see
        the intent ("retry from Last-Event-Id"); the `sse_error` frame
        carries the error text for logging.  Clients should treat this
        as a non-clean close and reconnect with the standard SSE
        `Last-Event-Id` semantics (see Resuming).

        **Keepalive comment** — periodic `: keepalive\n\n` lines
        emitted while the stream is idle.  They keep upstream
        `proxy_read_timeout` / TCP idle timers fresh and have no
        application meaning.  Spec-compliant; EventSource and any SSE
        parser must ignore comment lines (those beginning with `:`).

        ### `follow` semantics

        The `follow` parameter controls only whether the stream stays
        open after the last currently-known event:

          * `follow=0` (default) — the server emits everything
            currently available and closes the connection.
          * `follow=1` — same start; if the operation is still
            running the server keeps the connection open and forwards
            new events as they appear.  For terminal operations
            `follow=1` is a no-op: there's nothing more to subscribe
            to, so the connection closes after the last event just
            like `follow=0`.

        Optional filters:

          * `?spid=N` — only events whose `spid` (Spawned Process ID,
            the routing identity in `OperationEvent`) matches.
          * `?since=N` — only events with `id > N`.

        `follow=1` requires `SPAWN` or `SPAWN_DISPOSABLE` on top of
        the baseline `LIST` — a long-lived subscription reserves
        per-operation server state.  `follow=0` is read-only and
        stays under `LIST`.

        ### Resuming after a drop

        Every normal frame carries `id:` — the canonical event id.
        On reconnect send the last successfully received id in the
        standard `Last-Event-Id` request header (or `?since=N` on
        manual GETs); the server resumes from that point.

        ### Error handling

        | Status | Meaning                                          | Client action                                |
        |--------|--------------------------------------------------|----------------------------------------------|
        | 200    | Stream open                                      | Read frames; reconnect with Last-Event-Id if the stream closes before reaching a terminal event |
        | 400    | Malformed query/header (non-integer param)       | Fix request                                  |
        | 401    | Missing/invalid auth                             | Refresh credentials                          |
        | 403    | Auth lacks LIST (or SPAWN for `follow=1`)        | Use a token with the right scope             |
        | 404    | Operation not in this namespace                  | Wrong UUID                                   |
        | 410    | Stream is over but the terminal artifact isn't ready yet | Retry after `Retry-After`                    |
        | 425    | Not yet ready (operation is still being prepared)| Retry after `Retry-After`                    |
        | 502    | Upstream returned an error opening the stream    | Retry; if persistent, escalate               |
        | 504    | Upstream took too long to respond                | Retry                                        |

        A `200` followed by an `event: sse_error` frame and immediate
        close is the in-band equivalent of "the stream broke after we
        already committed to a 200" — handle it the same way as 410:
        wait briefly, reconnect with `Last-Event-Id`.

        See `OperationEvent` for the per-event shape.
      operationId: getOperationEvents
      tags:
        - operations
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: follow
          in: query
          required: false
          allowEmptyValue: true
          description: |
            HTTP-flag boolean.  Present without a value (`?follow`)
            and `?follow=1` both enable; `?follow=0` and absence
            disable.  When enabled, the SSE stream stays open after
            the currently-known events have been sent — for a
            running operation new events are forwarded as they
            appear; for a terminal operation it has no effect.
          schema:
            type: string
            enum: ["", "0", "1"]
            default: "0"
        - name: spid
          in: query
          required: false
          description: |
            Only emit events whose `spid` field matches.  Filter is
            applied server-side regardless of whether the operation is
            still running or already terminal.
          schema:
            type: integer
            minimum: 0
        - name: since
          in: query
          required: false
          description: |
            Only emit events with `id > since` (event IDs are
            monotonically increasing).  Overridden by the
            `Last-Event-Id` header when present.
          schema:
            type: integer
            minimum: 0
        - name: Last-Event-Id
          in: header
          required: false
          description: |
            Standard SSE resume header sent automatically by
            `EventSource` on reconnect.  Treated as `?since=N`;
            takes precedence over the query param.
          schema:
            type: integer
            minimum: 0
      responses:
        '200':
          description: |
            OK — `text/event-stream` body.  Normal events,
            `: keepalive` comments, and a terminal `event: sse_error`
            frame may all appear; see endpoint description.  With
            `follow=0` (or any terminal operation) the response ends
            after the last available event; with `follow=1` on a
            still-running operation the connection stays open until the
            client disconnects or the operation reaches a terminal
            state.
          headers:
            Content-Type:
              schema:
                type: string
                enum: [text/event-stream]
            Cache-Control:
              schema:
                type: string
                enum: [no-cache]
          content:
            text/event-stream:
              schema:
                $ref: '#/components/schemas/OperationEventStream'
              examples:
                ordered_lifecycle:
                  summary: "SSE frames for a tiny successful run"
                  value: |
                    : keepalive

                    id: 0
                    event: init
                    data: {"id":0,"ts":"2026-06-08T20:00:00Z","spid":0,"type":"init","data":{"init_pid":1}}

                    id: 1
                    event: spawn
                    data: {"id":1,"ts":"2026-06-08T20:00:00.10Z","spid":1,"type":"spawn","data":{"pid":4242}}

                    id: 2
                    event: exit
                    data: {"id":2,"ts":"2026-06-08T20:00:00.12Z","spid":1,"type":"exit","data":{"pid":4242,"code":0}}
                broken_mid_stream:
                  summary: |
                    Stream that committed to 200 but then hit a
                    server-side error.  Reconnect with `Last-Event-Id: 1`.
                  value: |
                    id: 0
                    event: init
                    data: {"id":0,"ts":"2026-06-08T20:00:00Z","spid":0,"type":"init","data":{"init_pid":1}}

                    id: 1
                    event: spawn
                    data: {"id":1,"ts":"2026-06-08T20:00:00.10Z","spid":1,"type":"spawn","data":{"pid":4242}}

                    : stream ended with error, retry since last event id

                    event: sse_error
                    data: upstream event source closed unexpectedly
        '400':
          description: |
            Bad request — a query parameter failed to parse as an
            integer.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '410':
          description: |
            Gone — the live stream is finished but the terminal
            artifact isn't durable yet.  Reconnect after the
            `Retry-After` delay; the subsequent request will deliver
            the full event log.
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds to wait before retrying.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                finalizing:
                  summary: "Live stream over, terminal artifact still being committed"
                  value:
                    status: 410
                    error: "operation finished; events not yet durable"
        '425':
          description: |
            Too Early (RFC 8470) — the operation isn't streamable yet.
            It may still be queued, or just starting up.  Retry after
            `Retry-After`.
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds to wait before retrying.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                pre_attach:
                  summary: "Operation accepted but events not yet flowing"
                  value:
                    status: 425
                    error: "events not yet available for operation ..."
                pending_budget_exhausted:
                  summary: "Operation still queued past the server's wait budget"
                  value:
                    status: 425
                    error: "Events not yet available; retry shortly."
        '502':
          description: |
            Bad Gateway — an upstream component returned an error
            opening the event source.  Retry after a short delay.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '504':
          description: |
            Gateway Timeout — an upstream component didn't respond
            within the server-side deadline.  Idempotent on this
            endpoint — retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /operations/{operationId}/subprocesses:
    post:
      summary: Spawn an additional subprocess inside a running instance
      description: |
        Starts a new process inside the VM that already hosts the named
        operation.  Distinct from `POST /instances`, which spins up a
        VM: this endpoint requires a running operation (EXECUTING or
        ASSIGNED) and reuses the existing VM.

        The body is an `ExecSpec` — process-execution fields only.
        VM-level concerns (`image`, `hostname`,
        `files`, `timeout`, `disposable`, `preserve_env`) are not
        accepted here; they were set when the parent operation was
        created.

        `resources_limits.cpu` and `resources_limits.memory_mib` use the
        same names and units as operation creation. Each omitted or null
        subprocess limit inherits the corresponding operation limit.
        Values above the operation limit return 400. Limits apply at
        launch: memory_mib sets RLIMIT_AS for each process and memory.max
        for the entire process tree. They cannot be changed through this
        API. Guest root can modify limits; these limits do not
        provide security isolation between processes in one VM.

        The required permission follows the parent instance:
        `SPAWN_DISPOSABLE` when it was spawned with `disposable=true`,
        `SPAWN` otherwise.

        On success the worker assigns a fresh `spid` (≥2; `spid=1` is
        the main process spawned from `metadata`) and the response
        carries it in the body plus a `Location` header pointing at
        `GET /operations/{operationId}/subprocesses/{spid}` — the
        subprocess result reconstructed from its events.
      operationId: operationSubprocessCreate
      tags:
        - operation
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExecSpec'
      responses:
        '201':
          description: |
            Created — subprocess started.  `Location` references the
            new subprocess result.
          headers:
            Location:
              schema:
                type: string
              description: URL of the new subprocess result.
              example: /v1/operations/01J.../subprocesses/2
          content:
            application/json:
              schema:
                type: object
                required: [spid]
                properties:
                  spid:
                    type: integer
                    minimum: 2
                    description: Spawn id assigned by the worker.
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: |
            Conflict — the operation exists but is not an instance, or
            is not currently EXECUTING / ASSIGNED.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '425':
          description: |
            Too Early (RFC 8470) — the VM is not ready to accept the
            exec yet: no worker holds the operation, or the guest
            control channel is still coming up.  Retry after
            `Retry-After`.
          headers:
            Retry-After:
              schema:
                type: integer
        '504':
          description: |
            Gateway Timeout — the guest accepted the connection but the
            spawn call didn't return in time.  The subprocess MAY have
            started anyway; do not blind-retry — inspect
            `GET /events` for a `spawn` event first.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /operations/{operationId}/subprocesses/{spid}:
    get:
      summary: Result of one subprocess, reconstructed from its events
      description: |
        Returns an `InstanceResult` for `spid` — the same shape as the
        parent operation's `metadata.result` — folded from the
        subprocess's event log (spawn / stdout / stderr / exit).
        Works for running and terminal operations alike.  While the
        process is still running, `state.exit_code` and `state.signal`
        are `-1` (unknown) and `resources` holds sentinel defaults;
        once the exit event lands they carry the real values.

        `stdout` / `stderr` are consolidated and capped at the spec's
        `truncate_output_at`.  The raw event stream stays available at
        `GET /operations/{operationId}/events?spid={spid}`.
      operationId: operationSubprocess
      tags:
        - operation
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - in: path
          name: spid
          required: true
          schema:
            type: integer
            minimum: 1
          description: Spawn id (1 = main process; ≥2 = exec'd children).
      responses:
        '200':
          description: Result of the requested subprocess.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InstanceResult'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          description: |
            Not Found — the operation does not exist, its event log has
            no `spawn` event for that spid, or the operation was
            CANCELLED (events are dropped for cancelled operations).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '425':
          description: |
            Too Early — the event source is not reachable yet (no
            worker holds the operation, or events.gz is not uploaded).
            Retry after `Retry-After`.
          headers:
            Retry-After:
              schema:
                type: integer

    delete:
      summary: Kill one subprocess
      description: |
        Sends a signal to the process group of `spid` inside the
        running instance.  Without the `signal` parameter the group
        gets SIGKILL.  Termination is observable, not returned: the
        `exit` event lands in the event log and
        `GET /operations/{operationId}/subprocesses/{spid}` reports
        the terminal `state` (`signal` set, `exit_code` -1 when killed).

        Killing `spid=1` (the main process) effectively ends the
        operation, like letting the command fail.
      operationId: operationSubprocessKill
      tags:
        - operation
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - in: path
          name: spid
          required: true
          schema:
            type: integer
            minimum: 1
          description: Spawn id (1 = main process; ≥2 = exec'd children).
        - in: query
          name: signal
          required: false
          schema:
            type: string
          description: |
            Signal to send instead of SIGKILL — a number (`15`) or a
            name with or without the SIG prefix (`TERM`, `SIGTERM`).
          example: SIGTERM
      responses:
        '204':
          description: Signal delivered to the subprocess's process group.
        '400':
          description: Invalid spid or unknown `signal` value.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: |
            Not Found — the operation does not exist, or the worker has
            no live process with that spid (never spawned or already
            exited).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: |
            Conflict — the operation exists but is not an instance, or
            is not currently EXECUTING / ASSIGNED.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '425':
          description: |
            Too Early — no worker holds the operation yet.  Retry after
            `Retry-After`.
          headers:
            Retry-After:
              schema:
                type: integer

  /operations/{operationId}/subprocesses/{spid}/stdin:
    post:
      summary: Write to a subprocess's stdin and/or close it
      description: |
        Writes a chunk to the stdin of a live process inside the
        running instance — `spid=1` targets the main process, `≥2` the
        exec'd children.  Requires the process to have been started
        with `stdin.close=false`; otherwise its pipe is already at EOF
        and the call returns 409.

        `close=true` (the default) signals EOF after writing `value`;
        an empty `value` with `close=true` just closes the pipe.  A
        client that serializes its own requests gets ordered writes;
        concurrent requests to the same spid are safe but their order
        is unspecified.

        A 504 means the guest write timed out mid-call — the chunk may
        or may not have been delivered (e.g. the process stopped
        reading and the pipe is full), so blind retries can duplicate
        data.
      operationId: operationSubprocessStdin
      tags:
        - operation
      parameters:
        - name: operationId
          in: path
          required: true
          description: The ID of the operation
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - in: path
          name: spid
          required: true
          schema:
            type: integer
            minimum: 1
          description: Spawn id (1 = main process; ≥2 = exec'd children).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ClosableStreamRepr'
      responses:
        '204':
          description: Chunk written (and/or stdin closed).
        '400':
          description: Invalid spid or request body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: |
            Not Found — the operation does not exist, or the worker has
            no live process with that spid (never spawned or already
            exited).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: |
            Conflict — the operation is not a running instance, or the
            process's stdin is already closed (spawned without
            `close=false`, closed by an earlier request, or the process
            exited).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '410':
          description: |
            Gone — the instance finished; there is no live process to
            write to.
        '425':
          description: |
            Too Early — no worker holds the operation yet, or the
            control channel is not up.  Retry after `Retry-After`.
          headers:
            Retry-After:
              schema:
                type: integer
        '501':
          description: |
            Not Implemented — the instance runs a guest image that
            predates stdin streaming.
        '504':
          description: |
            Gateway Timeout — the guest write did not complete in time;
            the chunk may or may not have been written.  Not safe to
            retry blindly.

  /operations/{operation_uuid}/files:
    post:
      summary: Apply an uploaded file to a running instance
      operationId: applyInstanceFile
      tags:
        - operations
      description: |
        Reads a file previously uploaded through POST /files and writes it to a
        running INSTANCE operation, including disposable instances. Requires LIST
        and the permission used to start the instance. Both the operation and the
        uploaded file must belong to the request namespace. Expired files are unavailable.
        The assigned worker streams the stored object to the guest through RPC.
        Init records request metadata in `inspect` events and the terminal
        publication result in `file_upload`, including `file_uuid` and byte count.
        File contents do not enter operation events.

        With unpack omitted or false, path is the full destination filename.
        Missing parent directories are created. The file is published atomically after
        transfer and SHA256 verification. The new file has mode 0644 and is
        owned by the guest runtime user. With replace true, an existing leaf symlink is replaced.
        Directories and special files are not regular file destinations.

        With unpack true, path is the destination directory. Supports tar,
        tar.gz and tar.bz2; compression is detected from the stored bytes. Xz is
        unsupported and rejected before subsequent chunks are sent. Without unpack,
        compressed archives are copied unchanged. Content-Type describes this JSON
        request and never controls extraction.

        Extraction accepts regular files, directories, symlinks and hardlinks to
        regular files already extracted in the staging tree. Parent symlinks inside that tree are
        not followed. Absolute entry names and entries containing '..' are rejected.
        procfs, sysfs, devices, FIFOs and sockets are unsupported. New directories
        have mode 0755; regular files retain tar permission bits (0777). Ownership
        and timestamps are not restored. Other entries fail explicitly.
        With replace omitted or false, any existing destination returns 409, including
        a symlink or empty directory. This condition is checked again atomically at publication.
        replace true permits an existing destination. With merge omitted or false,
        directory replacement removes the entire old tree without merging contents.

        Archives are extracted into a temporary sibling directory. The destination
        remains unchanged until the complete stream and SHA256 have been verified.
        Without merge, publication uses an atomic rename or exchange, then removes the old tree.
        Root and mount-point replacement are unavailable. Existing open descriptors
        can still refer to old inodes; concurrent workload access is not a snapshot.

        merge true requires both unpack true and replace true. After complete staging
        and verification, it combines directories and atomically replaces individual
        files and symlinks. Existing entries absent from the archive remain. Destination
        directory symlinks are not followed; directory/file conflicts fail explicitly.
        Same-filesystem hardlinks are retained. Crossing a destination mount requires
        copying file bytes and does not preserve hardlinks across filesystems.
        Merge is not atomic for the whole tree: errors, cancellation or timeout after
        application starts can leave completed changes. These changes are not rolled back.

        Returns 204 only after completion. Transfers have a 300-second deadline
        and bounded buffers and handles. Disconnect or VM exit cancels the transfer.
        A lost response can leave an uncertain outcome; requests are not replayed
        automatically. This endpoint does not write to a completed result image.

        A transfer timeout does not stop the instance. Before publication or merge starts, cancellation
        preserves the old destination and removes the temporary file or extraction tree.
        A timeout while awaiting the final response can occur after publication;
        it does not prove that no changes were made. An old-tree cleanup failure is
        reported as an error after publication; it does not roll back the new tree.
        The uploaded source object retains its normal lifetime. Automatically created
        parent directories have mode 0755 and can remain after errors.

        The primary command's timeout follows normal instance finalization: ordinary
        instances persist their filesystem, including successfully published uploads;
        disposable instances do not. Instance shutdown waits for pending upload cleanup.
        A timeout or crash of the execution environment can bypass this cleanup and does not produce
        a successfully persisted result image through normal finalization.
      parameters:
        - name: operation_uuid
          in: path
          required: true
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [file_uuid, path]
              properties:
                file_uuid:
                  $ref: '#/components/schemas/UUIDSchema'
                path:
                  type: string
                  minLength: 1
                  maxLength: 4096
                  description: Absolute guest filename, or directory when unpack is true. Missing parents are created.
                unpack:
                  type: boolean
                  default: false
                  description: Extract tar, tar.gz or tar.bz2 instead of copying the stored bytes.
                replace:
                  type: boolean
                  default: false
                  description: Permit an existing destination. Without merge, directories are replaced in full.
                merge:
                  type: boolean
                  default: false
                  description: Merge verified archive contents. Requires unpack and replace. Can leave partial changes.
            example:
              file_uuid: 799ba70b-911c-4fdd-97ea-da10910b94bd
              path: /workspace
              unpack: true
      responses:
        '204':
          description: File write or archive extraction completed.
        '400':
          description: Invalid JSON fields, UUID, damaged archive, or merge without both unpack and replace.
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing permission or inaccessible guest path.
        '404':
          description: Operation, uploaded file, stored object, or required directory not found.
        '409':
          description: Operation is not INSTANCE, destination exists without replace, or destination cannot be replaced.
        '410':
          description: Instance has exited.
        '415':
          description: Request Content-Type must be application/json.
        '422':
          description: Invalid path, unsupported file type, archive entry, or compression.
        '425':
          description: Instance filesystem is not ready.
        '429':
          description: Guest transfer resource limit reached.
        '501':
          description: Guest runtime does not support file writes.
        '502':
          description: Guest or storage transfer failed, or stored file integrity check failed.
        '503':
          description: Assigned worker is unavailable.
        '504':
          description: Transfer timed out.
        '507':
          description: Guest has insufficient space or quota.

  /operations/{operation_uuid}/inspect/download:
    get:
      summary: Download a file from a running instance
      description: |
        Reads through guest RPC without recording file contents in operation events.
        Requires LIST and the permission used to start this instance (SPAWN or
        SPAWN_DISPOSABLE). Reads include tmpfs and additional mounts visible to
        the guest runtime. procfs, sysfs, devices, sockets, and FIFOs are unavailable.
        Reads do not form a snapshot. The opened inode and initial size are used;
        later growth is excluded. Truncation or VM exit interrupts the response.
        A transfer has a 300-second deadline. No result-image fallback is performed.
      operationId: inspectInstanceDownload
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          description: The UUID of the running instance to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file to inspect inside the running instance, e.g. `/etc/hosts`
        - name: text
          in: query
          required: false
          allowEmptyValue: true
          schema:
            type: boolean
          description: If present (with or without value), returns text/plain format instead of JSON
          example: ""
      responses:
        '409':
          description: The operation is not an instance, or the file changed before streaming began.
        '502':
          description: Guest inspection failed.
        '503':
          description: The worker is unavailable.
        '410':
          description: The instance has exited. No image fallback is performed.
        '425':
          description: The instance filesystem is not ready.
        '429':
          description: The guest inspection resource limit was reached.
        '501':
          description: The guest runtime does not support live inspection.
        '504':
          description: Guest inspection timed out.
        '200':
          description: OK
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
            text/plain:
              schema:
                type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The file does not exist in the running instance or running instance does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path is not a file inside the running instance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    head:
      summary: Check if a file exists in running instance
      description: Checks if a file exists in the specified running instance without returning the file content
      operationId: checkInstanceFile
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          schema:
            type: string
            format: uuid
            example: "12345678-9abc-baba-deda-0123456789ab"
          description: The UUID of the running instance to inspect
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file to check inside the running instance, e.g. `/etc/hosts`
      responses:
        '409':
          description: The operation is not an instance, or the file changed before streaming began.
        '502':
          description: Guest inspection failed.
        '503':
          description: The worker is unavailable.
        '410':
          description: The instance has exited. No image fallback is performed.
        '425':
          description: The instance filesystem is not ready.
        '429':
          description: The guest inspection resource limit was reached.
        '501':
          description: The guest runtime does not support live inspection.
        '504':
          description: Guest inspection timed out.
        '200':
          description: OK - The file exists in the running instance
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Unauthorized - Invalid or missing authentication credentials
        '403':
          description: Forbidden - Token does not have sufficient permissions
        '404':
          description: Not Found - The file does not exist in the running instance or running instance does not exist
        '422':
          description: Unprocessable Entity - The specified path is not a file inside the running instance


  /operations/{operation_uuid}/inspect/list:
    get:
      summary: List files in running instance
      description: |
        Lists guest files without recording contents in operation events.
        Requires LIST and the permission used to start this instance.
        Reads do not form a snapshot. A directory can contain at most 10000 entries.
        procfs and sysfs cannot be listed.
      operationId: inspectInstanceFile
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          description: The UUID of the running instance to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          description: The path of the directory to inspect inside the running instance
          schema:
            type: string
            example: "/etc"
        - name: text
          in: query
          required: false
          allowEmptyValue: true
          schema:
            type: boolean
          description: If present (with or without value), returns text/plain format instead of JSON
          example: ""
      responses:
        '409':
          description: The operation is not an instance, or the file changed before streaming began.
        '502':
          description: Guest inspection failed.
        '503':
          description: The worker is unavailable.
        '410':
          description: The instance has exited. No image fallback is performed.
        '425':
          description: The instance filesystem is not ready.
        '429':
          description: The guest inspection resource limit was reached.
        '501':
          description: The guest runtime does not support live inspection.
        '504':
          description: Guest inspection timed out.
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectoryList'
            text/plain:
              schema:
                type: string
                description: ls-like output format
                example: |
                  total 19.42 KB
                  drwxr-xr-x 1 0 0   858.00 May 30 12:13 bin
                  drwxr-xr-x 1 0 0        0 May 30 12:13 dev
                  drwxr-xr-x 1 0 0   540.00 May 30 12:13 etc
                  drwxr-xr-x 1 0 0        0 May 30 12:13 home
                  drwxr-xr-x 1 0 0   146.00 May 30 12:13 lib
                  drwxr-xr-x 1 0 0    28.00 May 30 12:13 media
                  drwxr-xr-x 1 0 0        0 May 30 12:13 mnt
                  drwxr-xr-x 1 0 0        0 May 30 12:13 opt
                  dr-xr-xr-x 1 0 0        0 May 30 12:13 proc
                  drwx------ 1 0 0        0 May 30 12:13 root
                  drwxr-xr-x 1 0 0     8.00 May 30 12:13 run
                  drwxr-xr-x 1 0 0   790.00 May 30 12:13 sbin
                  drwxr-xr-x 1 0 0        0 May 30 12:13 srv
                  drwxr-xr-x 1 0 0        0 May 30 12:13 sys
                  drwxrwxrwt 1 0 0        0 May 30 12:13 tmp
                  drwxr-xr-x 1 0 0    40.00 May 30 12:13 usr
                  drwxr-xr-x 1 0 0    86.00 May 30 12:13 var
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The file does not exist in the running instance or running instance does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path could not be listed inside the running instance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'


  /operations/{operation_uuid}/inspect/archive:
    get:
      summary: Download a file or a directory from running instance as tar archive
      description: |
        Streams the specified path inside the running instance root filesystem as a POSIX PAX
        tar archive. A directory becomes the archive root; a regular file becomes
        a single-entry archive. The response is chunked; total size is not known
        upfront. Served as an attachment, `filename` is the path with `/` replaced
        by `_` plus `.tar` (e.g. `/bin/true` -> `bin_true.tar`).
        Requires LIST and the permission used to start this instance.
        Contents do not enter operation events. Reads do not form a snapshot.
        Traversal skips procfs and sysfs and preserves descendant symlinks.
        File changes or VM exit can interrupt the stream. Transfers have a
        300-second deadline.
      operationId: inspectInstanceArchive
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          description: The UUID of the running instance to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file or directory to archive inside the running instance, e.g. `/etc`
      responses:
        '409':
          description: The operation is not an instance, or the file changed before streaming began.
        '502':
          description: Guest inspection failed.
        '503':
          description: The worker is unavailable.
        '410':
          description: The instance has exited.
        '425':
          description: The instance filesystem is not ready.
        '501':
          description: The guest runtime does not support live inspection.
        '429':
          description: The guest inspection resource limit was reached.
        '504':
          description: Guest inspection timed out.
        '200':
          description: OK
          content:
            application/x-tar:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The path does not exist in the running instance or running instance does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path is not a regular file or directory inside the running instance
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    head:
      summary: Check if a path can be archived from running instance
      description: Checks if a file or a directory exists in the specified running instance without streaming the archive
      operationId: checkInstanceArchive
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          description: The UUID of the running instance to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file or directory to check inside the running instance, e.g. `/etc`
      responses:
        '409':
          description: The operation is not an instance, or the file changed before streaming began.
        '502':
          description: Guest inspection failed.
        '503':
          description: The worker is unavailable.
        '410':
          description: The instance has exited.
        '425':
          description: The instance filesystem is not ready.
        '501':
          description: The guest runtime does not support live inspection.
        '429':
          description: The guest inspection resource limit was reached.
        '504':
          description: Guest inspection timed out.
        '200':
          description: OK - The path exists in the running instance
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Unauthorized - Invalid or missing authentication credentials
        '403':
          description: Forbidden - Token does not have sufficient permissions
        '404':
          description: Not Found - The path does not exist in the running instance or running instance does not exist
        '422':
          description: Unprocessable Entity - The specified path is not a regular file or directory inside the running instance


  /inspect:
    get:
      summary: Redirect to /inspect/
      description: Redirects to /inspect/ with a trailing slash
      operationId: inspectRedirect
      tags:
        - inspect
      responses:
        '307':
          description: Temporary Redirect
          headers:
            Location:
              schema:
                type: string
              description: Redirect target with trailing slash
              example: /v1/inspect/

  /inspect/{imageUUID}:
    get:
      summary: Redirect to /inspect/{imageUUID}/
      description: Redirects to /inspect/{imageUUID}/ with a trailing slash
      operationId: inspectImageRedirect
      tags:
        - inspect
      parameters:
        - name: imageUUID
          in: path
          required: true
          description: The UUID of the image
          schema:
            $ref: '#/components/schemas/UUIDSchema'
      responses:
        '307':
          description: Temporary Redirect
          headers:
            Location:
              schema:
                type: string
              description: Redirect target with trailing slash
              example: /v1/inspect/12345678-9abc-baba-deda-0123456789ab/

  /inspect/:
    get:
      summary: Find image by tag
      description: Redirects to the image inspection endpoint for the specified tag
      operationId: inspectFindImageByTag
      tags:
        - inspect
      parameters:
        - name: tag
          in: query
          required: true
          description: The tag of the image to inspect
          schema:
              type: string
      responses:
        '302':
          description: Found - Redirecting to the image inspection endpoint
          headers:
            Location:
              schema:
                type: string
              description: URL of the image inspection endpoint
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /inspect/{image_uuid}/:
    get:
      summary: Inspect an image
      description: Returns image metadata
      operationId: inspectImage
      tags:
        - inspect
      parameters:
      - name: image_uuid
        in: path
        required: true
        description: The UUID of the image to inspect
        schema:
          $ref: '#/components/schemas/UUIDSchema'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Image'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'

  /inspect/{image_uuid}/download:
    get:
      summary: Download a file from image
      description: Returns file content
      operationId: inspectImageDownload
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          description: The UUID of the image to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file to inspect inside the image, e.g. `/etc/hosts`
        - name: text
          in: query
          required: false
          allowEmptyValue: true
          schema:
            type: boolean
          description: If present (with or without value), returns text/plain format instead of JSON
          example: ""
      responses:
        '200':
          description: OK
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
            text/plain:
              schema:
                type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The file does not exist in the image or image does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path is not a file inside the image
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    head:
      summary: Check if a file exists in image
      description: Checks if a file exists in the specified image without returning the file content
      operationId: checkImageFile
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          schema:
            type: string
            format: uuid
            example: "12345678-9abc-baba-deda-0123456789ab"
          description: The UUID of the image to inspect
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file to check inside the image, e.g. `/etc/hosts`
      responses:
        '200':
          description: OK - The file exists in the image
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Unauthorized - Invalid or missing authentication credentials
        '403':
          description: Forbidden - Token does not have sufficient permissions
        '404':
          description: Not Found - The file does not exist in the image or image does not exist
        '422':
          description: Unprocessable Entity - The specified path is not a file inside the image

  /inspect/{image_uuid}/archive:
    get:
      summary: Download a file or a directory from image as tar archive
      description: |
        Streams the specified path inside the image root filesystem as a POSIX PAX
        tar archive. A directory becomes the archive root; a regular file becomes
        a single-entry archive. The response is chunked; total size is not known
        upfront. Served as an attachment, `filename` is the path with `/` replaced
        by `_` plus `.tar` (e.g. `/bin/true` -> `bin_true.tar`).
      operationId: inspectImageArchive
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          description: The UUID of the image to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file or directory to archive inside the image, e.g. `/etc`
      responses:
        '200':
          description: OK
          content:
            application/x-tar:
              schema:
                type: string
                format: binary
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The path does not exist in the image or image does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path is not a regular file or directory inside the image
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    head:
      summary: Check if a path can be archived from image
      description: Checks if a file or a directory exists in the specified image without streaming the archive
      operationId: checkImageArchive
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          description: The UUID of the image to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          schema:
            type: string
          description: The path of the file or directory to check inside the image, e.g. `/etc`
      responses:
        '200':
          description: OK - The path exists in the image
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          description: Unauthorized - Invalid or missing authentication credentials
        '403':
          description: Forbidden - Token does not have sufficient permissions
        '404':
          description: Not Found - The path does not exist in the image or image does not exist
        '422':
          description: Unprocessable Entity - The specified path is not a regular file or directory inside the image

  /inspect/{image_uuid}/list:
    get:
      summary: List files in image
      description: Returns files list
      operationId: inspectImageFile
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          description: The UUID of the image to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: path
          in: query
          required: true
          allowReserved: true
          description: The path of the directory to inspect inside the image
          schema:
            type: string
            example: "/etc"
        - name: text
          in: query
          required: false
          allowEmptyValue: true
          schema:
            type: boolean
          description: If present (with or without value), returns text/plain format instead of JSON
          example: ""
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DirectoryList'
            text/plain:
              schema:
                type: string
                description: ls-like output format
                example: |
                  total 19.42 KB
                  drwxr-xr-x 1 0 0   858.00 May 30 12:13 bin
                  drwxr-xr-x 1 0 0        0 May 30 12:13 dev
                  drwxr-xr-x 1 0 0   540.00 May 30 12:13 etc
                  drwxr-xr-x 1 0 0        0 May 30 12:13 home
                  drwxr-xr-x 1 0 0   146.00 May 30 12:13 lib
                  drwxr-xr-x 1 0 0    28.00 May 30 12:13 media
                  drwxr-xr-x 1 0 0        0 May 30 12:13 mnt
                  drwxr-xr-x 1 0 0        0 May 30 12:13 opt
                  dr-xr-xr-x 1 0 0        0 May 30 12:13 proc
                  drwx------ 1 0 0        0 May 30 12:13 root
                  drwxr-xr-x 1 0 0     8.00 May 30 12:13 run
                  drwxr-xr-x 1 0 0   790.00 May 30 12:13 sbin
                  drwxr-xr-x 1 0 0        0 May 30 12:13 srv
                  drwxr-xr-x 1 0 0        0 May 30 12:13 sys
                  drwxrwxrwt 1 0 0        0 May 30 12:13 tmp
                  drwxr-xr-x 1 0 0    40.00 May 30 12:13 usr
                  drwxr-xr-x 1 0 0    86.00 May 30 12:13 var
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The file does not exist in the image or image does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Unprocessable Entity - The specified path could not be listed inside the image
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /operations/{operation_uuid}/inspect/grep:
    get:
      summary: Search file contents in running instance
      description: |
        Regex content search inside the running instance's root filesystem, through guest RPC.
        A Go converter translates supported Rust regex syntax to Go regexp.

        Symlinks are never followed during traversal, hidden files are searched,
        `.ignore` and `.gitignore` rules within each search root are respected.
        A NUL byte in the first 64 KiB causes a file to be skipped; a later NUL
        ends that file's search. Go regexp uses linear-time matching.
        The classes \w/\W, \d/\D, and \s/\S use Unicode semantics.
        Unicode properties and case folding are pinned to Unicode 16.0.0, matching the image engine.
        Scoped flags, nested class set operations, and bounded expansion of large repetitions are supported.
        Expanded patterns share a 1 MiB limit per request. Unsupported syntax returns 400 with a pattern
        index and byte offset. Unicode \b/\B, CRLF mode, non-ASCII byte mode, and \Q…\E are rejected.
        Use (?-u:\b) for an ASCII word boundary. Smart case examines parsed literals.

        Results are a flat, file-ordered list of lines. `before`/`after` request extra
        `type: context` lines around each `type: match` line, mirroring ripgrep's
        --json message type field.

        `path` may be repeated to search multiple roots in one call, the same way
        `pattern`/`glob` already can; results are concatenated in the given order
        and share the `max_total` budget across all of them.
        Results never enter operation events. Reads are live and do not form a snapshot.
        procfs, sysfs, devices, sockets, and FIFOs are not searched.
        Requires LIST and the permission used to start this instance.
        Searches have a 10-second budget per root and permit two concurrent
        searches per instance. Reaching the time, depth, or result limit sets
        `truncated`. Context lines count towards `max_total`. Display text is
        limited to 4096 bytes per line; matching can continue beyond this window.
      operationId: inspectInstanceGrep
      tags:
        - inspect
      parameters:
        - name: operation_uuid
          in: path
          required: true
          description: The UUID of the running instance to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: pattern
          in: query
          required: true
          allowReserved: true
          description: Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each.
          schema:
            type: string
            example: "^PermitRootLogin"
        - name: path
          in: query
          required: false
          allowReserved: true
          description: |
            File or directory to search inside the running instance. May be repeated (max 16) to search
            multiple roots; results are concatenated in the given order, sharing max_total
            across all paths. Defaults to the rootfs root.
          schema:
            type: string
            default: "/"
            example: "/etc"
        - name: glob
          in: query
          required: false
          allowReserved: true
          description: Glob to filter files (ripgrep -g semantics, "!" negates). May be repeated.
          schema:
            type: string
            example: "*.conf"
        - name: max_count
          in: query
          required: false
          description: Maximum matches per file (hard cap 10000).
          schema:
            type: integer
            minimum: 1
            maximum: 10000
        - name: max_total
          in: query
          required: false
          description: Maximum total matches across all files (default 1000, hard cap 10000).
          schema:
            type: integer
            minimum: 1
            maximum: 10000
            default: 1000
        - name: case
          in: query
          required: false
          description: Case sensitivity mode.
          schema:
            type: string
            enum: [sensitive, insensitive, smart]
            default: sensitive
        - name: before
          in: query
          required: false
          description: |
            Lines of context to include before each match (ripgrep -B semantics, hard cap 50).
            For symmetric context (grep -C n), pass both before and after yourself.
          schema:
            type: integer
            minimum: 0
            maximum: 50
            default: 0
        - name: after
          in: query
          required: false
          description: Lines of context to include after each match (ripgrep -A semantics, hard cap 50).
          schema:
            type: integer
            minimum: 0
            maximum: 50
            default: 0
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GrepResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The path does not exist in the running instance or running instance does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

        '409':
          description: The operation is not an instance.
        '422':
          description: The path has an unsupported file type or contains a NUL character.
        '410':
          description: Instance has exited
        '425':
          description: Guest is not ready
        '429':
          description: Guest inspection resource limit reached
        '501':
          description: Guest runtime does not support inspection
        '502':
          description: Guest inspection failed
        '503':
          description: Worker unavailable
        '504':
          description: Guest inspection timed out

  /inspect/{image_uuid}/grep:
    get:
      summary: Search file contents in image
      description: |
        Regex content search inside the image's root filesystem, powered by ripgrep.

        Symlinks are never followed during traversal, hidden files are searched,
        `.gitignore`-style files inside the image are ignored, and binary files
        (containing a NUL byte) are skipped. Rust regex syntax, linear-time matching.

        Results are a flat, file-ordered list of lines. `before`/`after` request extra
        `type: context` lines around each `type: match` line, mirroring ripgrep's
        --json message type field.

        `path` may be repeated to search multiple roots in one call, the same way
        `pattern`/`glob` already can; results are concatenated in the given order
        and share the `max_total` budget across all of them.
      operationId: inspectImageGrep
      tags:
        - inspect
      parameters:
        - name: image_uuid
          in: path
          required: true
          description: The UUID of the image to inspect
          schema:
            $ref: '#/components/schemas/UUIDSchema'
        - name: pattern
          in: query
          required: true
          allowReserved: true
          description: Regex pattern to search for. May be repeated (max 16); patterns are OR-ed. Max 1024 characters each.
          schema:
            type: string
            example: "^PermitRootLogin"
        - name: path
          in: query
          required: false
          allowReserved: true
          description: |
            File or directory to search inside the image. May be repeated (max 16) to search
            multiple roots; results are concatenated in the given order, sharing max_total
            across all paths. Defaults to the rootfs root.
          schema:
            type: string
            default: "/"
            example: "/etc"
        - name: glob
          in: query
          required: false
          allowReserved: true
          description: Glob to filter files (ripgrep -g semantics, "!" negates). May be repeated.
          schema:
            type: string
            example: "*.conf"
        - name: max_count
          in: query
          required: false
          description: Maximum matches per file (hard cap 10000).
          schema:
            type: integer
            minimum: 1
            maximum: 10000
        - name: max_total
          in: query
          required: false
          description: Maximum total matches across all files (default 1000, hard cap 10000).
          schema:
            type: integer
            minimum: 1
            maximum: 10000
            default: 1000
        - name: case
          in: query
          required: false
          description: Case sensitivity mode.
          schema:
            type: string
            enum: [sensitive, insensitive, smart]
            default: sensitive
        - name: before
          in: query
          required: false
          description: |
            Lines of context to include before each match (ripgrep -B semantics, hard cap 50).
            For symmetric context (grep -C n), pass both before and after yourself.
          schema:
            type: integer
            minimum: 0
            maximum: 50
            default: 0
        - name: after
          in: query
          required: false
          description: Lines of context to include after each match (ripgrep -A semantics, hard cap 50).
          schema:
            type: integer
            minimum: 0
            maximum: 50
            default: 0
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GrepResult'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Not Found - The path does not exist in the image or image does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /whoami:
    get:
      summary: Get current token information
      description: |
        Returns information about the current authentication token, including
        the token UUID, expiration time, and a map of all known permissions
        with their granted status.
      operationId: whoAmI
      tags:
        - auth
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WhoAmIResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

components:
  parameters:
    UntilParameter:
      name: until
      in: query
      required: false
      description: |
        **Show only results created before the given date/time or interval.**

        Accepts a Unix timestamp or interval string.

        Interval format: `600s`/`15m`/`2h`/`3d`/`1w` means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively).

        For example:
        * `2025-01-01T12:00:00+00:00` means January 1st, 2025 at 12:00 UTC
        * `600s` means 600 seconds ago
        * `15m` means 15 minutes ago

        Invalid values raise 400 error.
      schema:
        type: string
      example: 1h
    SinceParameter:
      name: since
      in: query
      required: false
      schema:
        type: string
      example: 1w
      description: |
        **Show only results created after the given date/time or interval.**

        Accepts a Unix timestamp or interval string.

        Interval format: `600s`/`15m`/`2h`/`3d`/`1w` means 600 seconds, 15 minutes, 2 hours, 3 day, or 1 week ago respectively).

        For example:
        * `2025-01-01T12:00:00+00:00` means January 1st, 2025 at 12:00 UTC
        * `600s` means 600 seconds ago
        * `15m` means 15 minutes ago

        Invalid values raise 400 error.

  responses:
    Unauthorized:
      description: |
        Unauthorized - Invalid or missing authentication credentials.
        Either the `Authorization` bearer token is missing or invalid, or
        the `Project` header is missing.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    Forbidden:
      description: Forbidden - Token does not have sufficient permissions
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    NotFound:
      description: Not Found - The requested resource does not exist
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    BadRequest:
      description: Bad Request - Invalid request parameters
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

    Conflict:
      description: Conflict - The operation cannot be completed due to a conflict
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

  securitySchemes:
    IAMBearerAuth:
      type: http
      scheme: bearer
      bearerFormat: IAM
      description: |
        IAM bearer token issued by the Nebius IAM service. Sent as
        `Authorization: Bearer <iam-token>`. Must be combined with the
        `Project` header (see `IAMProjectHeader`).

        This is the recommended authentication scheme for new clients.
    IAMProjectHeader:
      type: apiKey
      in: header
      name: Project
      description: |
        Nebius project ID associated with the IAM token. Required together
        with `IAMBearerAuth`. Identifies the project context the request is
        scoped to.

  schemas:
    UUIDSchema:
      type: string
      format: uuid
      description: A UUID string
      example: "12345678-9abc-baba-deda-0123456789ab"

    ImageSourceTag:
      type: string
      description: |
        A container image tag. String must be started with a prefix "tag:" followed by the actual tag.
      pattern: '^tag:[A-Za-z0-9][A-Za-z0-9_-]*(?:[:/.][A-Za-z0-9_-]+)*$'
      example: "tag:busybox:latest"

    ImageSource:
      oneOf:
        - $ref: '#/components/schemas/UUIDSchema'
        - $ref: '#/components/schemas/ImageSourceTag'
      description: |
        An base image for run a new instance. May be either image UUID or image tag (prefixed with "tag:").
        After creation of the instance, if tag is used, this value will be resolved to the image UUID,
        and the UUID will be stored in the metadata.
      example: "tag:busybox:latest"

    FileItem:
      type: object
      required:
        - size
        - path
        - owner
        - group
        - mode
        - mtime
        - nlink
        - uid
        - gid
        - is_dir
        - is_regular
        - is_symlink
        - is_socket
        - is_fifo
        - symlink_to
      properties:
        size:
          type: integer
          format: int64
          description: File size in bytes
          example: 1024
        path:
          type: string
          description: File name (relative to the directory being listed)
          example: "passwd"
        owner:
          oneOf:
            - type: string
            - type: integer
          description: File owner name or UID
          example: "root"
        group:
          oneOf:
            - type: string
            - type: integer
          description: File group name or GID
          example: "root"
        uid:
          type: integer
          description: User ID of the file owner
          example: 0
        gid:
          type: integer
          description: Group ID of the file
          example: 0
        mode:
          type: integer
          description: File mode/permissions as integer (octal representation)
          example: 33188
        mtime:
          type: integer
          format: int64
          description: Last modification time as Unix timestamp
          example: 1640995200
        nlink:
          type: integer
          description: Number of hard links
          example: 1
        is_dir:
          type: boolean
          description: True if the item is a directory
          example: false
        is_regular:
          type: boolean
          description: True if the item is a regular file
          example: true
        is_symlink:
          type: boolean
          description: True if the item is a symbolic link
          example: false
        is_socket:
          type: boolean
          description: True if the item is a socket
          example: false
        is_fifo:
          type: boolean
          description: True if the item is a FIFO/named pipe
          example: false
        symlink_to:
          type: string
          description: Target path if the item is a symbolic link, empty string otherwise
          example: ""

    DirectoryList:
      type: object
      required:
        - path
        - files
      properties:
        path:
          type: string
          description: The directory path that was listed
          example: "/etc"
        files:
          type: array
          description: List of files and directories in the specified path
          items:
            $ref: '#/components/schemas/FileItem'

    GrepSubmatch:
      type: object
      required:
        - text
        - start
        - end
      properties:
        text:
          type: string
          description: The matched text
          example: "PermitRootLogin"
        start:
          type: integer
          description: Byte offset of the match start within the line
          example: 1
        end:
          type: integer
          description: Byte offset of the match end within the line
          example: 16

    GrepMatch:
      type: object
      required:
        - path
        - line_number
        - absolute_offset
        - line_text
        - line_bytes
        - submatches
        - type
      properties:
        path:
          type: string
          description: File path relative to the image rootfs
          example: "/etc/ssh/sshd_config"
        line_number:
          type: integer
          description: 1-based line number of the match
          example: 57
        absolute_offset:
          type: integer
          description: Byte offset of the line from the start of the file
          example: 1712
        line_text:
          type: string
          description: The matching line, including the line terminator (truncated at 4096 bytes)
          example: "#PermitRootLogin prohibit-password\n"
        line_bytes:
          type: integer
          description: Real byte length of the matching line; greater than line_text length when the line was capped
          example: 8192
        submatches:
          type: array
          description: Empty for context lines (they carry no submatches)
          items:
            $ref: '#/components/schemas/GrepSubmatch'
        type:
          type: string
          enum: [match, context]
          description: |
            Mirrors ripgrep's --json message type: "match" is an actual match, "context" is a
            before/after context line requested via before/after.
          example: match

    GrepResult:
      type: object
      required:
        - path
        - patterns
        - matches
        - truncated
      properties:
        path:
          type: string
          description: |
            The first path inside the image that was searched. When `path` was repeated,
            see each row's own `path` for which root it actually came from.
          example: "/etc"
        patterns:
          type: array
          description: The patterns that were searched for
          items:
            type: string
          example: ["^PermitRootLogin"]
        matches:
          type: array
          description: File-ordered lines; each is a match or (when before/after are set) surrounding context
          items:
            $ref: '#/components/schemas/GrepMatch'
        truncated:
          type: boolean
          description: True when max_total or the search deadline stopped the search early
          example: false

    ImageImportRequest:
      type: object
      required:
        - registry
      properties:
        registry:
          type: object
          required:
            - url
          properties:
            url:
              type: string
              description: URL of the container registry
              example: docker://docker.io/busybox:latest
            credentials:
              type: object
              properties:
                username:
                  type: string
                  description: Username for the registry authentication
                  example: myuser
                password:
                  type: string
                  description: Password for the registry authentication
                  example: secret
                  format: password
        tag:
          type: string
          nullable: true
          description: Tag to identify the image when listing publicly available images. If omitted, the image will be private and only accessible by ID.
          example: busybox:latest
        timeout:
          type: integer
          description: Maximum time in seconds to wait for the import operation to complete
          default: 300
          example: 300

    ImageListResponse:
      type: object
      properties:
        images:
          type: array
          items:
            $ref: '#/components/schemas/Image'
          description: List of publicly available images

    ImageImportMetadata:
      type: object
      properties:
        registry:
          type: object
          properties:
            url:
              type: string
              description: URL of the container registry
              example: docker://docker.io/busybox:latest
            credentials:
              type: object
              properties:
                username:
                  type: string
                  description: Username for the registry authentication
                  example: myuser
                password:
                  type: string
                  description: Always masked in the response is present
                  example: "<MASKED>"
        tag:
          type: string
          nullable: true
        timeout:
          type: integer
          description: Maximum time in seconds to wait for the import operation to complete
          default: 300
          example: 300

    Image:
      type: object
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        tag:
          type: string
          nullable: true
          description: Tag to identify the image
          example: busybox:latest
        created_at:
          type: string
          description: ISO 8601 formatted timestamp of when the image was created
          example: "2024-01-01T12:00:00+00:00"
        operation_uuid:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/UUIDSchema'
          description: |
            UUID of the operation that created this image.
            Returns `null` when the image belongs to a different namespace (e.g. public images)
            or when the image was not created by an operation (e.g. shared images).

    StreamRepr:
      type: object
      required:
        - value
        - encoding
      properties:
        value:
          type: string
          description: Content of the stream
          example: "Y29tbWFuZCBvdXRwdXQK"
        encoding:
          type: string
          enum: [ascii, base64]
          description: Encoding of the content
          example: "base64"
        truncated:
          type: boolean
          description: Whether the output was truncated
          example: false

    ClosableStreamRepr:
      type: object
      description: |
        Stdin payload.  Delivery to the child is always complete —
        stdin is never truncated on its way to the process.  Only the
        *recorded* `stdin` events in the subprocess event log are
        capped by `truncate_output_at`, same as stdout/stderr.  This
        schema also carries a `close` flag controlling the pipe's EOF.
      required:
        - value
      properties:
        value:
          type: string
          description: Content to write to stdin (may be empty for a close-only request)
          example: "aGVsbG8K"
        encoding:
          type: string
          enum: [ascii, base64]
          description: Encoding of the content
          default: ascii
        close:
          type: boolean
          default: true
          description: |
            `true` (default) closes stdin (EOF) after writing `value` —
            the pre-existing one-shot behavior.  `false` keeps the pipe
            open so more data can be sent later via
            `POST /operations/{operationId}/subprocesses/{spid}/stdin`.

    InstanceResourcesLimits:
      type: object
      additionalProperties: false
      description: |
        Launch-time limits. CPU sets the VM's vCPU count. memory_mib limits
        each process's address space (RLIMIT_AS, soft and hard) and the
        whole process tree's memory (cgroup memory.max). A request for
        1 MiB is valid and enforces that limit on the workload. The backend
        independently selects a minimum VM RAM allocation for guest boot,
        networking and runtime services, for example 128 or 256 MiB.
        This minimum is an implementation detail and can change. It does
        not increase the requested workload limit.
        A small address-space limit can prevent the executable or runtime
        from loading. It includes stacks, libraries and reserved mappings;
        allocations can fail with ENOMEM even with overcommit enabled.
        Guest kernel and runtime consume part of VM RAM.
        Limits are maxima, not reservations.
        Guest root retains permission to modify cgroups.
      properties:
        cpu:
          type: integer
          minimum: 1
          maximum: 4
          default: 4
          description: Number of guest vCPUs.
        memory_mib:
          type: integer
          minimum: 1
          maximum: 8192
          default: 4096
          description: Per-process address-space and process-tree memory limit in MiB (1048576 bytes).
        max_layer_bytes:
          type: integer
          minimum: 1
          description: Maximum writable layer size in bytes.
          example: 1073741824
          default: 12884901888

    ProcessResourcesLimits:
      type: object
      additionalProperties: false
      description: |
        Launch-time limits for a subprocess and its descendants. Each omitted
        or null field inherits the requested operation limit, not the VM's
        minimum boot memory. CPU/RAM cannot exceed the parent operation.
        Limits are maxima, not reservations. Concurrent processes share VM
        resources and can exhaust the aggregate budget. memory_mib sets
        RLIMIT_AS (soft and hard) before exec and memory.max for the tree.
        RLIMIT_AS includes reserved mappings, stacks and libraries; allocation
        or executable loading can fail with ENOMEM. Descendants inherit it.
        A local cgroup OOM
        kills this process tree. A VM-wide OOM can affect other processes.
        Guest root retains permission to modify cgroups.
      properties:
        cpu:
          type: integer
          nullable: true
          minimum: 1
          maximum: 4
          description: >
            Number of guest vCPUs available to the process tree. The runtime
            selects CPU affinity; CPU sets can overlap between subprocesses.
        memory_mib:
          type: integer
          nullable: true
          minimum: 1
          maximum: 8192
          description: Per-process RLIMIT_AS and tree memory.max in MiB. Swap is disabled for this group.

    InstanceNetworking:
      type: object
      properties:
        enabled:
          type: boolean
          description: >
            Enable network access for the instance. When `false`, the VM starts without
            a guest network interface.
          default: true
        policy:
          type: array
          maxItems: 512
          description: |
            Network policies to apply, referenced by UUID or by tag prefixed with `tag:`.

            **References**

            - You can use your own policies and shared policies.
            - Your tag takes precedence over a shared tag with the same name.
            - Duplicate references and resolved policy UUIDs are removed while preserving first occurrence order.
            - Unknown or unavailable references return 404.
            - Deleted policies remain usable by UUID.

            **Permissions**

            Using policies requires only the permission to create the instance;
            `network_policy` is not required.

            **Limits**

            - At most 512 references may be supplied, including duplicates.
            - Before and after merging, the rules are limited to 16384 units in total:
              sum the number of ports across all rules, counting an all-port rule as 1.
              All IP versions and protocols share this limit. Repeated rules and ports
              across policies count again before merging.
            - Exceeding either limit returns 400.

            **No policies**

            Omitting this field or passing `policy: []` allows all IPv4 destinations and
            global unicast IPv6 destinations on all ports.
            The API adds four explicit rules to `effective_policy`:
            TCP and UDP for IPv4 `0.0.0.0/0` and IPv6 `2000::/3`, each with `ports: []`
            (all ports). ICMP is also allowed to these destinations.
            IPv6 destinations outside `2000::/3`, including unique-local and link-local
            addresses, require explicit policy rules.

            **Empty policies**

            A selected policy with no rules (`{"cidrs": []}`) allows nothing.
            If all selected policies are empty, `effective_policy` is `{"cidrs": []}`
            and all network traffic is denied.
            An empty policy combined with non-empty policies adds no permissions;
            the other policies' rules still apply.

            **Effective policy**

            `effective_policy` contains the final combined network rules that will be
            applied to the operation.
            Rules are combined by merging CIDRs per protocol and port, then grouping
            ports for matching CIDRs and protocols.
          default: []
          items:
            oneOf:
              - $ref: '#/components/schemas/UUIDSchema'
              - type: string
                pattern: '^tag:.+$'
                description: Network policy tag reference.
          example:
            - "12345678-9abc-baba-deda-0123456789ab"
            - "tag:github"

    InstanceNetworkingResponse:
      allOf:
        - $ref: '#/components/schemas/InstanceNetworking'
        - type: object
          properties:
            policy:
              type: array
              description: Unique applied policy UUIDs in first occurrence order. Tag references are returned as UUIDs.
              items:
                $ref: '#/components/schemas/UUIDSchema'
            effective_policy:
              type: object
              nullable: true
              readOnly: true
              description: |
                The final combined network rules that will be applied to the operation.
                New instances always include an explicit effective policy, including when
                no policy references are specified. Omitting `networking.policy` or passing
                `policy: []` allows all IPv4 and global unicast IPv6 destinations on all ports:
                this field contains four rules, TCP and UDP for both `0.0.0.0/0` (IPv4)
                and `2000::/3` (IPv6), with `ports: []` on each rule.
                ICMP is also allowed to these destinations.
                IPv6 destinations outside `2000::/3` require explicit policy rules.
                Selecting only empty policies (`{"cidrs": []}`) instead produces `{"cidrs": []}`,
                which denies all network traffic. Empty policies add no permissions when
                combined with non-empty policies.
                Historical instance metadata may omit this field or contain null.
              allOf:
                - $ref: '#/components/schemas/NetworkPolicyCreateRequest'

    NetworkPolicyTag:
      type: object
      required:
        - tag
        - uuid
      properties:
        tag:
          type: string
          description: Network policy tag name
        uuid:
          $ref: '#/components/schemas/UUIDSchema'

    NetworkPolicyCIDRRule:
      type: object
      required:
        - cidr
        - proto
      properties:
        cidr:
          type: string
          description: IPv4 or IPv6 destination network in CIDR notation.
          example: 192.0.2.0/24
        proto:
          type: string
          enum: [tcp, udp]
        ports:
          type: array
          description: Allowed destination ports. Omitted or empty means all ports.
          default: []
          items:
            type: integer
            minimum: 1
            maximum: 65535

    NetworkPolicyCreateRequest:
      type: object
      description: |
        An allowlist of destination networks, protocols, and ports. A policy with `{"cidrs": []}`
        allows nothing. Selecting only empty policies denies all network traffic.
        This differs from selecting no policies (`networking.policy: []`), which allows
        all IPv4 destinations (`0.0.0.0/0`) and global unicast IPv6 destinations (`2000::/3`)
        on all ports and adds these explicit rules to `effective_policy`.
      additionalProperties: false
      required:
        - cidrs
      properties:
        cidrs:
          type: array
          items:
            $ref: '#/components/schemas/NetworkPolicyCIDRRule'

    NetworkPolicy:
      type: object
      required:
        - uuid
        - cidrs
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        cidrs:
          type: array
          items:
            $ref: '#/components/schemas/NetworkPolicyCIDRRule'

    NetworkPolicyListItem:
      type: object
      required:
        - uuid
        - created_at
        - tags
        - summary
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        created_at:
          type: string
          format: date-time
          description: Time when the policy was created.
        tags:
          type: array
          description: Accessible tag names resolving to this policy, sorted by name. Empty when none exist.
          items:
            type: string
        summary:
          type: object
          required:
            - cidrs
          properties:
            cidrs:
              type: integer
              minimum: 0
              description: Number of CIDR rules in the policy, including repeated CIDRs.

    NetworkPolicyListResponse:
      type: object
      required:
        - policies
      properties:
        policies:
          type: array
          items:
            $ref: '#/components/schemas/NetworkPolicyListItem'

    ExecSpec:
      type: object
      description: |
        Process-execution surface shared between `InstanceSpawnRequest`
        (the main process) and
        `POST /operations/{operationId}/subprocesses` (additional
        subprocesses).  VM-level concerns (image, hostname,
        disk limits, files, timeout, disposable, preserve_env)
        live on `InstanceSpawnRequest` only.
      required:
        - command
      properties:
        resources_limits:
          $ref: '#/components/schemas/ProcessResourcesLimits'
        command:
          type: string
          description: >
            The command to execute.  Same semantics as in
            `InstanceSpawnRequest.command` — when `shell=true` it is a
            shell expression, otherwise a path to an executable.
          example: /bin/app
        args:
          type: array
          items:
            type: string
          description: Arguments to pass to the command if shell is set to false.
          example: [arg1, arg2]
          default: []
        shell:
          type: boolean
          description: Run command through a shell expression (args must be empty).
          default: false
        env:
          nullable: true
          type: object
          additionalProperties:
            type: string
          description: Environment variables to set in the child process.
        cwd:
          type: string
          pattern: "^((/[^/]*)+/?)?$"
          description: Working directory; empty string means image / server default.
          default: ""
        uid:
          type: integer
          minimum: 0
          default: 0
          description: User ID to run the process as.
        gid:
          type: integer
          minimum: 0
          default: 0
          description: Group ID to run the process as.
        stdin:
          allOf:
            - $ref: '#/components/schemas/ClosableStreamRepr'
          description: |
            Bytes fed to the child's stdin — honored for both the main
            process and exec'd subprocesses.  With `close=false` the
            pipe stays open and more data can be written via
            `POST /operations/{operationId}/subprocesses/{spid}/stdin`.
        truncate_output_at:
          type: integer
          description: |
            Maximum number of bytes to keep per stream (stdout,
            stderr, and stdin) in the subprocess event log.  Does not
            affect delivery to the child — stdin is always delivered
            in full regardless of this cap.  Defaults to 1 MiB; capped
            at 10 MiB.
          default: 1048576
          example: 65535

    InstanceSpawnRequest:
      type: object
      required:
        - command
        - image
      properties:
        command:
          type: string
          description: >
            The command to execute. In case if `shell` is set to `true`, this MUST contain
            shell expression.

            For example `echo hello world` or `ls -l /app`.

            If `shell` is set to `false`, this must be a relative or absolute path to the executable inside the
            image rootfs.

            For example: `/bin/app` or `/usr/bin/find`.

            Do not forget pass necessary `PATH` variable to env field, by default `PATH` is set to
            `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`.
          example: /bin/app
        disposable:
          type: boolean
          description: Creates a disposable execution environment no any state will be saved.
          default: false
        hostname:
          type: string
          description: Hostname to set when execution.
          example: container-name
          default: linuxkit
        image:
          $ref: '#/components/schemas/ImageSource'
        args:
          type: array
          items:
            type: string
          description: >
            Arguments to pass to the command if shell is set to false.
          example: [arg1, arg2]
          default: []
        shell:
          type: boolean
          description: >
            Whether to run the command through a shell. If `true`, the command must be a shell expression and all
            values from args will be ignored. If `false`, the command field must be a path to an executable and
            args will be used. When `true`, environment variables from the image are automatically inherited.
            When `false`, they are not - use the `env` field to pass them explicitly.
          default: false
        env:
          nullable: true
          type: object
          additionalProperties:
            type: string
          description: >
            Environment variables to set in the container. These are merged with image-defined
            variables when `shell` is `true`. When `shell` is `false`, only variables specified
            here are available - image-defined variables are not inherited.
          example:
            KEY1: value1
            KEY2: value2
        preserve_env:
          type: boolean
          description: >
            Preserve environment variables in resulting image after execution.
            When `true`, the image's existing environment variables from `metadata/env` are merged
            with user-provided `env` values (user values take priority on conflicts), and the
            combined result is written back to `metadata/env` after command execution.
            Setting a variable to an empty string or `null` removes it from the preserved environment.
          default: false
        preserve_cwd:
          type: boolean
          description: >
            Save the resolved initial working directory as the default in the resulting image.
            An empty or omitted `cwd` resolves to the image's current workdir, or `/` if none exists.
            The metadata file is opened for writing only when its contents differ from the new value.
            Directory changes made by the command do not change the saved value.
            Requires `disposable: false` to retain the metadata in a resulting image.
          default: false
        cwd:
          type: string
          pattern: "^((/[^/]*)+/?)?$"
          description: >
            Path to the working directory, must be absolute or a special value the empty string.
            It means the default working directory of the image or server default will be used.
            If field is omitted it will be set to the empty string.
            The directory will be created automatically if it does not exist.
          example: /app
          default: ""
        uid:
          type: integer
          minimum: 0
          description: User ID to run the process as.
          example: 0
          default: 0
        gid:
          type: integer
          minimum: 0
          description: Group ID to run the process as.
          example: 0
          default: 0
        resources_limits:
          $ref: '#/components/schemas/InstanceResourcesLimits'
        networking:
          $ref: '#/components/schemas/InstanceNetworking'
        stdin:
          $ref: '#/components/schemas/ClosableStreamRepr'
        timeout:
          type: integer
          description: Maximum execution time in seconds
          example: 60
        truncate_output_at:
          type: integer
          description: >
            Maximum number of bytes to keep per stream (stdout,
            stderr, and stdin) in the subprocess event log.
            Does not affect stdin delivery to the child, which always
            receives the complete stream regardless of this cap.
            Default is `1048576` (1 MiB).
            The maximum value is `10485760` (10 MiB).
          example: 65535
          default: 1048576
        files:
          type: object
          description: Map of absolute file paths to file metadata
          additionalProperties:
            type: object
            properties:
              uuid:
                $ref: '#/components/schemas/UUIDSchema'
              uid:
                type: integer
                description: User ID
                example: 0
              gid:
                type: integer
                description: Group ID
                example: 0
              mode:
                type: string
                description: File mode in octal format (e.g., "0644")
                example: "0644"
          example:
            /root/hello.txt:
              uuid: "a9165a5d-5c86-4bd8-8ee4-ae46c19cf45d"
              uid: 0
              gid: 0
              mode: "0644"
            /tmp/log.txt:
              uuid: "065def2a-e977-4852-8b26-a0ec05e85a90"
              uid: 1000
              gid: 1000
              mode: "0600"

    InstanceSpawnResponse:
      type: object
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        command:
          type: string
        image:
          $ref: '#/components/schemas/UUIDSchema'
        hostname:
          type: string
        args:
          type: array
          items:
            type: string
        shell:
          type: boolean
        env:
          nullable: true
          type: object
          additionalProperties:
            type: string
        preserve_env:
          type: boolean
        cwd:
          type: string
        uid:
          type: integer
        gid:
          type: integer
        resources_limits:
          $ref: '#/components/schemas/InstanceResourcesLimits'
        networking:
          $ref: '#/components/schemas/InstanceNetworkingResponse'
        stdin:
          $ref: '#/components/schemas/ClosableStreamRepr'
        timeout:
          type: integer
        truncate_output_at:
          type: integer
        disposable:
          type: boolean
        files:
          type: object
          additionalProperties:
            type: object
            properties:
              uuid:
                $ref: '#/components/schemas/UUIDSchema'
              uid:
                type: integer
              gid:
                type: integer
              mode:
                type: string
        result:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/InstanceResult'

    OperationSummary:
      type: object
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        kind:
          type: string
          description: Type of the operation
          enum: [ image_import, instance ]
        status:
          type: string
          enum: [ PENDING, ASSIGNED, EXECUTING, SUCCESS, FAILED, CANCELLED ]
          description: Current state of the instance operation
          example: success
        error:
          type: string
          nullable: true
          description: Error message if the operation failed
          example: "Container image not found"
        created_at:
          type: string
          description: ISO 8601 formatted timestamp when the operation was created
          example: "2024-01-01T12:00:00+00:00"
        duration:
          type: number
          nullable: true
          description: Operation duration in seconds
        image_size:
          type: integer
          nullable: true
          description: |
            Bytes written for the resulting image/layer(s).
            `null` when not measured (e.g. disposable instance, non-SUCCESS operations).
        consumed_cpu:
          type: number
          nullable: true
          description: |
            Total CPU time consumed by the operation, in seconds.
            `null` when not measured.
        consumed_memory:
          type: integer
          nullable: true
          description: |
            Peak resident memory used by the operation's execution environment, in KiB.
            `null` when not measured. Shared resident pages are included.
        image_uuid:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/UUIDSchema'
          description: |
            UUID of the source image this operation was run on.
            Set for INSTANCE operations, `null` for IMAGE_IMPORT.
        result_image_uuid:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/UUIDSchema'
          description: |
            UUID of the image produced by this operation.
            Only set for completed (SUCCESS) operations, `null` otherwise.

    InstanceResult:
      type: object
      description: Result of an instance execution
      properties:
        resources:
          type: object
          properties:
            block_input:
              type: integer
              description: Block input operations
            block_output:
              type: integer
              description: Block output operations
            cost:
              type: number
              format: float
              description: Operation cost
            elapsed_time:
              type: number
              description: Elapsed wall time
            involuntary_switches:
              type: integer
              description: Number of involuntary context switches
            max_rss:
              type: integer
              description: Maximum resident set size in KB
            monotonic_time:
              type: number
              format: float
              description: Monotonic time measurement
            page_faults:
              type: integer
              description: Number of page faults
            page_faults_io:
              type: integer
              description: Number of page faults requiring I/O
            shared_memory:
              type: integer
              description: Shared memory size
            signals:
              type: integer
              description: Number of signals received
            swaps:
              type: integer
              description: Number of swaps
            system_cpu_time:
              type: number
              format: float
              description: System CPU time used
            unshared_memory:
              type: integer
              description: Unshared memory size
            user_cpu_time:
              type: number
              format: float
              description: User CPU time used
            voluntary_switches:
              type: integer
              description: Number of voluntary context switches
        state:
          type: object
          properties:
            continued:
              type: boolean
              description: Whether the process was continued from a stop
            core_dump:
              type: boolean
              description: Whether a core dump was generated
            exit_code:
              type: integer
              description: Process exit code
            pid:
              type: integer
              description: Process ID
            signal:
              type: integer
              description: Signal that caused termination, if any
            stopped:
              type: boolean
              description: Whether the process was stopped
            timed_out:
              type: boolean
              description: Whether process had been killed because operation timeout was reached
            oom_killed:
              type: boolean
              default: false
              description: Whether an OOM kill was observed in the process tree's cgroup.
        stdout:
          $ref: '#/components/schemas/StreamRepr'
        stderr:
          $ref: '#/components/schemas/StreamRepr'

    OperationInstanceMetadata:
      allOf:
        - $ref: '#/components/schemas/InstanceSpawnRequest'
        - type: object
          description: Metadata for an instance execution operation, including request parameters and result
          properties:
            image:
              $ref: '#/components/schemas/UUIDSchema'
            networking:
              $ref: '#/components/schemas/InstanceNetworkingResponse'
            result:
              $ref: '#/components/schemas/InstanceResult'

    OperationMetadata:
      oneOf:
        - $ref: '#/components/schemas/OperationInstanceMetadata'
        - $ref: '#/components/schemas/ImageImportMetadata'
      description: Metadata specific to the operation type

    OperationResponse:
      type: object
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        kind:
          type: string
          description: Type of the operation
          enum: [ image_import, instance ]
        status:
          type: string
          enum: [ PENDING, ASSIGNED, EXECUTING, SUCCESS, FAILED, CANCELLED ]
        error:
          type: string
          nullable: true
        created_at:
          type: string
          description: ISO 8601 formatted timestamp when the operation was created
          example: "2024-01-01T12:00:00+00:00"
        duration:
          type: number
          nullable: true
        image_size:
          type: integer
          nullable: true
          description: |
            Bytes written for the resulting image/layer(s).
            `null` when not measured (e.g. disposable instance, non-SUCCESS operations).
        consumed_cpu:
          type: number
          nullable: true
          description: |
            Total CPU time consumed by the operation, in seconds.
            `null` when not measured.
        consumed_memory:
          type: integer
          nullable: true
          description: |
            Peak resident memory used by the operation's execution environment, in KiB.
            `null` when not measured. Shared resident pages are included.
        image_uuid:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/UUIDSchema'
          description: |
            UUID of the source image this operation was run on.
            Set for INSTANCE operations, `null` for IMAGE_IMPORT.
        result_image_uuid:
          nullable: true
          allOf:
            - $ref: '#/components/schemas/UUIDSchema'
          description: |
            UUID of the image produced by this operation.
            Only set for completed (SUCCESS) operations, `null` otherwise.
        metadata:
          $ref: '#/components/schemas/OperationMetadata'
        result:
          type: object
          description: Result of the operation, if any
          properties:
            image:
              nullable: true
              allOf:
                - $ref: '#/components/schemas/UUIDSchema'
            tag:
              type: string
              nullable: true
              description: Tag assigned to the imported image
              example: busybox:latest

    Error:
      type: object
      required:
        - error
      properties:
        error:
          oneOf:
            - type: string
            - type: object
            - type: array
              items:
                type: object
          description: Error message or structured validation errors
          example: "Some error occurred, this is an example of error message"
        status:
          type: integer
          description: HTTP status code
          example: 500
        traceback:
          type: array
          items:
            type: string
    FileResponse:
      type: object
      required:
        - uuid
        - sha256
        - size
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        sha256:
          type: string
          description: SHA256 hash of the file content
          example: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        size:
          type: integer
          format: int64
          description: File size in bytes; -1 if unknown
          example: 1024

    File:
      type: object
      required:
        - uuid
        - sha256
        - size
        - created_at
        - updated_at
      properties:
        uuid:
          $ref: '#/components/schemas/UUIDSchema'
        sha256:
          type: string
          description: SHA256 hash of the file content
        size:
          type: integer
          format: int64
          description: File size in bytes; -1 if unknown
          example: 1024
        created_at:
          type: string
          format: date-time
          description: When the file was first uploaded by this namespace
        updated_at:
          type: string
          format: date-time
          description: Updated on each upload of the same file

    FilesListResponse:
      type: object
      properties:
        files:
          type: array
          items:
            $ref: '#/components/schemas/File'

    WhoAmIResponse:
      type: object
      required:
        - token_uuid
        - token_expiration
        - permissions
        - operations_stat
      properties:
        token_uuid:
          type: string
          description: UUID of the authentication token
          example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
        token_expiration:
          type: integer
          nullable: true
          description: Token expiration time as Unix timestamp, or null if not set
          example: 1735689600
        permissions:
          type: object
          additionalProperties:
            type: boolean
          description: |
            Map of all known permission names to their granted status.
            Keys are permission names (e.g., `import`, `spawn`, `list`),
            values indicate whether the token has the permission.
          example:
            import: true
            spawn: true
            spawn_disposable: false
            list: true
            cancel: false
            set_image_tag: false
            network_policy: false
        limits:
          type: object
          additionalProperties:
            type: integer
          description: Map of resource limit names to their values for the current token.
          example:
            instance_max_timeout: 3600
            instance_max_concurrency: 10
            images_import_max_concurrency: 5
            images_import_max_timeout: 3600
        operations_stat:
          type: object
          additionalProperties:
            type: integer
          description: Operation statistics (reserved for future use)

    # ------------------------------------------------------------
    # Event log schemas
    # ------------------------------------------------------------
    # GET /operations/{operationId}/events returns SSE; each frame
    # carries one OperationEvent JSON in its `data:` field.
    # ------------------------------------------------------------

    OperationEventStream:
      type: string
      format: binary
      description: |
        SSE response body for `GET /operations/{operationId}/events`.
        Wire format: a sequence of `\n\n`-separated frames; each frame
        is an [`OperationEventSSEFrame`](#/components/schemas/OperationEventSSEFrame).

        OpenAPI doesn't have first-class SSE support, so this content
        is typed as binary at the protocol level — but the per-frame
        contract is the linked schema.  Clients should parse frame by
        frame and either dispatch on the `event:` line (e.g. via
        native `EventSource`) or JSON-decode the `data:` payload.

    OperationEventSSEFrame:
      type: object
      description: |
        One SSE frame in the `/events` stream.  Three categories:

          * **Normal event** — `event:` carries the
            [`OperationEventType`](#/components/schemas/OperationEventType),
            `id:` carries the monotonic event id, `data:` carries the
            full [`OperationEvent`](#/components/schemas/OperationEvent)
            JSON.
          * **Server error** — `event: sse_error`, `data:` is a
            plain-text exception message (NOT JSON).  Pairs with a
            preceding `: stream ended with error, retry since last
            event id` comment line.
          * **Keepalive comment** — `: keepalive` (no `event:`/`id:`/`data:`).
            Discardable.

        This object is the abstract description of what one frame can
        carry; the wire is line-oriented text per the SSE spec.
      properties:
        id:
          type: integer
          format: int64
          description: |
            Monotonic event id.  Present on normal event frames; absent
            on `sse_error` and keepalive frames.
        event:
          type: string
          description: |
            On a normal frame this matches `data.type` and the
            `OperationEventType` enum.  On a transport error this is
            the literal `sse_error`.
        data:
          oneOf:
            - $ref: '#/components/schemas/OperationEvent'
            - type: string
              description: |
                Plain-text exception message (only for `event: sse_error` frames).

    OperationEvent:
      type: object
      required: [id, ts, type, data]
      description: |
        One event in the operation's event log.

        **Process events** carry a Spawned Process ID (`spid`) as
        their routing identity: `spid=0` is the daemon (init /
        network / shutdown / size_cap, plus any synthetic stderr
        emitted before a child existed), `spid=1` is the main
        process from `InstanceMetadata`, and `spid>=2` are exec'd
        children (Phase 3+).  Spids are Registry-assigned,
        monotonic, and never recycled within an operation; the
        kernel PID (when needed for debugging) lives inside the
        per-type `data` payload.

        **System events** (`completion`) describe the operation as
        a whole, not a specific child process — they omit `spid`
        entirely.
      properties:
        id:
          type: integer
          format: int64
          description: |
            Sequential id assigned at append time.  Strictly
            increasing within a single operation's event log; gaps
            are possible (rare, after a transient producer-side
            serialization failure).  Use this with `Last-Event-Id` /
            `?since=` to resume a dropped SSE stream.
          example: 42
        ts:
          type: string
          format: date-time
          description: UTC wall-clock time when the event was emitted.
          example: "2026-06-08T20:00:00.123456789Z"
        spid:
          type: integer
          minimum: 0
          description: |
            Spawned Process ID — present on process-scoped events
            (`init`, `spawn`, `stdin`, `stdout`, `stderr`, `exit`,
            `truncated`, `size_cap`, `network`, `shutdown`, `inspect`, `file_upload`).
            Absent on operation-scoped system events
            (`completion`), which don't tie to a specific child.
          example: 1
        type:
          $ref: '#/components/schemas/OperationEventType'
        data:
          description: |
            Per-type payload.  Clients should switch on `type` and
            validate `data` against the corresponding schema below.
          oneOf:
            - $ref: '#/components/schemas/EventDataInit'
            - $ref: '#/components/schemas/EventDataSpawn'
            - $ref: '#/components/schemas/EventDataStream'
            - $ref: '#/components/schemas/EventDataExit'
            - $ref: '#/components/schemas/EventDataTruncated'
            - $ref: '#/components/schemas/EventDataSizeCap'
            - $ref: '#/components/schemas/EventDataNetwork'
            - $ref: '#/components/schemas/EventDataShutdown'
            - $ref: '#/components/schemas/EventDataInspect'
            - $ref: '#/components/schemas/EventDataFileUpload'
            - $ref: '#/components/schemas/EventDataCompletion'

    OperationEventType:
      type: string
      enum:
        - init
        - spawn
        - stdin
        - stdout
        - stderr
        - exit
        - truncated
        - size_cap
        - network
        - shutdown
        - inspect
        - file_upload
        - completion
      description: |
        Lifecycle category for the event.

        System events (operation-scoped, no `spid`, always last):
          * `completion` — emitted once at terminal state.  Carries
            the final operation status, the result image uuid (if
            any), the error message (if any), and rollups for the
            log/image artifacts.  Always the last event in the log.

        Service events (always emitted, never dropped by the size
        cap):
          * `init` — emitted first; operation-level startup snapshot.
          * `spawn` — emitted when a process starts; payload is the
            spawn parameters.
          * `exit` — emitted once per process when it exits; carries
            exit code, signal, timed_out flag, and resource usage.
          * `truncated` — emitted on stream EOF if a per-stream
            byte cap was crossed during the stream's lifetime.
          * `size_cap` — emitted once if the operation's overall
            event log approached its size cap; subsequent stream
            events get dropped, service events continue.
          * `network` — per-interface counters plus the configured
            network state.  Emitted at the end of the network setup
            phase; absent for network-less operations.
          * `inspect` — guest RPC request metadata and result, with `spid=0`.
            Includes reads and writes, but never their contents.
          * `file_upload` — terminal publication result, with `spid=0`.
            Includes source UUID, destination, flags, and bytes received.
          * `shutdown` — emitted last; the operation is about to
            wind down.

        Stream events (subject to BOTH the per-stream `truncate_at`
        cap from `EventDataSpawn` AND the overall size cap):
          * `stdin` — bytes written into the process's stdin.
          * `stdout` / `stderr` — chunks the process wrote to its
            respective stream.

    EventDataInspect:
      type: object
      description: |
        Metadata for a guest inspect RPC. Init emits a started/completed pair
        with the same request_id. Event IDs order the starts independently of
        completion order. A returned handle links subsequent reads, writes,
        finish, close, and file_upload events. All events use spid=0.
        Request parameters are recorded even when the method rejects them.
        A successful open/upload only allocates a handle; it does not complete
        the transfer. Read events report RPC bytes, not HTTP client receipt.
        File contents, directory listings, and grep matches are never recorded.
        Events are flushed to the journal and bypass the stream size cap.
        A missing completion can indicate an interrupted or lost event.
        These records support a future replay implementation; replay is not automatic.
      required: [request_id, method, phase]
      oneOf:
        - required: [params]
          properties:
            phase:
              enum: [started]
        - required: [status, error]
          properties:
            phase:
              enum: [completed]
      properties:
        request_id:
          type: string
          description: Opaque identifier shared by the request and result events.
        method:
          type: string
          enum: [stat, list, open, archive, grep, read, close, upload, write, finish]
        phase:
          type: string
          enum: [started, completed]
        params:
          $ref: '#/components/schemas/EventInspectParameters'
        status:
          type: string
          enum: [success, error, cancelled, timeout]
        error:
          type: string
          nullable: true
          description: Error category only; null on success. No exception text or file contents.
        handle:
          type: string
          description: Present after a successful open, archive, grep, or upload.
        bytes:
          type: integer
          format: int64
          minimum: 0
          description: Bytes returned by a successful read.
        eof:
          type: boolean
          description: Present after a successful read; true at the end of its stream.

    EventInspectParameters:
      type: object
      description: |
        Parameters for the method named in EventDataInspect. Path methods
        (stat/list/open/archive/grep/upload) record path. Grep also records options.
        Upload records file_uuid, unpack, replace, and merge. Read/write record
        handle, offset, and size; write size is the input chunk length, not an
        acknowledgement. Close/finish record handle. Binary payloads are excluded.
      properties:
        path:
          type: string
        file_uuid:
          $ref: '#/components/schemas/UUIDSchema'
        unpack:
          type: boolean
        replace:
          type: boolean
        merge:
          type: boolean
        handle:
          type: string
        offset:
          type: integer
          format: int64
        size:
          type: integer
        options:
          type: object
          required: [patterns, globs, case, max_count, max_total, before, after]
          properties:
            patterns:
              type: array
              nullable: true
              items:
                type: string
            globs:
              type: array
              nullable: true
              items:
                type: string
            case:
              type: string
            max_count:
              type: integer
            max_total:
              type: integer
            before:
              type: integer
            after:
              type: integer

    EventDataFileUpload:
      type: object
      description: |
        Init emits this event once after publication or cleanup of an accepted
        upload. It is emitted even if the host disconnects or Finish loses its
        response. A rejected upload has only its inspect request/result pair.
        Success means publication finished. Error or cancellation can leave a
        partially applied merge, as specified by the upload endpoint.
        The event contains metadata only, uses spid=0, bypasses the stream size
        cap, and is flushed before shutdown. Recording does not extend the
        source file's TTL or guarantee its availability for future replay.
      required: [handle, file_uuid, path, unpack, replace, merge, bytes, status, error]
      properties:
        handle:
          type: string
        file_uuid:
          $ref: '#/components/schemas/UUIDSchema'
        path:
          type: string
          description: Clean absolute destination path.
        unpack:
          type: boolean
        replace:
          type: boolean
        merge:
          type: boolean
        bytes:
          type: integer
          format: int64
          minimum: 0
          description: |
            Source bytes consumed from the upload pipe, including on failure.
            For an archive, counts compressed/source bytes, not extracted bytes.
            This is not a count of bytes successfully published to the destination.
        status:
          type: string
          enum: [success, error, cancelled, timeout]
        error:
          type: string
          nullable: true
          description: Error category only; null on success.

    EventDataInit:
      type: object
      description: |
        Operation-level startup snapshot.  `hostname`, `kernel`,
        `machine`, `boot_id` are best-effort — omitted if the
        environment couldn't provide them.
      required: [started_at, runtime_path, verbose, init_pid]
      properties:
        started_at:
          type: string
          format: date-time
          example: "2026-06-08T20:00:00.000000000Z"
        runtime_path:
          type: string
          description: Internal runtime directory for the operation.
          example: "/run/contreeinitd"
        verbose:
          type: boolean
          example: false
        init_pid:
          type: integer
          description: PID of the operation's init process.
          example: 1
        hostname:
          type: string
          example: "vm-abc123"
        kernel:
          type: string
          description: "uname release + version, space-separated."
          example: "6.10.0-generic #1 SMP PREEMPT"
        machine:
          type: string
          example: "x86_64"
        boot_id:
          type: string
          description: "Operation-unique boot identifier."
          example: "5e0a3f24-7c2d-4f50-8e1d-9b3c8d7e6a4f"

    EventDataSpawn:
      type: object
      description: |
        Process spawn parameters.  `env` values for keys ending in
        TOKEN/SECRET/PASSWORD/API_KEY/CREDENTIALS/AUTHORIZATION are
        replaced with the literal string `<MASKED>` before emission.
      required: [pid, command, args, shell, cwd, uid, gid, timeout, truncate_at]
      properties:
        resources_limits:
          $ref: '#/components/schemas/ProcessResourcesLimits'
        cpu_affinity:
          type: array
          items:
            type: integer
            minimum: 0
          description: Effective guest vCPU IDs available to this process tree.
        pid:
          type: integer
          minimum: 1
          description: PID assigned to the process.
          example: 4242
        command:
          type: string
          example: "/bin/sh"
        args:
          type: array
          items:
            type: string
          example: ["-c", "echo hi"]
        shell:
          type: boolean
          description: |
            If true, the command is wrapped in `<shell> -c <command>`
            (so the args / command may differ from the user's input).
          example: true
        cwd:
          type: string
          example: "/work"
        uid:
          type: integer
          example: 1000
        gid:
          type: integer
          example: 1000
        timeout:
          type: integer
          description: Per-process SIGKILL deadline in seconds.
          example: 60
        truncate_at:
          type: integer
          description: |
            Per-stream cap (bytes) above which stdout/stderr/stdin
            chunks stop being emitted and the stream's `truncated`
            event fires on EOF.
          example: 1048576
        env:
          type: object
          additionalProperties:
            type: string
          description: |
            Environment as passed to the process.  Values for
            secret-suffix keys are replaced with `<MASKED>`.
          example:
            PATH: "/usr/bin:/bin"
            DATABASE_PASSWORD: "<MASKED>"

    EventDataStream:
      type: object
      description: |
        Payload for `stdin` / `stdout` / `stderr` events.  Encoding
        is `ascii` when every byte is printable plus `\\n` / `\\r`
        / `\\t`; `base64` otherwise.  Chunks are at most a few KB
        each — the natural read granularity from a pipe.
      required: [value, encoding]
      properties:
        value:
          type: string
          example: "hello world\n"
        encoding:
          type: string
          enum: [ascii, base64]
          example: "ascii"
        truncated:
          type: boolean
          description: |
            Always `false` on per-chunk stream events.  When a stream
            crosses its per-stream cap a separate `truncated`-type
            event is emitted on EOF carrying the cumulative
            emitted/dropped totals.
          example: false

    EventDataExit:
      type: object
      description: |
        Process lifecycle close-out.  Carries the exit code OR the
        kill signal (signal = -1 means normal exit), the `timed_out`
        flag (true only when the process's per-process timeout fired
        — distinguishes from an external signal/kill), wall-clock
        duration, and a snapshot of resource usage.
      required: [pid, code, signal, timed_out, duration_ms, resources]
      properties:
        oom_killed:
          type: boolean
          default: false
          description: An OOM kill was observed in this process tree. Missing in older events.
        pid:
          type: integer
          minimum: 1
          description: PID of the process that just exited.
          example: 4242
        code:
          type: integer
          description: Exit code (0..255) if the process exited normally; -1 if killed by signal.
          example: 0
        signal:
          type: integer
          description: Signal number if killed by signal; -1 if normal exit.
          example: -1
        core_dump:
          type: boolean
          description: |
            True when the terminating signal produced a core dump.
            Absent in events recorded before the field was added —
            treat missing as false.
          example: false
        timed_out:
          type: boolean
          description: |
            True only if the process's own timeout fired the kill.
            An externally-driven kill (`signal` / `kill` / cancel)
            leaves `timed_out=false`.
          example: false
        duration_ms:
          type: integer
          format: int64
          description: Wall-clock time from spawn to exit.
          example: 1234
        resources:
          $ref: '#/components/schemas/EventResources'

    EventResources:
      type: object
      description: |
        Resource usage snapshot for the process.  Time fields are
        in microseconds; memory in kilobytes (max_rss_kb) or
        platform-specific units (shared_memory / unshared_memory).
        Some kernels populate fewer fields than others; expect
        zeroes for unsupported counters.
      required:
        - user_time_us
        - sys_time_us
        - max_rss_kb
        - shared_memory
        - unshared_memory
        - swaps
        - minor_faults
        - major_faults
        - voluntary_ctx_switches
        - involuntary_ctx_switches
        - block_input_ops
        - block_output_ops
        - ipc_msgs_sent
        - ipc_msgs_received
        - signals_received
      properties:
        user_time_us:
          type: integer
          format: int64
        sys_time_us:
          type: integer
          format: int64
        max_rss_kb:
          type: integer
          format: int64
        shared_memory:
          type: integer
          format: int64
        unshared_memory:
          type: integer
          format: int64
        swaps:
          type: integer
          format: int64
        minor_faults:
          type: integer
          format: int64
        major_faults:
          type: integer
          format: int64
        voluntary_ctx_switches:
          type: integer
          format: int64
        involuntary_ctx_switches:
          type: integer
          format: int64
        block_input_ops:
          type: integer
          format: int64
        block_output_ops:
          type: integer
          format: int64
        ipc_msgs_sent:
          type: integer
          format: int64
        ipc_msgs_received:
          type: integer
          format: int64
        signals_received:
          type: integer
          format: int64

    EventDataTruncated:
      type: object
      description: |
        Per-stream summary emitted once on stream EOF when the
        stream's `truncate_at` cap was crossed during its lifetime.
        Carries the final cumulative emitted/dropped totals (not
        partial numbers at cap-hit time).  Absent if the stream
        never crossed the cap.
      required: [stream, bytes_emitted, bytes_dropped]
      properties:
        stream:
          type: string
          enum: [stdin, stdout, stderr]
          example: "stdout"
        bytes_emitted:
          type: integer
          format: int64
          description: Bytes that were delivered before the cap kicked in.
          example: 1048576
        bytes_dropped:
          type: integer
          format: int64
          description: Bytes consumed from the producer but suppressed by the cap.
          example: 4096

    EventDataSizeCap:
      type: object
      description: |
        Emitted at most once per operation when the cumulative
        event-log size approached its budget.  After this marker,
        further stream events (`stdin` / `stdout` / `stderr`) are
        dropped; service events continue so the lifecycle stays
        observable.
      required: [limit_bytes, file_size]
      properties:
        limit_bytes:
          type: integer
          format: int64
          description: Size budget at which dropping kicked in.
          example: 104857600
        file_size:
          type: integer
          format: int64
          description: Approximate cumulative event-log size at cap-hit.
          example: 104800000

    EventDataNetwork:
      type: object
      description: |
        Per-interface counters plus the configured network state.
        Emitted once at the end of the network setup phase, so the
        counters represent the initial baseline.  Absent entirely
        for network-less operations.
      required: [interfaces]
      properties:
        interfaces:
          type: array
          items:
            $ref: '#/components/schemas/NetworkInterface'
        configured:
          type: object
          description: |
            Subset of network params that were applied — empty keys
            are omitted, so the object only carries what was
            requested.
          properties:
            ip4:
              type: string
              example: "10.0.0.5/24"
            ip4_gw:
              type: string
              example: "10.0.0.1"
            ip6:
              type: string
              example: "fc10:c0::33/64"
            ip6_gw:
              type: string
              example: "fc10:c0::1"
            gw_mac:
              type: string
              description: "Gateway MAC address."
              example: "ee:d0:a7:48:b5:98"
            nameserver:
              type: string
              example: "8.8.8.8"
          additionalProperties: false
        error:
          type: string
          description: |
            Set if the per-interface counter read failed;
            `interfaces` then holds an empty list.  Best-effort —
            failure does not block shutdown.

    NetworkInterface:
      type: object
      required:
        - name
        - rx_bytes
        - rx_packets
        - rx_errs
        - rx_drop
        - tx_bytes
        - tx_packets
        - tx_errs
        - tx_drop
      properties:
        name:
          type: string
          example: "eth0"
        rx_bytes:
          type: integer
          format: int64
        rx_packets:
          type: integer
          format: int64
        rx_errs:
          type: integer
          format: int64
        rx_drop:
          type: integer
          format: int64
        tx_bytes:
          type: integer
          format: int64
        tx_packets:
          type: integer
          format: int64
        tx_errs:
          type: integer
          format: int64
        tx_drop:
          type: integer
          format: int64

    EventDataShutdown:
      type: object
      description: |
        Stream-terminating marker emitted right before the operation
        winds down.  Distinct from the `network` event so consumers
        can recognize a clean shutdown without parsing payload-
        specific data.
      required: [stopped_at, reason]
      properties:
        stopped_at:
          type: string
          format: date-time
          example: "2026-06-08T20:01:34.567890123Z"
        reason:
          type: string
          enum: [job_complete, timeout, spawn_failed, signal]
          description: |
            Short categorical reason for the shutdown:
              * `job_complete` — process exited normally;
              * `timeout` — the operation timeout fired;
              * `spawn_failed` — the process couldn't be started;
              * `signal` — terminated by an external signal.
            Additional categories may be added.

    EventDataCompletion:
      type: object
      description: |
        Terminal system-event payload, emitted once when the
        operation reaches one of `SUCCESS`, `FAILED`, `CANCELLED`.
        Carries the operation outcome and rollup counters for the
        log + image artifacts.  Always the last event in the log;
        the event itself has no `spid` (operation-scoped, not
        process-scoped).
      required: [status, duration_ms]
      properties:
        status:
          type: string
          enum: [SUCCESS, FAILED, CANCELLED]
          description: Terminal operation status.
        result_image_uuid:
          type: string
          format: uuid
          nullable: true
          description: |
            UUID of the result image the operation produced.
            Present on every SUCCESS that persists an image — for
            runs that wrote no new layer, this is the image UUID the
            operation was spawned from (per the spec).  Distinct
            from the spec uuid only when persist produced a new
            image.  ``null`` for disposable runs (no image was
            persisted at all) and for FAILED / CANCELLED outcomes.
          example: "019eef27-7ecb-7771-8184-aaf5fa596ce2"
        error:
          type: string
          nullable: true
          description: |
            Short human-readable error message when ``status`` is
            ``FAILED`` or ``CANCELLED``.  ``null`` on success.
          example: "spawn failed: exec /run/entrypoint: no such file"
        duration_ms:
          type: integer
          format: int64
          minimum: 0
          description: Wall-clock duration of the handler in milliseconds.
          example: 4327
        image_size_bytes:
          type: integer
          format: int64
          minimum: 0
          description: |
            Size of the result image's runtime layer in bytes.
            ``0`` for failed/cancelled operations and for
            disposables (no image persisted).
          example: 134217728
        consumed_cpu:
          type: number
          nullable: true
          description: Total CPU time consumed by the operation, in seconds; null when unmeasured.
        consumed_memory:
          type: integer
          nullable: true
          description: Peak resident memory used by the operation's execution environment, in KiB; null when unmeasured.

security:
  - IAMBearerAuth: [ ]
    IAMProjectHeader: [ ]