Skip to content

Host control (files, commands, power)

Your service runs inside WSL and needs to act on the machine hosting it: read a file under C:\Users\..., run a PowerShell command, open the native file picker, power the computer down at the end of the day. tempest_fastapi_sdk.hostbridge is that layer — the one that used to live as a separate service in every project that needed it.

Nothing here mounts itself: create_app does not know this module, and the router exists because a service asked for it.

uv add "tempest-fastapi-sdk"

The system, file and command surface needs no extra at all — it is the standard library and FastAPI. Reading PDFs needs [pdf-read], and reading them with layout and tables needs [pdf-layout].

This is a shell on that machine

Whoever reaches these methods runs commands as the host user and powers the machine off. Two things follow, and neither is optional: allowed_base_paths starts empty — denying every path until someone configures it — and make_hostbridge_router requires auth dependencies, refusing an empty list. The write side (commands, writes, deletes, power) is behind destructive=True and off by default.

The first read

HostBridge takes a HostBridgeConfig and nothing else. Everything is async, and whatever touches the disk or a process runs off the event loop:

import asyncio

from tempest_fastapi_sdk.hostbridge import HostBridge, HostBridgeConfig


async def main() -> None:
    bridge = HostBridge(
        HostBridgeConfig(allowed_base_paths=("/mnt/c/Users/me/Documents",)),
    )

    info = await bridge.host_info()
    print(info.computer_name, info.os_version)

    file = await bridge.read_text("C:\\Users\\me\\Documents\\notes.txt")
    print(file.size_bytes, file.content[:80])


asyncio.run(main())

Look at that path: it was written in Windows form and it worked. The bridge takes both — C:\Users\me and /mnt/c/Users/me — and normalizes before checking, through wslpath where it exists.

Order matters: resolve first, check second

The path is resolved (.. collapsed, symlinks followed) before it is compared against allowed_base_paths. Checking before resolving is the classic bug: /mnt/c/Users/me/../../../etc/passwd starts inside an allowed base and ends outside it.

Configuration from the environment

In a service, these options belong on Settings. Compose the mixin and splat the mapper — the field → argument translation lives in one place:

from tempest_fastapi_sdk.settings import HostBridgeSettings, ServerSettings
from tempest_fastapi_sdk.hostbridge import HostBridge, HostBridgeConfig


class Settings(HostBridgeSettings, ServerSettings):
    """Only what is specific to this service is declared here."""


settings = Settings()
bridge = HostBridge(HostBridgeConfig(**settings.hostbridge_kwargs()))

The environment variables are the field names themselves: HOST_ALLOWED_BASE_PATHS, HOST_POWERSHELL_BINARY, HOST_CMD_BINARY, HOST_COMMAND_TIMEOUT and HOST_MAX_FILE_READ_BYTES — plus HOST_BRIDGE_URL and HOST_BRIDGE_TOKEN, which point the service at a host agent (Backend in a container).

HOST_ALLOWED_BASE_PATHS has no permissive default

Empty denies everything. That is the safe direction to fail: a bridge that can run PowerShell should not also be able to read the whole disk because nobody remembered to configure it.

Exposing it over HTTP

make_hostbridge_router returns an APIRouter ready for include_router. It requires the dependency list — the signature is what forces the auth decision, instead of a warning in the docs:

from fastapi import Depends, FastAPI

from tempest_fastapi_sdk import make_token_dependency, register_exception_handlers
from tempest_fastapi_sdk.hostbridge import (
    HostBridge,
    HostBridgeConfig,
    make_hostbridge_router,
)

app = FastAPI()
register_exception_handlers(app)

bridge = HostBridge(
    HostBridgeConfig(allowed_base_paths=("/mnt/c/Users/me/Documents",)),
)

app.include_router(
    make_hostbridge_router(
        bridge,
        dependencies=[Depends(make_token_dependency("a-long-secret"))],
    )
)

That mounts the side that reads:

Method Route What it does
GET /system/info Machine name, user, OS, uptime
GET /system/files Read a text file
GET /system/files/list List a directory
GET /system/files/pdf Extract a PDF, page by page
POST /system/files/pick Open the native file picker

The side that writes — POST /system/exec, POST/DELETE /system/files, POST /system/{shutdown,restart,abort,lock,logoff} — only appears with destructive=True:

from fastapi import Depends

from tempest_fastapi_sdk import make_token_dependency
from tempest_fastapi_sdk.hostbridge import (
    HostBridge,
    HostBridgeConfig,
    make_hostbridge_router,
)

bridge = HostBridge(
    HostBridgeConfig(allowed_base_paths=("/mnt/c/Users/me/Documents",)),
)

router = make_hostbridge_router(
    bridge,
    dependencies=[Depends(make_token_dependency("a-long-secret"))],
    destructive=True,
)

Turn the destructive side on only with someone there to confirm

An assistant that runs commands without human confirmation is one that deletes the wrong folder exactly once. The pattern that works is holding the call until the user approves it, showing the exact arguments.

Errors, with a code

Every failure raises one of the SDK's envelope exceptions, so a service that already calls register_exception_handlers answers {detail, code, details} with no extra wiring — in PT-BR or en-US, per Accept-Language:

Code Status When
HOST_INVALID_PATH 400 Path outside the bases, or untranslatable
HOST_FILE_NOT_FOUND 404 No file there
HOST_FILE_TOO_LARGE 413 Over max_file_read_bytes
HOST_FILE_DECODE_FAILED 400 Bytes do not decode — a PDF or an image
HOST_COMMAND_FAILED 500 The command exited non-zero
HOST_COMMAND_TIMEOUT 504 The command ran past its timeout and was killed
HOST_UNAVAILABLE 503 The executable the action calls (PowerShell, wslpath, shutdown.exe) does not exist here — one missing is enough

HOST_UNAVAILABLE is what tells "this machine has no Windows host" apart from "the action failed": on a plain Linux container the caller degrades instead of reporting an error.

Reading a PDF from the host

import asyncio

from tempest_fastapi_sdk.hostbridge import HostBridge, HostBridgeConfig
from tempest_fastapi_sdk.pdf import PdfExtractorEnum


async def main() -> None:
    bridge = HostBridge(
        HostBridgeConfig(allowed_base_paths=("/mnt/c/Users/me/Documents",)),
    )
    document = await bridge.read_pdf(
        "C:\\Users\\me\\Documents\\contract.pdf",
        extractor=PdfExtractorEnum.LAYOUT,
    )
    for page in document.pages:
        print(page.page_number, len(page.tables), page.text[:60])


asyncio.run(main())

PdfExtractorEnum.TEXT is pypdf — fast, plain prose, [pdf-read]. PdfExtractorEnum.LAYOUT is pdfplumber, [pdf-layout]: slower, but it recovers columns and fills page.tables.

There is no OCR here

A scanned page is an image with no text layer: it comes back with text="" rather than being dropped — entry n is always page n. Check for it and route those files elsewhere; handing a model an empty page is how a confident answer gets invented about something nobody read.

Running commands

import asyncio

from tempest_fastapi_sdk.hostbridge import (
    CommandSchema,
    HostBridge,
    HostBridgeConfig,
)


async def main() -> None:
    bridge = HostBridge(HostBridgeConfig())
    result = await bridge.run_command(
        CommandSchema(command="Get-Date -Format o", shell="powershell", timeout=10),
    )
    print(result.return_code, result.stdout.strip(), result.duration_seconds)


asyncio.run(main())

Elevation (UAC) does not happen from here

A command that needs administrator rights fails. Wrap it through gsudo or a pre-created Task Scheduler entry on the Windows side.

Backend in a container

Inside a Docker container there is no powershell.exe and no /mnt/c: HostBridge answers HOST_UNAVAILABLE on every call. What can reach the host is the machine the container runs on — so the host runs an agent, and the service talks to it over HTTP:

container                              host (WSL)
┌──────────────────────────┐   HTTP    ┌────────────────────────────────┐
│ service                  │  X-Token  │ tempest hostbridge serve       │
│   RemoteHostBridge ──────┼──────────►│   make_hostbridge_router       │
│                          │           │     HostBridge → powershell.exe│
└──────────────────────────┘           └────────────────────────────────┘

RemoteHostBridge has the same methods, the same return schemas and raises the same exceptions as HostBridge. The router, a chat tool, a script: anything typed against HostBridgeProtocol takes either one without knowing which it got.

1. The agent, on the host

The SDK does not install uvicorn, so it comes along:

uv tool install "tempest-fastapi-sdk[cli-ops,pdf-read]" --with uvicorn

The token is required and has at least 32 characters; tempest secrets generate prints 64. Without a token, with one too short or without uvicorn, the command exits with code 2 before opening any port:

export HOST_BRIDGE_TOKEN="$(tempest secrets generate)"
export HOST_ALLOWED_BASE_PATHS='["/mnt/c/Users/me/Documents"]'
tempest hostbridge serve --host 172.17.0.1 --port 8765

Configuration comes from the environment (and a .env in the working directory) through HostBridgeSettings — the same HOST_* names as the in-process bridge — and each flag overrides its variable:

Flag Variable Default
--host HOST_BRIDGE_BIND 127.0.0.1
--port HOST_BRIDGE_PORT 8765
--token HOST_BRIDGE_TOKEN — (required)
--allow (repeatable) HOST_ALLOWED_BASE_PATHS [] (denies all)
--destructive / --read-only HOST_BRIDGE_DESTRUCTIVE --read-only
--powershell HOST_POWERSHELL_BINARY powershell.exe
--cmd HOST_CMD_BINARY cmd.exe
--command-timeout HOST_COMMAND_TIMEOUT 30
--locale — pt-BR

Prefer the variable to the --token flag

A command-line argument shows up in the process list (ps aux) for any user of the machine. The variable does not.

The agent serves /health/liveness without a token (for the healthcheck), the router under /system behind an X-Token compared in constant time, and no OpenAPI document.

2. Where to bind

Measured with Docker Engine 29.10 running inside WSL (Ubuntu 24.04):

  • 127.0.0.1 (the default) — the container does not reach it: connection refused. Only for a service running on the host itself.
  • 172.17.0.1, the docker0 bridge IP — reached by a container on the default network and by one on a user-defined network (the one a docker compose creates). Not visible to the local network. This is the recommendation.
  • 0.0.0.0 — reaches everything, other machines on the network included. Only with a firewall rule in front; the command warns when it starts this way.

The docker0 IP comes from ip -4 addr show docker0. On the container side, the name host.docker.internal does not resolve on Docker Engine until an extra_hosts line maps it to host-gateway — which points at exactly that IP:

services:
  api:
    image: my-service
    extra_hosts:
      - "host.docker.internal:host-gateway"
    environment:
      HOST_BRIDGE_URL: "http://host.docker.internal:8765"
      HOST_BRIDGE_TOKEN: "${HOST_BRIDGE_TOKEN}"

The token is the only thing between the network and a shell

With --destructive, whoever holds the token runs commands as the host user and powers the machine off. Keep the agent on docker0 or loopback, generate the token with tempest secrets generate and keep it out of the repository.

3. The service, in the container

The two new HostBridgeSettings fields — HOST_BRIDGE_URL and HOST_BRIDGE_TOKEN (SecretStr, never printed) — decide which bridge the service gets. hostbridge_from_settings returns a RemoteHostBridge when the URL is set and a HostBridge when it is not, so the same code runs on the host in development and in the container in production:

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI

from tempest_fastapi_sdk import make_token_dependency, register_exception_handlers
from tempest_fastapi_sdk.hostbridge import (
    hostbridge_from_settings,
    make_hostbridge_router,
)
from tempest_fastapi_sdk.settings import HostBridgeSettings, ServerSettings


class Settings(HostBridgeSettings, ServerSettings):
    """Only what is specific to the service lives here."""


settings = Settings()
bridge = hostbridge_from_settings(settings)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    yield
    await bridge.aclose()


app = FastAPI(lifespan=lifespan)
register_exception_handlers(app)
app.include_router(
    make_hostbridge_router(
        bridge,
        dependencies=[Depends(make_token_dependency("a-long-secret"))],
        destructive=True,
    )
)

HOST_BRIDGE_URL without HOST_BRIDGE_TOKEN does not boot: Settings() refuses it, because the agent would refuse every call. aclose() exists on both bridges — on HostBridge it does nothing — so the lifespan closes what it got without asking which.

Without Settings, construction is direct:

from tempest_fastapi_sdk.hostbridge import RemoteHostBridge

bridge = RemoteHostBridge(
    "http://host.docker.internal:8765",
    token="the-agent-secret-with-32-or-more-characters",
)

Errors, across the wire

Each failure the agent answers comes back as the same class HostBridge would raise, by the envelope's code — HOST_FILE_NOT_FOUND becomes HostFileNotFoundError, PDF_DECRYPT_FAILED becomes PdfDecryptError, and so on, with details preserved. Three situations belong to the wire, not the host:

Situation Exception Code Status
Agent down, port closed, connection dropped HostUnavailableError HOST_UNAVAILABLE 503
Agent refused the token (401/403) HostBridgeUnauthorizedError HOST_BRIDGE_UNAUTHORIZED 503
Unknown code — an unhandled error on the host, a write route on a --read-only agent (404), a proxy in between HostBridgeRemoteError HOST_BRIDGE_REMOTE_ERROR 502

A refused token becomes 503, not 401, on purpose: whoever receives the response is the service's end user, and a 401 would tell them their session expired. HostBridgeUnauthorizedError extends HostUnavailableError, so code that already degrades on HOST_UNAVAILABLE keeps degrading.

The error sentence is the agent's

The envelope carries detail, code and details, but not the values the sentence was built from (the path, the size, the time). A service with a catalog still translates every code whose sentence has no placeholder; the others arrive with the agent's sentence, in the agent's language (--locale).

Timeouts

A command runs on the host until its timeout (CommandSchema.timeout, or default_command_timeout) and the agent answers HOST_COMMAND_TIMEOUT. RemoteHostBridge waits that long plus a margin (timeout_margin, 10 s) before giving up, so the agent's answer arrives first. The file picker waits timeout_seconds plus the margin; reads, listings and PDFs use request_timeout (60 s). If the agent still does not answer, the call raises HostCommandTimeoutError with the seconds it waited.

Starting with the login: systemd --user

# ~/.config/systemd/user/tempest-hostbridge.service
[Unit]
Description=tempest hostbridge agent

[Service]
EnvironmentFile=%h/.config/tempest-hostbridge.env
ExecStart=%h/.local/bin/tempest hostbridge serve --host 172.17.0.1 --port 8765
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target

tempest-hostbridge.env holds HOST_BRIDGE_TOKEN=... and HOST_ALLOWED_BASE_PATHS=[...] (keep it chmod 600). If docker0 does not exist yet when the agent starts, the bind fails and Restart=on-failure tries again every 5 s. Enable it with systemctl --user daemon-reload && systemctl --user enable --now tempest-hostbridge.

Recap

  • HostBridge + HostBridgeConfig give you the whole surface; HostBridgeSettings is the same thing from the environment, via hostbridge_kwargs().
  • An empty allowed_base_paths denies everything, and a path is resolved before it is checked.
  • make_hostbridge_router requires auth by signature, and only mounts the write side with destructive=True.
  • Every failure carries a code — HOST_UNAVAILABLE says this machine has no host to control.
  • PDFs: [pdf-read] for text, [pdf-layout] for columns and tables, no OCR in either.
  • In a container: tempest hostbridge serve on the host (a 32+ character token, bound to docker0), RemoteHostBridge in the service — or hostbridge_from_settings with HOST_BRIDGE_URL + HOST_BRIDGE_TOKEN. Same methods, same exceptions; the wire adds HOST_BRIDGE_UNAUTHORIZED and HOST_BRIDGE_REMOTE_ERROR.