Skip to content

clabe.server

Serve a run over HTTP: a snapshot, a resumable Server-Sent Events stream, answers and commands, described by OpenAPI (/openapi.json); plus a thin Python client.

RunClient

RunClient(
    base_url: str,
    *,
    token: str | None = None,
    name: str = "remote",
    timeout: float = 10.0,
)

Talks to a served run.

Parameters:

Name Type Description Default
base_url str

The server's root URL, e.g. http://localhost:8090.

required
token str | None

The shared token, when the server requires one.

None
name str

Recorded as the client in answers and commands.

'remote'
timeout float

Seconds to wait for a non-streaming request.

10.0
Source code in src/clabe/server/_client.py
def __init__(self, base_url: str, *, token: str | None = None, name: str = "remote", timeout: float = 10.0) -> None:
    self.base_url = base_url.rstrip("/")
    self.name = name
    self.timeout = timeout
    self._session = requests.Session()
    if token:
        self._session.headers["Authorization"] = f"Bearer {token}"

info

info() -> ServerInfo

The server's identity and its run.

Source code in src/clabe/server/_client.py
def info(self) -> ServerInfo:
    """The server's identity and its run."""
    response = self._session.get(self._url("/info"), timeout=self.timeout)
    response.raise_for_status()
    return ServerInfo.model_validate(response.json())

state

state() -> RunState

A snapshot of the run.

Source code in src/clabe/server/_client.py
def state(self) -> RunState:
    """A snapshot of the run."""
    response = self._session.get(self._url("/state"), timeout=self.timeout)
    response.raise_for_status()
    return RunState.model_validate(response.json())

answer

answer(prompt_id: str, value: Any) -> CommandResult

Answers an open prompt.

Source code in src/clabe/server/_client.py
def answer(self, prompt_id: str, value: Any) -> CommandResult:
    """Answers an open prompt."""
    return self._post(f"/prompts/{prompt_id}/answer", {"value": value, "client": self.name})

back

back(step: str | None = None) -> CommandResult

Goes back to step; to the previous step (the state's back_target) when omitted.

Source code in src/clabe/server/_client.py
def back(self, step: str | None = None) -> CommandResult:
    """Goes back to ``step``; to the previous step (the state's ``back_target``) when omitted."""
    if step is None:
        return self._post("/back", {"client": self.name})
    return self._post(f"/steps/{step}/back", {"client": self.name})

retry

retry(step: str) -> CommandResult

Retries a failed step.

Source code in src/clabe/server/_client.py
def retry(self, step: str) -> CommandResult:
    """Retries a failed step."""
    return self._post(f"/steps/{step}/retry", {"client": self.name})

skip

skip(step: str) -> CommandResult

Skips an optional step.

Source code in src/clabe/server/_client.py
def skip(self, step: str) -> CommandResult:
    """Skips an optional step."""
    return self._post(f"/steps/{step}/skip", {"client": self.name})

forward

forward() -> CommandResult

Answers the open prompt with its earlier answer.

Source code in src/clabe/server/_client.py
def forward(self) -> CommandResult:
    """Answers the open prompt with its earlier answer."""
    return self._post("/forward", {"client": self.name})

close

close() -> CommandResult

Closes the finished run's session (its closing screen).

Source code in src/clabe/server/_client.py
def close(self) -> CommandResult:
    """Closes the finished run's session (its closing screen)."""
    return self._post("/close", {"client": self.name})

options

options(
    prompt_id: str,
    typed: str = "",
    *,
    item: str | None = None,
) -> list[str]

The options of an open autocomplete prompt for the text typed so far.

Source code in src/clabe/server/_client.py
def options(self, prompt_id: str, typed: str = "", *, item: str | None = None) -> list[str]:
    """The options of an open autocomplete prompt for the text typed so far."""
    params = {"q": typed} if item is None else {"q": typed, "item": item}
    response = self._session.get(self._url(f"/prompts/{prompt_id}/options"), params=params, timeout=self.timeout)
    response.raise_for_status()
    return list(response.json())

export

export() -> bytes

The run's logs and records so far, as a zip.

Source code in src/clabe/server/_client.py
def export(self) -> bytes:
    """The run's logs and records so far, as a zip."""
    response = self._session.get(self._url("/export"), timeout=self.timeout)
    response.raise_for_status()
    return response.content

report

report(comment: str = '') -> ReportInfo

Files an issue report with comment; returns what was saved.

Source code in src/clabe/server/_client.py
def report(self, comment: str = "") -> ReportInfo:
    """Files an issue report with ``comment``; returns what was saved."""
    response = self._session.post(
        self._url("/report"), json={"comment": comment, "client": self.name}, timeout=self.timeout
    )
    response.raise_for_status()
    return ReportInfo.model_validate(response.json())

abort

abort(reason: str = 'Aborted by user.') -> CommandResult

Aborts the run.

Source code in src/clabe/server/_client.py
def abort(self, reason: str = "Aborted by user.") -> CommandResult:
    """Aborts the run."""
    return self._post("/abort", {"reason": reason})

list_dir

list_dir(
    path: str | None = None,
    *,
    kind: str = "any",
    extensions: list[str] | None = None,
) -> DirListing

Lists a directory of the machine running the run.

Source code in src/clabe/server/_client.py
def list_dir(
    self, path: str | None = None, *, kind: str = "any", extensions: list[str] | None = None
) -> DirListing:
    """Lists a directory of the machine running the run."""
    body = {"path": path, "kind": kind, "extensions": extensions}
    response = self._session.post(self._url("/fs/list"), json=body, timeout=self.timeout)
    response.raise_for_status()
    return DirListing.model_validate(response.json())

events

events(
    after: int = 0,
    *,
    reconnect: bool = True,
    retry_delay: float = 0.5,
) -> Iterator[Event]

Follows the run's events from after; reconnects (resuming) when the stream drops, until the run ends.

Source code in src/clabe/server/_client.py
def events(self, after: int = 0, *, reconnect: bool = True, retry_delay: float = 0.5) -> Iterator[Event]:
    """Follows the run's events from ``after``; reconnects (resuming) when the stream drops, until the run ends."""
    last = after
    while True:
        try:
            for event in self._stream(last):
                last = event.seq
                yield event
                if event.type == "run_finished":
                    return
            return
        except (requests.ConnectionError, requests.exceptions.ChunkedEncodingError):
            if not reconnect:
                raise
            time.sleep(retry_delay)

AbortBody

Bases: BaseModel

Aborts the run.

AnswerBody

Bases: BaseModel

An answer to an open prompt.

ClientBody

Bases: BaseModel

Identifies who sends a command.

CommandResult

Bases: BaseModel

Outcome of an answer or a command: accepted, or rejected with a reason to show the user.

DirEntry

Bases: BaseModel

One entry of a listed directory.

DirListing

Bases: BaseModel

A listed directory.

ListDirBody

Bases: BaseModel

Lists a directory of the machine running the run (the remote path picker).

ServerInfo

Bases: BaseModel

Identity of the server and the run it serves.

SessionInfo

Bases: BaseModel

What a run is about, as far as known so far: the hub lists it as a session.

RunServer

RunServer(
    run: Run,
    *,
    host: str = "127.0.0.1",
    port: int = 8090,
    token: str | None = None,
)

Serves a run over HTTP (API + web UI) on a background thread.

Parameters:

Name Type Description Default
run Run

The run to serve.

required
host str

Interface to bind; 127.0.0.1 (default) keeps it local, 0.0.0.0 opens it to the LAN.

'127.0.0.1'
port int

Preferred port; the next free one is used when it is taken.

8090
token str | None

When set, every API request must carry it.

None
Source code in src/clabe/server/_server.py
def __init__(self, run: Run, *, host: str = "127.0.0.1", port: int = 8090, token: str | None = None) -> None:
    self.run = run
    self.host = host
    self.port = port
    self.token = token
    self._server: uvicorn.Server | None = None
    self._thread: threading.Thread | None = None
    self._logs: LogBuffer | None = None

url property

url: str

Where the run is served (with the token, when one is set).

Open to the LAN (0.0.0.0 or ::), it names this computer, so the address also works from other PCs.

start

start(timeout: float = 10.0) -> str

Starts serving (on the next free port if needed) and returns the URL.

Raises:

Type Description
ImportError

The web server (the frontend extra) is not installed.

Source code in src/clabe/server/_server.py
def start(self, timeout: float = 10.0) -> str:
    """Starts serving (on the next free port if needed) and returns the URL.

    Raises:
        ImportError: The web server (the ``frontend`` extra) is not installed.
    """
    require_web("Serving a run")
    import uvicorn

    from ._app import create_app

    self.port = free_port(self.host, self.port)
    self._logs = LogBuffer()  # the process' log records, for the web UI's Log pane (as the TUI's Logs pane)
    self._logs.attach()
    config = uvicorn.Config(
        create_app(self.run, token=self.token, logs=self._logs),
        host=self.host,
        port=self.port,
        log_level="warning",
        lifespan="off",
    )
    self._server = uvicorn.Server(config)
    self._thread = threading.Thread(target=self._server.run, name=f"clabe-server-{self.port}", daemon=True)
    self._thread.start()
    deadline = time.monotonic() + timeout
    while not self._server.started:
        if not self._thread.is_alive() or time.monotonic() > deadline:
            self._detach_logs()
            raise RuntimeError(f"The run server did not start on {self.host}:{self.port}.")
        time.sleep(0.02)
    logger.info("Serving run %s at %s", self.run.id, self.url)
    if announce := os.environ.get(ANNOUNCE_ENV):
        Path(announce).write_text(json.dumps({"port": self.port, "pid": os.getpid()}), encoding="utf-8")
    return self.url

stop

stop(timeout: float = 5.0) -> None

Stops serving; open event streams are closed.

Source code in src/clabe/server/_server.py
def stop(self, timeout: float = 5.0) -> None:
    """Stops serving; open event streams are closed."""
    self._detach_logs()
    if self._server is None:
        return
    self._server.should_exit = True
    if self._thread is not None:
        self._thread.join(timeout)
    self._server = None
    self._thread = None

create_app

create_app(
    run: Run,
    *,
    token: str | None = None,
    static_dir: Path | None = STATIC_DIR,
    logs: LogBuffer | None = None,
) -> FastAPI

Builds the API serving run.

Parameters:

Name Type Description Default
run Run

The run to serve.

required
token str | None

When set, every API request must carry it (Authorization: Bearer <token> or ?token=).

None
static_dir Path | None

Directory of the web UI to serve at / (a placeholder page when it is missing).

STATIC_DIR
logs LogBuffer | None

The process' log records to serve at /api/logs (attached by RunServer); none: an empty stream.

None
Source code in src/clabe/server/_app.py
def create_app(
    run: Run, *, token: str | None = None, static_dir: Path | None = STATIC_DIR, logs: LogBuffer | None = None
) -> FastAPI:
    """Builds the API serving ``run``.

    Args:
        run: The run to serve.
        token: When set, every API request must carry it (``Authorization: Bearer <token>`` or ``?token=``).
        static_dir: Directory of the web UI to serve at ``/`` (a placeholder page when it is missing).
        logs: The process' log records to serve at ``/api/logs`` (attached by `RunServer`); none: an empty stream.
    """
    logs = logs if logs is not None else LogBuffer()
    app = FastAPI(
        title="clabe run API",
        version=__version__,
        description="Observe and drive a clabe run: a snapshot, a resumable event stream, answers and commands.",
    )
    app.add_middleware(TokenCookies, token=token)
    api = APIRouter(prefix="/api", dependencies=[Depends(token_check(token))])

    @api.get("/info", response_model=ServerInfo)
    def info() -> ServerInfo:
        """Identity of the server and its run."""
        return ServerInfo(
            clabe_version=__version__,
            hostname=socket.gethostname(),
            run_id=run.id,
            workflow=run.workflow.name,
            status=run.status.value,
        )

    @api.get("/session", response_model=SessionInfo)
    def session() -> SessionInfo:
        """What the run is about so far: session id, subject, experimenter, repository, progress, start and end."""
        return _session_info(run)

    @api.get("/state", response_model=RunState)
    def state() -> RunState:
        """A snapshot of the run; follow the events after its ``last_seq``."""
        return run.state()

    @api.get("/events", response_class=EventSourceResponse)
    async def events(
        request: Request,
        after: int | None = Query(default=None, description="Only events after this sequence number."),
        last_event_id: str | None = Header(default=None),
    ) -> AsyncIterable[Event]:
        """The run's events as Server-Sent Events, from ``after`` (or ``Last-Event-ID``); ends after the run ends."""
        start = after if after is not None else int(last_event_id) if last_event_id and last_event_id.isdigit() else 0
        async for event in _event_stream(run, request, start):
            yield ServerSentEvent(data=event, id=str(event.seq), event=event.type)

    _add_log_route(api, run, logs)

    @api.post("/prompts/{prompt_id}/answer", response_model=CommandResult)
    def answer(prompt_id: str, body: AnswerBody) -> CommandResult:
        """Answers an open prompt; an invalid answer is rejected and the prompt stays open."""
        return _result(run.answer(prompt_id, body.value, client=body.client))

    @api.get("/prompts/{prompt_id}/media", response_class=FileResponse)
    def media(prompt_id: str) -> FileResponse:
        """The local file shown by a media prompt (an image or an HTML page); nothing else is served."""
        return FileResponse(_media_file(run, prompt_id))

    @api.post("/steps/{name}/back", response_model=CommandResult)
    def back(name: str, body: ClientBody | None = None) -> CommandResult:
        """Goes back to step ``name``: it and the steps depending on it run again."""
        return _result(run.go_back(name))

    @api.post("/steps/{name}/retry", response_model=CommandResult)
    def retry(name: str, body: ClientBody | None = None) -> CommandResult:
        """Retries step ``name`` after it failed."""
        return _result(run.retry(name, client=(body or ClientBody()).client))

    @api.post("/steps/{name}/skip", response_model=CommandResult)
    def skip(name: str, body: ClientBody | None = None) -> CommandResult:
        """Skips the optional step ``name``."""
        return _result(run.skip(name, client=(body or ClientBody()).client))

    _add_navigation_and_session_routes(api, run)

    @api.post("/abort", response_model=CommandResult)
    def abort(body: AbortBody | None = None) -> CommandResult:
        """Aborts the run."""
        return _result(run.abort((body or AbortBody()).reason))

    @api.post("/agui", response_class=StreamingResponse)
    async def agui(body: RunAgentInput, request: Request) -> StreamingResponse:
        """The run as an AG-UI agent: one turn follows the run until it needs the user (see ``clabe.server._agui``)."""
        return StreamingResponse(agui_stream(run, body, request, _event_stream), media_type="text/event-stream")

    @api.post("/fs/list", response_model=DirListing)
    def list_dir(body: ListDirBody) -> DirListing:
        """Lists a directory of the machine running the run (for remote path pickers)."""
        return _list_dir(body)

    app.include_router(api)
    _mount_ui(app, static_dir)
    return app

free_port

free_port(host: str, start: int, attempts: int = 50) -> int

The first port from start on which host can listen.

Source code in src/clabe/server/_server.py
def free_port(host: str, start: int, attempts: int = 50) -> int:
    """The first port from ``start`` on which ``host`` can listen."""
    for port in range(start, start + attempts):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
            try:
                probe.bind((host, port))
            except OSError:
                continue
            return port
    raise OSError(f"No free port in {start}..{start + attempts - 1} on {host}.")