"""Server extension for the "patterns" demo (web/demos/patterns/). GET /api/patterns the four patterns: presets, default params, param spec, decision code POST /api/patterns/{slug}/run {inputs, params?} -> {requests, responses, params, decision} POST /api/patterns/{slug}/decide {inputs, params?, responses} -> {params, decision} (no model call) ``run`` goes through the same engine as ``POST /v1/systemone`` (and the same bearer key); ``decide`` only re-applies the code decision to responses the page already has, so sliders never trigger a model call. Errors use the server's JSON error body (422 ``invalid_request`` for bad inputs; budget errors pass through as ``input_budget_exceeded``). """ from __future__ import annotations import json from typing import Any from fastapi import Depends, Request from fastapi.concurrency import run_in_threadpool from macjev.demos.patterns import PATTERNS, PatternInputError, describe, from_adapter, redecide, run from macjev.serve.schema import ApiError MAX_BODY = 1_000_000 def _pattern(slug: str): mod = PATTERNS.get(slug) if mod is None: raise ApiError(404, "not_found", f"unknown pattern {slug!r}; have {sorted(PATTERNS)}") return mod async def _body(request: Request) -> dict: raw = await request.body() if len(raw) > MAX_BODY: raise ApiError(413, "too_large", f"request body over {MAX_BODY} bytes") try: body = json.loads(raw or b"{}") except ValueError as e: raise ApiError(422, "invalid_json", f"body is not JSON: {e}") from None if not isinstance(body, dict): raise ApiError(422, "invalid_request", "body must be a JSON object") return body def register(app: Any) -> None: auth = [Depends(app.state.require_auth)] @app.get("/api/patterns") async def patterns_index(): return {"patterns": [describe(m) for m in PATTERNS.values()]} @app.post("/api/patterns/{slug}/run", dependencies=auth) async def patterns_run(slug: str, request: Request): mod = _pattern(slug) body = await _body(request) call = from_adapter(app.state.adapter) try: return await run_in_threadpool(run, mod, body.get("inputs"), call, body.get("params")) except PatternInputError as e: raise ApiError(422, "invalid_request", str(e)) from None @app.post("/api/patterns/{slug}/decide") async def patterns_decide(slug: str, request: Request): mod = _pattern(slug) body = await _body(request) try: return redecide(mod, body.get("inputs"), body.get("responses"), body.get("params")) except PatternInputError as e: raise ApiError(422, "invalid_request", str(e)) from None except (KeyError, TypeError, ValueError) as e: # malformed saved responses raise ApiError(422, "invalid_request", f"responses do not match this pattern: {e}") from None