Skip to content

clabe.daemon

The clabe daemon: one per PC, it lists experiment repositories, runs an experiment in its repository's own environment, and serves it (proxied under /run/) so each rig has one stable URL.

AttachBody

Bases: BaseModel

A run started on this machine outside the daemon (e.g. from a terminal), announcing itself.

Host

Host(
    settings: DaemonSettings,
    *,
    leased_by: Callable[[], str | None] = lambda: None,
)

Lists the configured repositories and runs one experiment at a time.

A run is started as clabe run <file> --frontend headless --serve in the repository's own environment (settings.command), bound to localhost with a token only the host knows; the daemon proxies it.

Source code in src/clabe/daemon/_host.py
def __init__(self, settings: DaemonSettings, *, leased_by: Callable[[], str | None] = lambda: None) -> None:
    self.settings = settings
    self._leased_by = leased_by
    self._lock = threading.Lock()
    self._current: _Launched | _Attached | None = None
    self._runs_dir = settings.runs_directory or Path(tempfile.gettempdir()) / "clabe-daemon"

repositories

repositories() -> list[RepositoryInfo]

The configured repositories.

Source code in src/clabe/daemon/_host.py
def repositories(self) -> list[RepositoryInfo]:
    """The configured repositories."""
    return [
        RepositoryInfo(name=r.display_name, path=str(r.path), exists=r.path.is_dir())
        for r in self.settings.find_repositories()
    ]

repository

repository(name: str) -> RepositoryConfig

The repository called name.

Source code in src/clabe/daemon/_host.py
def repository(self, name: str) -> RepositoryConfig:
    """The repository called ``name``."""
    for repository in self.settings.find_repositories():
        if repository.display_name == name:
            return repository
    raise HostError(f"No repository named {name!r}.", status=404)

experiments

experiments(name: str) -> ExperimentListing

The experiments a repository offers, listed in its own environment (clabe list --json).

Source code in src/clabe/daemon/_host.py
def experiments(self, name: str) -> ExperimentListing:
    """The experiments a repository offers, listed in its own environment (``clabe list --json``)."""
    repository = self.repository(name)
    if not repository.path.is_dir():
        raise HostError(f"{repository.path} does not exist.", status=404)
    command = self._command(repository, "list", MAIN_FILE, "--json")
    try:
        done = subprocess.run(
            command, cwd=repository.path, capture_output=True, text=True, timeout=LIST_TIMEOUT, check=False
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise HostError(f"Could not list the experiments of {name}: {exc}", status=502) from exc
    try:
        return ExperimentListing.model_validate_json(done.stdout)
    except ValidationError as exc:
        detail = (done.stderr or done.stdout).strip().splitlines()[-5:]
        raise HostError(f"`{' '.join(command)}` failed: {' / '.join(detail)}", status=502) from exc

launch

launch(body: LaunchBody) -> RunInfo

Starts body's experiment; refused while another run is going.

Source code in src/clabe/daemon/_host.py
def launch(self, body: LaunchBody) -> RunInfo:
    """Starts ``body``'s experiment; refused while another run is going."""
    repository = self.repository(body.repository)
    with self._lock:
        if self._current is not None and self._current.alive():
            raise HostError("A run is already going on this machine.", status=409)
        if (owner := self._leased_by()) is not None:
            raise HostError(f"This machine is in use by {owner}.", status=423)
        self._runs_dir.mkdir(parents=True, exist_ok=True)
        stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
        log = self._runs_dir / f"{stamp}-{repository.display_name}.log"
        announce = self._runs_dir / f"{stamp}-{repository.display_name}.json"
        token = secrets.token_urlsafe(24)
        port = free_port("127.0.0.1", self.settings.port + 21)
        args = ["run", body.file, "--frontend", "headless", "--serve", "--host", "127.0.0.1"]
        args += ["--port", str(port), f"--token={token}", "--single-session"]  # "=": a token may start with "-"
        if body.experiment:
            args += ["--experiment-name", body.experiment]
        command = self._command(repository, *args, *self.settings.run_arguments)
        hidden = ("CLABE_TOKEN", "DAEMON_CLABE_TOKEN")  # the run gets its own token, not the daemon's
        env = {k: v for k, v in os.environ.items() if k not in hidden} | {
            ANNOUNCE_ENV: str(announce),
            "PYTHONUNBUFFERED": "1",
        }
        logger.info("Launching %s", " ".join(command))
        with log.open("w", encoding="utf-8") as output:
            process = subprocess.Popen(
                command,
                cwd=repository.path,
                stdin=subprocess.DEVNULL,
                stdout=output,
                stderr=subprocess.STDOUT,
                env=env,
                creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0,
            )
        self._current = _Launched(body, process, log, announce, token)
        return self._current.info()

current

current() -> _Launched | _Attached | None

The run launched (or attached) last, running or not.

Source code in src/clabe/daemon/_host.py
def current(self) -> "_Launched | _Attached | None":
    """The run launched (or attached) last, running or not."""
    return self._current

attach

attach(body: AttachBody) -> RunInfo

Follows a run started outside the daemon on this machine; refused while another run is going.

Source code in src/clabe/daemon/_host.py
def attach(self, body: AttachBody) -> RunInfo:
    """Follows a run started outside the daemon on this machine; refused while another run is going."""
    with self._lock:
        current = self._current
        again = isinstance(current, _Attached) and current.body.pid == body.pid
        if current is not None and current.alive() and not again:
            raise HostError("A run is already going on this machine.", status=409)
        if (owner := self._leased_by()) is not None:
            raise HostError(f"This machine is in use by {owner}.", status=423)
        self._current = _Attached(body)
        logger.info("Following %s (pid %s), started from a terminal", body.repository, body.pid)
        return self._current.info()

detach

detach(pid: int) -> None

Stops following the run of process pid: it has ended.

Source code in src/clabe/daemon/_host.py
def detach(self, pid: int) -> None:
    """Stops following the run of process ``pid``: it has ended."""
    with self._lock:
        if isinstance(self._current, _Attached) and self._current.body.pid == pid:
            self._current.port = None

stop

stop(timeout: float = 10.0) -> RunInfo

Stops the current run's process (prefer aborting it through its API: it cleans up).

Source code in src/clabe/daemon/_host.py
def stop(self, timeout: float = 10.0) -> RunInfo:
    """Stops the current run's process (prefer aborting it through its API: it cleans up)."""
    current = self._current
    if isinstance(current, _Attached):
        raise HostError("This run was started from a terminal: abort it (POST /run/api/abort).", status=409)
    if current is None or current.process.poll() is not None:
        raise HostError("No run is going.", status=409)
    current.process.terminate()
    deadline = time.monotonic() + timeout
    while current.process.poll() is None and time.monotonic() < deadline:
        time.sleep(0.1)
    if current.process.poll() is None:
        current.process.kill()
    return current.info()

info

info() -> HostInfo

Who the host is and what it runs.

Source code in src/clabe/daemon/_host.py
def info(self) -> HostInfo:
    """Who the host is and what it runs."""
    import socket

    from .. import __version__

    current = self._current
    run = current.info(tail=0) if current is not None else None
    busy = run is not None and run.status != "exited"
    owner = self._leased_by()
    status = "busy" if busy else "leased" if owner is not None else "idle"
    return HostInfo(
        hostname=socket.gethostname(), clabe_version=__version__, status=status, run=run, leased_by=owner
    )

busy

busy() -> bool

Whether a run launched (or attached) here is going.

Source code in src/clabe/daemon/_host.py
def busy(self) -> bool:
    """Whether a run launched (or attached) here is going."""
    return self._current is not None and self._current.alive()

HostError

HostError(message: str, status: int = 400)

Bases: Exception

A request the host cannot honour; status is the HTTP status to answer with.

Source code in src/clabe/daemon/_host.py
def __init__(self, message: str, status: int = 400) -> None:
    super().__init__(message)
    self.status = status

HostInfo

Bases: BaseModel

Who the host is and whether it is busy.

LaunchBody

Bases: BaseModel

Which experiment to run.

RepositoryInfo

Bases: BaseModel

A configured repository.

RunInfo

Bases: BaseModel

The run the host launched last.

DaemonSettings

Bases: EnvSettings

Settings of clabe daemon run, from environment variables only (DAEMON_CLABE_<FIELD>, e.g. DAEMON_CLABE_TOKEN). Every setting has a default; a rig usually needs none.

Repositories are found under repository_roots: every folder right under a root with a main.py and a pyproject.toml depending on aind-clabe. List others (any layout) in repositories. Lists are written a;b or as JSON:

setx DAEMON_CLABE_REPOSITORY_ROOTS "C:/git;D:/experiments"
setx DAEMON_CLABE_REPOSITORIES "C:/somewhere/else/Aind.Experiment.Special"

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Keyword arguments, then the environment, then a .env file when the class names one.

Source code in src/clabe/settings.py
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """Keyword arguments, then the environment, then a ``.env`` file when the class names one."""
    return (init_settings, env_settings, dotenv_settings)

reports_path

reports_path() -> Path

Where this machine's issue reports wait for the hub (reports_directory, else reports_dir).

Source code in src/clabe/daemon/_settings.py
def reports_path(self) -> Path:
    """Where this machine's issue reports wait for the hub (``reports_directory``, else `reports_dir`)."""
    from ..reports import reports_dir

    return self.reports_directory or reports_dir()

find_repositories

find_repositories() -> list[RepositoryConfig]

The listed repositories, then those found under the roots (sorted); a name is used once.

Source code in src/clabe/daemon/_settings.py
def find_repositories(self) -> list[RepositoryConfig]:
    """The listed repositories, then those found under the roots (sorted); a name is used once."""
    found: dict[str, RepositoryConfig] = {}
    for repository in self.repositories:
        found.setdefault(repository.display_name, repository)
    for root in self.repository_roots:
        try:
            candidates = sorted(p for p in root.iterdir() if p.is_dir())
        except OSError:
            continue
        for path in candidates:
            if not is_experiment_repository(path):
                continue
            if path.name in found:
                if found[path.name].path.resolve() != path.resolve():
                    logger.warning("Ignoring %s: a repository named %s is already offered.", path, path.name)
                continue
            found[path.name] = RepositoryConfig(path=path)
    return list(found.values())

RepositoryConfig

Bases: BaseModel

An experiment repository the daemon can run experiments from: its workflows are those of its main.py.

display_name property

display_name: str

The repository's name in the UI and the API.

Worker

Worker(
    settings: DaemonSettings,
    *,
    busy: Callable[[], bool] = lambda: False,
)

Jobs, files and the lease of the worker role.

Source code in src/clabe/daemon/_worker.py
def __init__(self, settings: DaemonSettings, *, busy: Callable[[], bool] = lambda: False) -> None:
    self.settings = settings
    self._busy = busy
    self._pool = ThreadPoolExecutor(max_workers=settings.max_jobs, thread_name_prefix="clabe-job")
    self._jobs: dict[str, _Job] = {}
    self._read: deque[_Job] = deque(maxlen=50)  # finished jobs whose result was read: output still served
    self._lease: Lease | None = None
    self._expired: Lease | None = None  # the last lease that expired: its run may take the worker back first
    self._lock = threading.Lock()
    self.files_dir = settings.file_transfer_dir or Path(os.environ.get("TEMP", "/tmp")) / "clabe-worker"
    self.files_dir.mkdir(parents=True, exist_ok=True)

lease

lease() -> Lease | None

The current lease, if it has not expired.

Source code in src/clabe/daemon/_worker.py
def lease(self) -> Lease | None:
    """The current lease, if it has not expired."""
    with self._lock:
        if self._lease is not None and self._lease.expires_at <= _now():
            logger.warning("The lease of %s expired", self._lease.owner)
            self._expired, self._lease = self._lease, None
        return self._lease

take

take(request: LeaseRequest) -> Lease

Takes the worker for a run, or renews the lease it holds.

Source code in src/clabe/daemon/_worker.py
def take(self, request: LeaseRequest) -> Lease:
    """Takes the worker for a run, or renews the lease it holds."""
    current = self.lease()
    with self._lock:
        if current is not None and current.lease_id != request.lease_id:
            raise HTTPException(status_code=423, detail=f"In use by {current.owner}.")
        if current is None and self._busy():
            raise HTTPException(status_code=409, detail="This machine is running an experiment of its own.")
        kept = self._expired
        if current is None and kept is not None and kept.run_id is not None and kept.run_id != request.run_id:
            until = kept.expires_at + datetime.timedelta(seconds=self.settings.lease_grace)
            if _now() < until:
                raise HTTPException(
                    status_code=423,
                    detail=f"Kept for run {kept.run_id} of {kept.owner} until {until:%H:%M:%S} UTC (it may "
                    "reattach to its jobs).",
                )
        lease_id = current.lease_id if current is not None else secrets.token_urlsafe(16)
        expires = _now() + datetime.timedelta(seconds=request.ttl)
        self._lease = Lease(lease_id=lease_id, owner=request.owner, run_id=request.run_id, expires_at=expires)
        return self._lease

release

release(lease_id: str, *, stop_jobs: bool) -> None

Gives the worker back; stop_jobs stops the jobs still running (e.g. the run was aborted).

Source code in src/clabe/daemon/_worker.py
def release(self, lease_id: str, *, stop_jobs: bool) -> None:
    """Gives the worker back; ``stop_jobs`` stops the jobs still running (e.g. the run was aborted)."""
    with self._lock:
        if self._lease is None or self._lease.lease_id != lease_id:
            raise HTTPException(status_code=404, detail="No such lease.")
        run_id, self._lease, self._expired = self._lease.run_id, None, None
    if stop_jobs:
        for job in list(self._jobs.values()):
            if run_id is None or job.run_id == run_id:
                self.stop(job.job_id)

check_lease

check_lease(given: str | None) -> None

Refuses a request that does not carry the current lease (when there is one).

Source code in src/clabe/daemon/_worker.py
def check_lease(self, given: str | None) -> None:
    """Refuses a request that does not carry the current lease (when there is one)."""
    current = self.lease()
    if current is not None and given != current.lease_id:
        raise HTTPException(status_code=423, detail=f"In use by {current.owner}.")

repository

repository(name: str | None) -> RepositoryConfig | None

The repository called name (by default the first one offered).

Source code in src/clabe/daemon/_worker.py
def repository(self, name: str | None) -> RepositoryConfig | None:
    """The repository called ``name`` (by default the first one offered)."""
    repositories = self.settings.find_repositories()
    if name is None:
        return repositories[0] if repositories else None
    for repository in repositories:
        if repository.display_name == name:
            return repository
    raise HTTPException(status_code=404, detail=f"No repository named {name!r}.")

info

info(repository: str | None) -> WorkerInfo

The worker, as seen for repository.

Source code in src/clabe/daemon/_worker.py
def info(self, repository: str | None) -> WorkerInfo:
    """The worker, as seen for ``repository``."""
    config = self.repository(repository)
    root = config.path if config is not None else Path.cwd()
    python = environment_python(root) if config is not None else Path(sys.executable)
    lease = self.lease()
    return WorkerInfo(
        clabe_version=__version__,
        hostname=socket.gethostname(),
        repository=config.display_name if config is not None else None,
        working_dir=str(root.resolve()),
        python_executable=str(python if python.exists() else sys.executable),
        leased_by=lease.owner if lease is not None else None,
        os_name=os.name,
    )

submit

submit(submission: JobSubmission) -> JobResult

Starts a job in the background.

Source code in src/clabe/daemon/_worker.py
def submit(self, submission: JobSubmission) -> JobResult:
    """Starts a job in the background."""
    if not submission.cmd:
        raise HTTPException(status_code=422, detail="Empty command.")
    config = self.repository(submission.repository)
    cwd = submission.cwd or str(config.path if config is not None else Path.cwd())
    job = _Job(str(uuid.uuid4()), submission.cmd, cwd, submission.run_id)
    span = _tracer.start_span(
        "clabe.worker.job",
        context=propagate.extract(submission.trace_context),
        attributes={"clabe.job_id": job.job_id, "process.command_args": job.cmd, "process.working_directory": cwd},
    )
    job.future = self._pool.submit(self._run, job, span)
    self._jobs[job.job_id] = job
    logger.info("Job %s: %s (in %s)", job.job_id, job.cmd, cwd)
    return JobResult(job_id=job.job_id, status=JobStatus.RUNNING)

output

output(job_id: str, after: int) -> JobOutput

A job's output lines after line after (the last OUTPUT_LINES are kept).

Source code in src/clabe/daemon/_worker.py
def output(self, job_id: str, after: int) -> JobOutput:
    """A job's output lines after line ``after`` (the last `OUTPUT_LINES` are kept)."""
    job = self._jobs.get(job_id) or next((j for j in self._read if j.job_id == job_id), None)
    if job is None:
        raise HTTPException(status_code=404, detail=f"No job {job_id}.")
    return job.output(after)

result

result(job_id: str) -> JobResult

A job's state; a finished job is forgotten once its result is read (its last output lines are kept a little longer, for whoever follows them).

Source code in src/clabe/daemon/_worker.py
def result(self, job_id: str) -> JobResult:
    """A job's state; a finished job is forgotten once its result is read (its last output lines are kept a
    little longer, for whoever follows them)."""
    job = self._jobs.get(job_id)
    if job is None or job.future is None:
        raise HTTPException(status_code=404, detail=f"No job {job_id}.")
    if not job.future.done():
        return JobResult(job_id=job_id, status=JobStatus.RUNNING)
    del self._jobs[job_id]
    self._read.append(job)
    return job.future.result()

stop

stop(job_id: str, timeout: float = 10.0) -> JobResult

Stops a job's process: asks it to exit, then kills it.

Source code in src/clabe/daemon/_worker.py
def stop(self, job_id: str, timeout: float = 10.0) -> JobResult:
    """Stops a job's process: asks it to exit, then kills it."""
    job = self._jobs.get(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail=f"No job {job_id}.")
    job.stopped = True
    process = job.process
    if process is not None and process.poll() is None:
        process.terminate()
        try:
            process.wait(timeout)
        except subprocess.TimeoutExpired:
            process.kill()
    return JobResult(job_id=job_id, status=JobStatus.STOPPED)

jobs_of

jobs_of(run_id: str) -> list[JobSummary]

The jobs of run run_id not yet collected (running, or finished with an unread result).

Source code in src/clabe/daemon/_worker.py
def jobs_of(self, run_id: str) -> list[JobSummary]:
    """The jobs of run ``run_id`` not yet collected (running, or finished with an unread result)."""
    return [
        JobSummary(
            job_id=job.job_id,
            run_id=job.run_id,
            command=job.cmd,
            running=job.future is not None and not job.future.done(),
            submitted_at=job.submitted_at,
        )
        for job in list(self._jobs.values())
        if job.run_id == run_id
    ]

jobs

jobs() -> JobList

The jobs, running and finished (but not yet read).

Source code in src/clabe/daemon/_worker.py
def jobs(self) -> JobList:
    """The jobs, running and finished (but not yet read)."""
    running = [j.job_id for j in self._jobs.values() if j.future is not None and not j.future.done()]
    finished = [j.job_id for j in self._jobs.values() if j.future is not None and j.future.done()]
    return JobList(running=running, finished=finished)

upload

upload(name: str, data: bytes, overwrite: bool) -> FileInfo

Writes a file to the transfer directory.

Source code in src/clabe/daemon/_worker.py
def upload(self, name: str, data: bytes, overwrite: bool) -> FileInfo:
    """Writes a file to the transfer directory."""
    path = self._file(name)
    if len(data) > self.settings.max_file_size:
        raise HTTPException(status_code=413, detail=f"Larger than {self.settings.max_file_size} bytes.")
    if path.exists() and not overwrite:
        raise HTTPException(status_code=409, detail=f"{name} exists; upload with overwrite to replace it.")
    path.write_bytes(data)
    return _file_info(path)

download

download(name: str) -> Path

A file of the transfer directory, to send back.

Source code in src/clabe/daemon/_worker.py
def download(self, name: str) -> Path:
    """A file of the transfer directory, to send back."""
    path = self._file(name)
    if not path.is_file():
        raise HTTPException(status_code=404, detail=f"No file {name}.")
    return path

files

files() -> list[FileInfo]

The files of the transfer directory.

Source code in src/clabe/daemon/_worker.py
def files(self) -> list[FileInfo]:
    """The files of the transfer directory."""
    return sorted((_file_info(p) for p in self.files_dir.iterdir() if p.is_file()), key=lambda f: f.name)

delete

delete(name: str) -> None

Deletes a file of the transfer directory.

Source code in src/clabe/daemon/_worker.py
def delete(self, name: str) -> None:
    """Deletes a file of the transfer directory."""
    self.download(name).unlink()

delete_all

delete_all() -> list[str]

Deletes every file of the transfer directory; returns their names.

Source code in src/clabe/daemon/_worker.py
def delete_all(self) -> list[str]:
    """Deletes every file of the transfer directory; returns their names."""
    deleted = []
    for path in self.files_dir.iterdir():
        if path.is_file():
            try:
                path.unlink()
                deleted.append(path.name)
            except OSError as exc:
                logger.error("Could not delete %s: %s", path, exc)
    return deleted

create_daemon

create_daemon(
    settings: DaemonSettings, *, token: str | None = None
) -> FastAPI

The daemon's app with both roles: the host (runs started here) and the worker (jobs for runs elsewhere).

Source code in src/clabe/daemon/_app.py
def create_daemon(settings: DaemonSettings, *, token: str | None = None) -> FastAPI:
    """The daemon's app with both roles: the host (runs started here) and the worker (jobs for runs elsewhere)."""
    holder: list[Worker] = []
    host = Host(settings, leased_by=lambda: lease.owner if (lease := holder[0].lease()) else None)
    holder.append(Worker(settings, busy=host.busy))
    return create_daemon_app(host, token=token, worker=holder[0])

create_daemon_app

create_daemon_app(
    host: Host,
    *,
    token: str | None = None,
    static_dir: Path | None = STATIC_DIR,
    worker: Worker | None = None,
) -> FastAPI

Builds the daemon's app.

Parameters:

Name Type Description Default
host Host

The host role (repositories and runs).

required
token str | None

When set, every API call (the daemon's and the proxied run's) must carry it.

None
worker Worker | None

The worker role (jobs and files for runs hosted elsewhere), served under /api/worker.

None
static_dir Path | None

The web UI, served at / (the daemon's page) and /run/ (the run's page).

STATIC_DIR
Source code in src/clabe/daemon/_app.py
def create_daemon_app(
    host: Host, *, token: str | None = None, static_dir: Path | None = STATIC_DIR, worker: Worker | None = None
) -> FastAPI:
    """Builds the daemon's app.

    Args:
        host: The host role (repositories and runs).
        token: When set, every API call (the daemon's and the proxied run's) must carry it.
        worker: The worker role (jobs and files for runs hosted elsewhere), served under ``/api/worker``.
        static_dir: The web UI, served at ``/`` (the daemon's page) and ``/run/`` (the run's page).
    """
    app = FastAPI(
        title="clabe daemon API",
        version=__version__,
        description="Run experiments on this machine: list repositories and experiments, launch one, and reach the "
        "run's own API under /run/api.",
    )
    app.add_middleware(TokenCookies, token=token)
    check = token_check(token)
    api = APIRouter(prefix="/api/daemon", dependencies=[Depends(check)])

    reports_directory = host.settings.reports_path()

    @api.get("/info", response_model=HostInfo)
    def info() -> HostInfo:
        """The machine, its clabe version, whether it is running an experiment, and its reports waiting."""
        return host.info().model_copy(update={"reports_waiting": count_reports(reports_directory)})

    @api.get("/repositories", response_model=list[RepositoryInfo])
    def repositories() -> list[RepositoryInfo]:
        """The experiment repositories this machine offers."""
        return host.repositories()

    @api.get("/repositories/{name}/experiments", response_model=ExperimentListing)
    def experiments(name: str) -> ExperimentListing:
        """The experiments of a repository (listed in its own environment; may take a while the first time)."""
        return _guarded(lambda: host.experiments(name))

    @api.post("/runs", response_model=RunInfo)
    def launch(body: LaunchBody) -> RunInfo:
        """Starts an experiment; 409 while another one runs. Follow it under /run/."""
        return _guarded(lambda: host.launch(body))

    _attach_routes(api, host)
    _report_routes(api, reports_directory)

    @api.get("/runs/current", response_model=RunInfo | None)
    def current() -> RunInfo | None:
        """The run launched last (running or not), with the end of its output."""
        launched = host.current()
        return launched.info() if launched is not None else None

    @api.post("/runs/current/stop", response_model=RunInfo)
    def stop() -> RunInfo:
        """Stops the current run's process. Prefer aborting it (POST /run/api/abort): that lets it clean up."""
        return _guarded(host.stop)

    app.include_router(api)
    if worker is not None:
        app.include_router(worker_router(worker, check))
    client = httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=None))

    @app.get("/run", include_in_schema=False)
    def run_root(request: Request) -> RedirectResponse:
        """The run's page needs the trailing slash (its links are relative)."""
        query = f"?{request.url.query}" if request.url.query else ""
        return RedirectResponse(f"/run/{query}")

    @app.api_route("/run/{path:path}", methods=["GET", "POST"], include_in_schema=False)
    async def proxy(path: str, request: Request) -> Response:
        """The current run's server: its web UI and (with the daemon's token) its API."""
        if path.startswith("api/"):
            await check(request)
        return await _proxy(host, client, path, request)

    if static_dir is not None and (static_dir / "index.html").is_file():
        app.mount("/", StaticFiles(directory=static_dir, html=True), name="ui")
    else:

        @app.get("/", response_class=HTMLResponse, include_in_schema=False)
        def placeholder() -> str:
            """A page pointing at the API when the web UI is not built."""
            return _PLACEHOLDER

    return app