Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
web/node_modules/
web/dist/
21 changes: 21 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FROM mirror.gcr.io/library/node:22-slim@sha256:4b150b48b4116e2a22f2c39cc27025fbf4f153e2078fd3b14d159fdb5c7279da AS web
WORKDIR /web
COPY web/package.json web/package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY web/ ./
RUN npm run build

FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir "agentenv-framework-protocol>=0.1.466" "uvicorn>=0.30"
COPY site.py /app/site.py
COPY data /app/data
COPY --from=web /web/dist /app/web/dist
ENV PORT=8000
EXPOSE 8000
RUN useradd --create-home --uid 10001 appuser
USER appuser
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/.well-known/agent-env.json' % os.environ.get('PORT', '8000'), timeout=2)"
CMD ["python", "site.py"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**/node_modules
**/dist
**/__pycache__
**/.pytest_cache
**/.venv
.git
87 changes: 87 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Notes: a reference website/v1 site

Notes is a small notes app built on `agentenv_protocol.website.WebsiteEnvironment`. It is the reference site for the
`urn:agentenv:website/v1` server contract. Each user keeps their own notes and can create, edit, mark done and delete
them. The page shows the universe's time.

| File | What it is |
| --- | --- |
| `site.py` | The server: the `Notes` WebsiteEnvironment, its `@api` routes, and `serve()` on `PORT` (8000). |
| `data/seed.json` | The seed data: two users (`ann`, `ben`), their notes, and `current_user`, the acting user. |
| `web/` | A minimal Vite app (`index.html`, `src/main.js`, `src/style.css`). Its assets (`base: "./"`) and API calls are relative to the page, so it works at `/` and under the gateway's `/website/notes/` alike; opened at a path without its final slash, such as `/website/notes` or `/website/notes/index.html`, the page first reloads itself at its folder's address. |
| `Dockerfile` | The server image, built with this folder as its context: Node builds `web/`, then Python installs the released protocol (`agentenv-framework-protocol`) with uvicorn. It installs `curl`, which the gateway's compose health check runs against the card. |
| `env.toml` | The website env as a bundle entry. |

## What it exercises

- **Site declaration.** `@website(domains=["notes.test"], static="web/dist")`. The card advertises website/v1 with
the domains and every route by name.
- **Routes.** `list_users`, `sign_in`, `list_notes` (with an optional `?done=`), `create_note` (201), `get_note`,
`edit_note`, `toggle_note` and `delete_note`. Errors are raised as `NotFound`, `BadRequest` and `Unauthorized`.
- **Roles.** `all_notes` (`GET /api/admin/notes`) is declared with `roles=["admin"]`. It answers only a caller that
sends `AgentEnv-Role: admin` with `AgentEnv-Role-Key` equal to the container's `WEBSITE_ROLE_KEY`; any other caller
gets 403. The gateway passes on whatever role a browser sends, so without the key a page could claim `admin`; with no
`WEBSITE_ROLE_KEY` set, every caller is `default` and the route is closed.
- **Users.** `ApiContext.user` is the user in the signed session cookie. With no cookie, it is the acting user (the
data's `current_user`, which `acting_user()` returns), and `GET /api/session` signs that user in. `POST /api/sign-in` switches to another seeded
user. A user's notes are invisible to every other user, and another user's note answers 404.
- **State.** The site keeps its users and notes itself, starting from `data/seed.json`, and serves them through its
data hooks: `data/add` adds a part's records by id (a data part, or a file part by bytes or `file://`), `data/get`
exports them, and `data/reset` empties them. `data/get` is how agentenv reads what a task left the site with.
- **Time.** Notes are stamped with `self.now()`, which follows the gateway's clock once `clock/v1`'s `sync_time` names
it. The frontend reads `X-Universe-Now` from every API response into `universeNow()` and shows it in the header.
It uses this helper rather than `clock_patch=True`, so the page works the same against a server written without the
SDK.
- **Readiness.** website/v1's `ready`, through the card, says not ready (`@ready_check seeded`) until the site has
users, for example after a `data/reset` and before the next `data/add`. The site serves no health path.

## Run it

From this folder:

```bash
cd web && npm ci && npm run build && cd ..
PYTHONPATH=<repo>/packages/agentenv-protocol/src python site.py
```

Open http://localhost:8000. To work on the frontend, run `npm run dev` in `web/` while `site.py` runs; Vite proxies
`/api` to port 8000.

## Test it

```bash
python -m pytest packages/agentenv-protocol/tests/test_website_notes_example.py
```

The test imports `site.py`, runs the conformance checker, and checks sign-in, per-user notes, the admin-only route,
clock-synced timestamps, and the data plane's reset and seed load. It serves a stand-in page, so it needs no Vite
build.

## Build and verify the image

The build context is this folder; the image installs the released protocol, so it runs the SDK as published, while
the test above runs this repo's.

```bash
docker build -t notes-site .
docker run -d --name notes-site -p 18080:8000 notes-site
python -m agentenv_protocol.website.conformance http://localhost:18080 --clock-host host.docker.internal
curl -s http://localhost:18080/api/notes
```

Use `--clock-host` so the container can reach the checker's clock. The clock check leaves the server following a
clock that is gone once the check ends: later timestamps start from 2031 until the server is synced again, so restart
the container before using it.

## Register it

In a bundle, `env.toml` declares the env: copied to a bundle's `envs/notes/`, `agent-env bundle register <bundle>`
builds the image with that folder as its context. Its keys are `type`, `environment_name` and `backend_image`; domains
are not one of them, as they come from the card. Without a bundle:

```bash
agent-env env website put --id notes-site --server-dockerfile Dockerfile --server-docker-context .
```

Run it from this folder. `environment_name` comes from the card (`@environment_card(name="notes")`). The stored env
has a server image and no frontend image. Pass `--skip-validation` to register without deploying.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"current_user": "ann",
"users": [
{"id": "ann", "name": "Ann Lee"},
{"id": "ben", "name": "Ben Ortiz"}
],
"notes": [
{"id": 1, "owner": "ann", "title": "Buy milk", "body": "Oat, two cartons.", "done": false,
"created_at": "2026-01-05T09:00:00.000Z", "updated_at": "2026-01-05T09:00:00.000Z"},
{"id": 2, "owner": "ann", "title": "Book dentist", "body": "", "done": true,
"created_at": "2026-01-04T15:30:00.000Z", "updated_at": "2026-01-06T08:10:00.000Z"},
{"id": 3, "owner": "ben", "title": "Draft the quarterly report", "body": "Due Friday.", "done": false,
"created_at": "2026-01-03T11:00:00.000Z", "updated_at": "2026-01-03T11:00:00.000Z"}
]
}
3 changes: 3 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/env.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
type = "website"
environment_name = "notes"
backend_image = { dockerfile = "Dockerfile" }
208 changes: 208 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/site.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
"""Notes: the reference site of ``urn:agentenv:website/v1``, a small notes app on WebsiteEnvironment. Each user keeps
notes they create, edit, mark done and delete; a browser with no session is signed in as the acting user, the seed's
``current_user``, and can sign in as another seeded user. The site keeps its users and notes itself, behind one lock
since plain ``def`` handlers run in worker threads, starting from ``data/seed.json``, and serves them through the data plane (``data/get``, ``data/reset``, ``data/add``), as any
AgentEnvEnvironment does; it stamps each note with the universe's time. ``admin`` callers, as the gateway's
``AgentEnv-Role`` names them, can list every user's notes.

Run it with ``python site.py`` after building ``web/`` into ``web/dist``; it serves on ``PORT`` (8000)."""
from __future__ import annotations

import base64
import copy
import json
import threading
from pathlib import Path
from typing import Optional
from urllib.parse import unquote, urlparse

from pydantic import BaseModel

from agentenv_protocol import DataPart, FilePart, TextPart, add_data, environment_card, get_data, reset_data
from agentenv_protocol.website import (
ApiContext,
BadRequest,
NotFound,
Unauthorized,
WebsiteEnvironment,
api,
ready_check,
website,
)
from agentenv_protocol.website.clock import iso

NOTES = "notes"
USERS = "users"
SEED = Path(__file__).resolve().parent / "data" / "seed.json"


class NewNote(BaseModel):
title: str
body: str = ""


class NoteEdit(BaseModel):
title: Optional[str] = None
body: Optional[str] = None
done: Optional[bool] = None


class SignIn(BaseModel):
user: str


@environment_card(name="notes")
@website(domains=["notes.test"], static="web/dist")
class Notes(WebsiteEnvironment):
def __init__(self) -> None:
super().__init__()
self._lock = threading.Lock()
self.data: dict = json.loads(SEED.read_text(encoding="utf-8"))

def acting_user(self) -> Optional[str]:
with self._lock:
return self.data.get("current_user")

@ready_check
def seeded(self) -> bool:
"""The site is usable once it knows who may sign in."""
with self._lock:
return bool(self.data.get(USERS))

@reset_data
def reset(self) -> None:
with self._lock:
self.data = {}

@add_data
def add(self, parts: list) -> None:
"""Each part's JSON, its collections' records added by id and its other fields set, as the seed is."""
loaded = [_part_data(part) for part in parts]
with self._lock:
for data in loaded:
for key, value in data.items():
if isinstance(value, list):
kept = {record["id"]: record for record in self.data.get(key, [])}
kept.update({record["id"]: copy.deepcopy(record) for record in value})
self.data[key] = list(kept.values())
else:
self.data[key] = copy.deepcopy(value)

@get_data
def export(self) -> list:
with self._lock:
return [DataPart(data=copy.deepcopy(self.data))]

@api.get("/api/users", name="list_users")
def list_users(self) -> list:
"""The users a browser can sign in as."""
with self._lock:
return copy.deepcopy(self.data.get(USERS, []))

@api.post("/api/sign-in", name="sign_in")
def sign_in(self, body: SignIn, ctx: ApiContext) -> dict:
"""Sign the browser in as one of the site's users."""
with self._lock:
known = any(user["id"] == body.user for user in self.data.get(USERS, []))
if not known:
raise NotFound(f"no user {body.user!r}")
ctx.sign_in(body.user)
return {"user": ctx.user}

@api.get("/api/notes", name="list_notes")
def list_notes(self, ctx: ApiContext, done: Optional[bool] = None) -> list:
"""The signed-in user's notes, newest first; with ``done``, only those done or not."""
user = self._user(ctx)
with self._lock:
mine = [copy.deepcopy(n) for n in self.data.get(NOTES, [])
if n["owner"] == user and (done is None or n["done"] == done)]
return sorted(mine, key=lambda note: note["created_at"], reverse=True)

@api.post("/api/notes", name="create_note", status=201)
def create_note(self, note: NewNote, ctx: ApiContext) -> dict:
"""Add a note for the signed-in user, not done, created and updated now."""
owner, title, now = self._user(ctx), _title(note.title), iso(self.now())
with self._lock:
notes = self.data.setdefault(NOTES, [])
created = {"id": max((n["id"] for n in notes), default=0) + 1, "owner": owner, "title": title,
"body": note.body, "done": False, "created_at": now, "updated_at": now}
notes.append(created)
return copy.deepcopy(created)

@api.get("/api/notes/{note_id:int}", name="get_note")
def get_note(self, note_id: int, ctx: ApiContext) -> dict:
with self._lock:
return copy.deepcopy(self._note(note_id, ctx))

@api.patch("/api/notes/{note_id:int}", name="edit_note")
def edit_note(self, note_id: int, edit: NoteEdit, ctx: ApiContext) -> dict:
"""Change a note's title, body or done, and its ``updated_at``."""
fields = edit.model_dump(exclude_none=True)
if "title" in fields:
fields["title"] = _title(fields["title"])
now = iso(self.now())
with self._lock:
note = self._note(note_id, ctx)
note.update(fields, updated_at=now)
return copy.deepcopy(note)

@api.post("/api/notes/{note_id:int}/toggle", name="toggle_note")
def toggle_note(self, note_id: int, ctx: ApiContext) -> dict:
"""Mark a note done, or not done when it was."""
now = iso(self.now())
with self._lock:
note = self._note(note_id, ctx)
note.update(done=not note["done"], updated_at=now)
return copy.deepcopy(note)

@api.delete("/api/notes/{note_id:int}", name="delete_note")
def delete_note(self, note_id: int, ctx: ApiContext) -> dict:
with self._lock:
note = self._note(note_id, ctx)
self.data[NOTES] = [n for n in self.data[NOTES] if n is not note]
return {"deleted": note_id}

@api.get("/api/admin/notes", name="all_notes", roles=["admin"])
def all_notes(self) -> list:
"""Every user's notes, for an ``admin`` caller only."""
with self._lock:
return copy.deepcopy(self.data.get(NOTES, []))

def _user(self, ctx: ApiContext) -> str:
if ctx.user is None:
raise Unauthorized("sign in first")
return ctx.user

def _note(self, note_id: int, ctx: ApiContext) -> dict:
"""The signed-in user's note ``note_id``, read under the lock; another user's is as missing as one that
doesn't exist."""
note = next((n for n in self.data.get(NOTES, []) if n["id"] == note_id), None)
if note is None or note["owner"] != self._user(ctx):
raise NotFound(f"no note {note_id}")
return note


def _part_data(part) -> dict:
"""A part's JSON: a data part's data, a text part's text, or a file part's bytes or ``file://`` file."""
if isinstance(part, DataPart):
return part.data
if isinstance(part, TextPart):
return json.loads(part.text)
if isinstance(part, FilePart):
if getattr(part.file, "bytes", None) is not None:
return json.loads(base64.b64decode(part.file.bytes))
uri = urlparse(part.file.uri)
if uri.scheme == "file":
return json.loads(Path(unquote(uri.path)).read_text(encoding="utf-8"))
raise ValueError(f"Notes reads a file part by its bytes or a file:// URI, not {part.file.uri!r}")
raise ValueError(f"Notes can't read a {type(part).__name__}")


def _title(title: str) -> str:
if not title.strip():
raise BadRequest("a note needs a title", code="empty_title")
return title.strip()


if __name__ == "__main__":
Notes().serve()
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Notes</title>
<script>
if (!location.pathname.endsWith("/")) { const url = new URL(location.href); url.pathname = url.pathname.replace(/\/index\.html$/, "") + "/"; location.replace(url.href); }
</script>
</head>
<body>
<header class="bar">
<h1>Notes</h1>
<div class="who">
<label>Signed in as
<select id="user" aria-label="Signed-in user"></select>
</label>
<time id="universe-now" title="The universe's time, from X-Universe-Now"></time>
</div>
</header>
<main>
<form id="new-note" class="card">
<input id="new-title" name="title" placeholder="New note title" autocomplete="off" required />
<textarea id="new-body" name="body" placeholder="Details (optional)" rows="2"></textarea>
<button type="submit">Add note</button>
</form>
<nav class="filters" aria-label="Filter notes">
<button data-filter="all" class="active">All</button>
<button data-filter="open">Open</button>
<button data-filter="done">Done</button>
</nav>
<p id="error" role="alert" hidden></p>
<ul id="notes"></ul>
</main>
<script type="module" src="/src/main.js"></script>
</body>
</html>
Loading
Loading