Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,13 @@ async with ToolSession(mcp_url=mcp_url, role="alice@example.com") as session:
- **Tools:** `list_tools()` returns the tools the role may use as `EnvironmentTool`, the type a card's
`capabilities.tools` holds. Each `inputSchema` is the JSON Schema a model API takes as the tool's parameters.

## Running a website

`WebsiteEnvironment.serve()` runs a site with uvicorn on `PORT`. Install the `website` extra in the site's image
(`pip install 'agentenv-framework-protocol[website]'`: uvicorn and websockets): a WebSocket a page opens, which a mounted
`app` answers, needs a WebSocket library, and uvicorn without one serves the upgrade as a plain request, which the site
answers 404.

## Website readiness

`agentenv_protocol.website` is the one definition of whether a website env is healthy. A site's card advertises
Expand Down
6 changes: 6 additions & 0 deletions packages/agentenv-protocol/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ computer = [
"uvicorn>=0.30",
"websockets>=13",
]
# A website's own server: WebsiteEnvironment.serve() runs it with uvicorn, which needs a WebSocket library to answer a
# page's WebSocket at all; without one it serves the upgrade as a plain request, which the site answers 404.
website = [
"uvicorn>=0.30",
"websockets>=13",
]
# A macOS driver on MacOSDriver: ScreenCaptureKit captures the display and Quartz events send its input, through PyObjC.
macos = [
"pyobjc-framework-Quartz>=11; sys_platform == 'darwin'",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,11 +260,13 @@ def mount(self, app: Any) -> Any:
raise TypeError(f"{type(self).__name__} builds its own app with create_app(); set app = ... to serve more")

def serve(self) -> None:
"""Serve the site on ``PORT`` (8000 by default) with uvicorn, of the ``agent`` or ``app`` extra."""
"""Serve the site on ``PORT`` (8000 by default) with uvicorn, of the ``website`` extra, which brings the
WebSocket library uvicorn needs to answer a page's WebSocket rather than serve the upgrade as a plain request."""
try:
import uvicorn
except ImportError as e:
raise ImportError("WebsiteEnvironment.serve needs uvicorn: pip install 'uvicorn>=0.30'") from e
raise ImportError("WebsiteEnvironment.serve needs uvicorn: pip install "
"'agentenv-framework-protocol[website]'") from e
uvicorn.run(self.asgi or self.create_app(), host=os.environ.get("HOST", "0.0.0.0"),
port=int(os.environ.get("PORT", "8000")))

Expand Down
11 changes: 11 additions & 0 deletions tst/data/socket_website/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY agentenv-protocol /tmp/agentenv-protocol
RUN pip install --no-cache-dir "/tmp/agentenv-protocol[website]" && rm -rf /tmp/agentenv-protocol
COPY server.py /app/server.py
ENV PORT=8000
EXPOSE 8000
RUN useradd --create-home --uid 10001 appuser
USER appuser
CMD ["python", "server.py"]
33 changes: 33 additions & 0 deletions tst/data/socket_website/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""A website on WebsiteEnvironment whose mounted app answers a WebSocket, for integration-testing that a site installed
with the protocol's website extra serves a page's WebSocket through the gateway's site route: it sends its opening
messages on connect and answers each ping with a pong."""
from starlette.applications import Starlette
from starlette.routing import WebSocketRoute
from starlette.websockets import WebSocket, WebSocketDisconnect

from agentenv_protocol import environment_card
from agentenv_protocol.website import WebsiteEnvironment, website

OPENING = ["hello", "unread:2"]


async def socket(websocket: WebSocket) -> None:
await websocket.accept()
for message in OPENING:
await websocket.send_text(message)
try:
while True:
if await websocket.receive_text() == "ping":
await websocket.send_text("pong")
except WebSocketDisconnect:
pass


@environment_card(name="sockets")
@website(builtin_routes=False)
class Sockets(WebsiteEnvironment):
app = Starlette(routes=[WebSocketRoute("/socket", socket)])


if __name__ == "__main__":
Sockets().serve()
49 changes: 49 additions & 0 deletions tst/integration/env/gateway/gateway_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import create_mcp_http_client
from websockets.asyncio.client import connect as connect_websocket

# Each test deploys a real GatewayEnv + MCP servers on sandbox VMs
# (~5-15 min per test). Mark the entire module as slow.
Expand Down Expand Up @@ -387,6 +388,30 @@ def agentenv_website_env() -> WebsiteEnv:
return env


@pytest.fixture(scope="module")
def socket_website_env() -> WebsiteEnv:
"""A WebsiteEnvironment site whose mounted app answers a WebSocket, its image installing this checkout's protocol
package with the website extra, as a site's image installs the released one."""
package = REPO_ROOT / "packages" / "agentenv-protocol"
server_dir = TST_DATA_DIR / "socket_website"
with tempfile.TemporaryDirectory() as build_dir:
bd = Path(build_dir)
shutil.copytree(package, bd / "agentenv-protocol",
ignore=shutil.ignore_patterns("__pycache__", "tests", "examples", ".venv", ".pytest_cache"))
shutil.copy(server_dir / "server.py", bd / "server.py")
shutil.copy(server_dir / "Dockerfile", bd / "Dockerfile")
result = subprocess.run(
["docker", "build", "--platform", "linux/amd64", "-t", "agentenv-socket-website", str(bd)],
capture_output=True, text=True,
)
if result.returncode != 0:
raise RuntimeError(f"socket website build failed: {result.stderr}")
image = DockerImageArtifact.put(id="integ-test-socket-website-image", description="A website answering a WebSocket",
image_name="agentenv-socket-website")
return WebsiteEnv.put(id="integ-test-socket-website", backend_docker_image_artifact=image,
environment_name="sockets")


@pytest.fixture(params=[
pytest.param("scale", id="scale"),
pytest.param(
Expand Down Expand Up @@ -2576,6 +2601,30 @@ async def test_gateway_with_website_env_v1(agentenv_website_env, monkeypatch, tm
await env.close()


_SOCKET_OPEN_TIMEOUT_S = 60
_SOCKET_MESSAGE_TIMEOUT_S = 30


@pytest.mark.asyncio
@pytest.mark.integration
async def test_gateway_relays_a_website_environments_websocket(socket_website_env):
"""A WebSocket a WebsiteEnvironment's mounted app answers reaches a client through the gateway's site route: the
site's opening messages arrive on connect and a ping is answered. Without a WebSocket library in the site's image,
uvicorn serves the upgrade as a plain request and the site answers 404."""
env = Env.get(socket_website_env.id, version=socket_website_env.version)
try:
result = await env.deploy()
url = "ws" + result.gateway_url.removeprefix("http") + "/website/sockets/socket"
async with connect_websocket(url, open_timeout=_SOCKET_OPEN_TIMEOUT_S) as websocket:
opening = [await asyncio.wait_for(websocket.recv(), _SOCKET_MESSAGE_TIMEOUT_S) for _ in range(2)]
await websocket.send("ping")
answer = await asyncio.wait_for(websocket.recv(), _SOCKET_MESSAGE_TIMEOUT_S)
finally:
await env.close()
assert opening == ["hello", "unread:2"]
assert answer == "pong"


async def _load_shell_named_artifact(env, environment_name: str, monkeypatch, tmp_path) -> None:
"""Load a seed whose file name runs ``touch pwned`` if the shell parses it, from ``tmp_path`` so a run leaves it there."""
artifact = EnvironmentArtifact.put(
Expand Down
8 changes: 7 additions & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading