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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Changelog

## [Unreleased]

**Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather
Expand Down Expand Up @@ -367,6 +368,9 @@ Full migration path, including the one decision to get right before the first de
behaviour except `scheduler_mode`, which is required — see **Breaking**.
- `pyyaml>=6.0` is now a declared dependency (it reads the group file). Already present in every
environment via `uvicorn[standard]`, so no installed set changes.
- **`@RestApiBase.head(path, **kwargs)`** registers a HEAD route, like the other verb decorators
(#63). A service that needed one, for a cheap existence check before a GET, had to write its own
decorator.

### Changed

Expand Down Expand Up @@ -401,6 +405,18 @@ Full migration path, including the one decision to get right before the first de

### Fixed

- **A handler that returns an `event_type` no longer fails its delivery where nothing can publish
it** (#40). A publishing service exists only beside an event-bus client, so with
`event_bus = "sessions"`, or without an event bus, the lookup raised after the handler had
finished, and every successful job was logged as `Unexpected error processing job` at ERROR. The
event is now skipped: a WARNING names the agent and the `event_type` once, later ones log at
DEBUG, and the delivery counts as processed. Two publishing services at one level still fail it.
- **The `/` service page lists the routes again** (#42). Since FastAPI 0.137, `include_router()`
leaves a wrapper in `app.routes` instead of the routes, and the page found none of them: every
route the framework mounts comes from an included router, so the table was empty. It is now built
from the OpenAPI schema, which works on every supported FastAPI version. A route declared with
`include_in_schema=False` is no longer listed, and an operation without a summary shows the one
FastAPI generates from the function name, as Swagger UI does.
- **`asbs validate` no longer fails an image build on an unset `nats_url`.** Outside development
it reported one as an issue, and an image that validates while it is built has no `nats_url` yet:
the deployment injects it when the container starts. It is a notice now, as `event_bus` is; the
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ Two things about that chain are worth knowing up front:
|-----------|-----------|---------|
| **Event Handler** | `EventHandlerBase` | Route CloudEvents (priority chain) and translate each into one service call; returns a result, `HandlerResult.skipped(reason)` or `None` |
| **Service** | `ServiceBase` | All business logic, including whether an event needs work; runs the agents |
| **REST API** | `RestApiBase` | Define HTTP endpoints with `@get()`, `@post()`, `@put()`, `@delete()`, `@patch()` decorators |
| **REST API** | `RestApiBase` | Define HTTP endpoints with `@get()`, `@post()`, `@put()`, `@delete()`, `@patch()`, `@head()` decorators |
| **Agent** | `AgentRuntime` | Run LLM agents with structured outputs, tool calling, and prompt management |
| **Scheduler** | `SchedulerBase` | Execute cron-based background tasks with auto-registered trigger endpoints |

Expand Down
2 changes: 1 addition & 1 deletion src/blueprint/agent_generator/claude_docs/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ class OrderApi(RestApiBase):
return await self._service.create(payload)
```

Route decorators: `@RestApiBase.get()`, `.post()`, `.put()`, `.delete()`, `.patch()`.
Route decorators: `@RestApiBase.get()`, `.post()`, `.put()`, `.delete()`, `.patch()`, `.head()`.

**Creating CloudEvents from REST payloads** — use `create_cloud_event()` when an API endpoint needs to feed a payload into the event processing pipeline:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ After scaffolding, implement the component logic:
- Resolve agent/cache dependencies in `on_startup()`

### RestApi
- Use `@RestApiBase.get/post/put/delete/patch()` decorators
- Use `@RestApiBase.get/post/put/delete/patch/head()` decorators
- Use Pydantic models for request/response types
- Resolve services in `on_startup()`

Expand Down
1 change: 1 addition & 0 deletions src/blueprint/agent_generator/docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ Use these to decorate methods on your subclass:
| `@RestApiBase.put(path, **kwargs)` | Register a PUT endpoint. |
| `@RestApiBase.delete(path, **kwargs)` | Register a DELETE endpoint. |
| `@RestApiBase.patch(path, **kwargs)` | Register a PATCH endpoint. |
| `@RestApiBase.head(path, **kwargs)` | Register a HEAD endpoint, e.g. a cheap existence check before a GET. |

`**kwargs` are forwarded to the underlying FastAPI route registration.

Expand Down
12 changes: 11 additions & 1 deletion src/blueprint/agents/io/api/rest_api_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class RestApiBase(IOBase, ABC):

Routes are registered by decorating methods with the class-level HTTP verb
helpers (``RestApiBase.get``, ``RestApiBase.post``, ``RestApiBase.put``,
``RestApiBase.delete``, ``RestApiBase.patch``). The base class wires those
``RestApiBase.delete``, ``RestApiBase.patch``, ``RestApiBase.head``). The base class wires those
decorated methods onto ``self.router`` during ``__init__``, so subclasses
never need to call ``_wire_routes()`` or touch the router directly.
"""
Expand Down Expand Up @@ -189,6 +189,16 @@ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:

return decorator

@staticmethod
def head(path: str, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Decorator: register a HEAD route on the instance router."""

def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
func._route = ("head", path, kwargs) # type: ignore[attr-defined]
return func

return decorator

def _wire_routes(self) -> None:
"""Discover and register all decorated route methods on self.router."""

Expand Down
37 changes: 28 additions & 9 deletions src/blueprint/agents/io/api/utilities/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.routing import APIRoute

from ..rest_api_base import RestApiBase

_HTTP_METHODS = frozenset({"GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"})
"""Keys of an OpenAPI path item that are operations; the others (``parameters``, ...) are not."""


class RootApi(RestApiBase):
"""Exposes a root endpoint listing service metadata and all registered routes."""
Expand Down Expand Up @@ -42,17 +44,13 @@ async def root(self) -> Any:
doc_links = " | ".join(f'<a href="{url}">{label}</a>' for label, url in [("Swagger UI", docs_url), ("ReDoc", redoc_url)] if url)

rows = []
for route in self._app.routes:
if not isinstance(route, APIRoute):
continue
route_methods = route.methods or set()
for path, route_methods, summary in self._operations():
methods = ", ".join(sorted(route_methods))
summary = route.summary or ""
if "GET" in route_methods:
path_cell = f'<a href="{route.path}">{route.path}</a>'
path_cell = f'<a href="{path}">{path}</a>'
else:
anchor = route.path.replace("/", "-").strip("-")
path_cell = f'<a href="{docs_url}#{anchor}" title="Open in Swagger">{route.path}</a>' if docs_url else route.path
anchor = path.replace("/", "-").strip("-")
path_cell = f'<a href="{docs_url}#{anchor}" title="Open in Swagger">{path}</a>' if docs_url else path
rows.append(f"<tr><td>{methods}</td><td>{path_cell}</td><td>{summary}</td></tr>")

rows_html = "\n".join(rows)
Expand Down Expand Up @@ -87,3 +85,24 @@ async def root(self) -> Any:
</body>
</html>"""
return self._html_cache

def _operations(self) -> list[tuple[str, set[str], str]]:
"""Return ``(path, methods, summary)`` for every documented operation, in schema order.

Read from the OpenAPI schema rather than from ``app.routes``: since FastAPI 0.137,
``include_router()`` leaves a lazy wrapper in ``app.routes`` instead of the routes
themselves, so every route of an included router -- which is every route this framework
mounts -- was missing from the table (#42). The schema is FastAPI's public view of the same
routes, under every version this package supports. It omits routes declared with
``include_in_schema=False``, which the table therefore no longer lists either.

Operations on one path with the same summary share a row, as one route declared with
several methods always did.
"""
rows: dict[tuple[str, str], set[str]] = {}
for path, operations in self._app.openapi().get("paths", {}).items():
for method, operation in operations.items():
if method.upper() not in _HTTP_METHODS:
continue
rows.setdefault((path, operation.get("summary") or ""), set()).add(method.upper())
return [(path, methods, summary) for (path, summary), methods in rows.items()]
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ def __init__(self) -> None:
# every application that exists today -- behaves exactly as it did.
self._handler_chains: dict[str, HandlerChain] = {ROOT_NAMESPACE: HandlerChain()}
self._correlation_context = self.registry.correlation_context
# Agents already warned that their handlers' events have nowhere to go: once per agent,
# because in sessions mode every successful job would repeat it.
self._unpublished_warned: set[str] = set()

async def on_startup(self) -> None:
"""Start one handler chain per namespace that has handlers registered in it.
Expand Down Expand Up @@ -194,7 +197,10 @@ async def process_event(
# unscoped lookup this used to be: with one publishing service per
# namespace (P6) that finds several and refuses to choose, so a grouped
# process would fail on the first handler that returns an event_type.
publisher = self.registry.get_component(EventPublishingService, namespace=namespace)
publisher = self._publisher_for(namespace)
if publisher is None:
self._log_unpublished(namespace, result.event_type)
continue
await publisher.publish_handler_event(
event_type=result.event_type,
data=result.data,
Expand Down Expand Up @@ -260,6 +266,40 @@ async def process_rest_request(
# Private helpers
# ------------------------------------------------------------------

def _publisher_for(self, namespace: str) -> EventPublishingService | None:
"""Return the agent's publishing service, else the root's, or ``None`` when neither exists.

A publishing service exists only beside an event-bus client. A process without one --
``event_bus = "sessions"``, or no event bus at all -- has none, and a handler that returns
an ``event_type`` there has nothing to publish on (#40). Absence is checked here rather
than by catching the registry's ``ValueError``, because that error also reports two
publishing services at one level, and ambiguity must still fail the delivery.
"""
own = self.registry.get_components_by_type(EventPublishingService, namespace)
if not own and not self.registry.get_components_by_type(EventPublishingService, ROOT_NAMESPACE):
return None
publisher: EventPublishingService = self.registry.get_component(EventPublishingService, namespace=namespace)
return publisher

def _log_unpublished(self, namespace: str, event_type: str) -> None:
"""Say that a handler's event is not published: WARNING once per agent, DEBUG after that.

The handler's own work is done by now; only the follow-up event is dropped. Before #40 the
lookup raised instead and the transport logged the delivery as failed after it had
succeeded -- an ERROR on every successful sessions job.
"""
agent = namespace or ROOT_LABEL
if namespace in self._unpublished_warned:
logger.debug("Not publishing event_type '%s' for agent '%s': no event publishing service", event_type, agent)
return
self._unpublished_warned.add(namespace)
logger.warning(
"Agent '%s' returned event_type '%s', but it has no event-bus client to publish on, so handler events are not "
"published. Logged once per agent.",
agent,
event_type,
)

@staticmethod
def _extract_handler_results(handler_result: Any) -> list[HandlerResult]:
"""Normalize handler output to a list of HandlerResult objects."""
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/agents/io/api/eventing/test_sessions_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,29 @@ async def test_agent_token_none_when_absent(self, sessions_bus: SessionsBus, moc
assert sessions_bus._agent_token is None
sessions_bus._sse_task.cancel()

async def test_agent_token_stripped_on_read(self, sessions_bus: SessionsBus, mock_config: MagicMock, mock_registry: MagicMock) -> None:
# A token mounted from a secret file usually ends in a newline, which is not valid in a header.
mock_config.get.return_value = {**_make_sessions_config(), "agent_token": " agent-jwt\n"}
mock_registry.get_service.return_value = MagicMock()

with patch.object(sessions_bus, "_consume_sse_stream", new=AsyncMock()):
await sessions_bus.on_startup()

assert sessions_bus._agent_token == "agent-jwt"
sessions_bus._sse_task.cancel()

async def test_whitespace_only_agent_token_treated_as_absent(
self, sessions_bus: SessionsBus, mock_config: MagicMock, mock_registry: MagicMock
) -> None:
mock_config.get.return_value = {**_make_sessions_config(), "agent_token": " \n"}
mock_registry.get_service.return_value = MagicMock()

with patch.object(sessions_bus, "_consume_sse_stream", new=AsyncMock()):
await sessions_bus.on_startup()

assert sessions_bus._agent_token is None
sessions_bus._sse_task.cancel()


# ---------------------------------------------------------------------------
# on_shutdown
Expand Down
13 changes: 11 additions & 2 deletions tests/unit/agents/io/api/test_rest_api_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ async def delete_item(self) -> None:
async def patch_item(self) -> dict:
return {}

@RestApiBase.head("/items/{id}")
async def item_exists(self) -> None:
pass


# ---------------------------------------------------------------------------
# Route decorator tests
Expand Down Expand Up @@ -82,6 +86,11 @@ def test_patch_decorator_attaches_route_attr(self) -> None:
assert verb == "patch"
assert path == "/items/{id}"

def test_head_decorator_attaches_route_attr(self) -> None:
verb, path, _ = _RoutedApi.item_exists._route
assert verb == "head"
assert path == "/items/{id}"

def test_decorator_stores_kwargs(self) -> None:
@RestApiBase.get("/tagged", tags=["foo"], summary="bar")
async def tagged_fn(self):
Expand All @@ -105,10 +114,10 @@ def test_router_has_routes_after_init(self, mock_config: MagicMock) -> None:
api = _RoutedApi()
assert len(api.router.routes) > 0

def test_all_five_verbs_are_registered(self, mock_config: MagicMock) -> None:
def test_all_six_verbs_are_registered(self, mock_config: MagicMock) -> None:
api = _RoutedApi()
flat = {m for route in api.router.routes if hasattr(route, "methods") for m in route.methods}
assert {"GET", "POST", "PUT", "DELETE", "PATCH"}.issubset(flat)
assert {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"}.issubset(flat)

def test_no_routes_when_no_decorated_methods(self, mock_config: MagicMock) -> None:
api = _MinimalApi()
Expand Down
Loading
Loading