hermes_dashboard.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """In-process dispatch to Hermes' own dashboard REST handlers (Yaoyao embedded mode).
  2. Yaoyao used to call a separately running Hermes dashboard over HTTP. The embedded runtime has
  3. no ASGI server: hermes_service.py shims FastAPI so the router modules import as plain functions
  4. and records each decorated route. ``call`` matches a method + path against those routes and
  5. invokes the native handler with path, query and body arguments, so responses keep the exact
  6. shapes the dashboard returned. One service process serves one Hermes home, so the ``profile``
  7. query parameter is resolved by the caller choosing the process, never by the handler.
  8. """
  9. import asyncio
  10. import inspect
  11. import re
  12. import types
  13. import typing
  14. from typing import Any
  15. ROUTER_MODULES = (
  16. "hermes_cli.web_routers.sessions",
  17. "hermes_cli.web_routers.profiles",
  18. "hermes_cli.web_routers.config_env",
  19. "hermes_cli.web_routers.models",
  20. "hermes_cli.web_routers.files",
  21. )
  22. _loaded = False
  23. _compiled: list[tuple[str, re.Pattern, list[str], Any]] = []
  24. def _load(routes):
  25. global _loaded
  26. if _loaded:
  27. return
  28. import importlib
  29. import os
  30. from pathlib import Path
  31. home = Path(os.environ["HERMES_HOME"])
  32. if not (home / "state.db").exists():
  33. # The dashboard expects its gateway to have created the store; the embedded home creates it here.
  34. from hermes_state import SessionDB
  35. SessionDB(db_path=home / "state.db").close()
  36. for name in ROUTER_MODULES:
  37. importlib.import_module(name)
  38. for method, template, fn in routes:
  39. names = re.findall(r"{([A-Za-z_][A-Za-z0-9_]*)(?::path)?}", template)
  40. pattern = re.escape(template)
  41. for param in names:
  42. pattern = pattern.replace(re.escape("{" + param + ":path}"), "(?P<%s>.+)" % param)
  43. pattern = pattern.replace(re.escape("{" + param + "}"), "(?P<%s>[^/]+)" % param)
  44. # Static routes (``/api/sessions/search``) win over templates (``/api/sessions/{id}``).
  45. _compiled.append((method, re.compile("^" + pattern + "$"), names, fn))
  46. _compiled.sort(key=lambda item: len(item[2]))
  47. _loaded = True
  48. class _Request:
  49. def __init__(self, query, body):
  50. self.headers = {}
  51. self.cookies = {}
  52. self.query_params = query
  53. self.client = types.SimpleNamespace(host="127.0.0.1", port=0)
  54. self.url = types.SimpleNamespace(path="", query="")
  55. self.state = types.SimpleNamespace()
  56. self._body = body
  57. async def json(self):
  58. return self._body
  59. def _base_types(annotation):
  60. if annotation is inspect.Parameter.empty:
  61. return ()
  62. origin = typing.get_origin(annotation)
  63. if origin in (typing.Union, types.UnionType):
  64. return tuple(a for a in typing.get_args(annotation) if a is not type(None))
  65. return (annotation,)
  66. def _convert(value, annotation):
  67. for kind in _base_types(annotation):
  68. if kind is bool:
  69. return str(value).lower() in ("1", "true", "yes", "on")
  70. if kind is int:
  71. return int(value)
  72. if kind is float:
  73. return float(value)
  74. if kind is str:
  75. return str(value)
  76. return value
  77. def _model_type(annotation):
  78. for kind in _base_types(annotation):
  79. if inspect.isclass(kind) and hasattr(kind, "model_validate"):
  80. return kind
  81. return None
  82. def _arguments(fn, path_args, query, body):
  83. kwargs = {}
  84. for name, param in inspect.signature(fn).parameters.items():
  85. annotation = param.annotation
  86. if name in path_args:
  87. kwargs[name] = _convert(path_args[name], annotation)
  88. elif name == "request" or getattr(annotation, "__name__", "") == "Request":
  89. kwargs[name] = _Request(query, body)
  90. elif _model_type(annotation) is not None:
  91. kwargs[name] = _model_type(annotation).model_validate(body or {})
  92. elif name in query:
  93. kwargs[name] = _convert(query[name], annotation)
  94. elif name in ("body", "payload", "data") and body is not None:
  95. kwargs[name] = body
  96. elif param.default is not inspect.Parameter.empty:
  97. kwargs[name] = param.default
  98. return kwargs
  99. def _response(result):
  100. if hasattr(result, "status_code") and hasattr(result, "body") and not hasattr(result, "kwargs"):
  101. # Real starlette responses (JSONResponse, Response, PlainTextResponse).
  102. raw = bytes(result.body or b"")
  103. media = getattr(result, "media_type", None) or ""
  104. if "json" in media:
  105. import json
  106. return {"status": int(result.status_code), "json": json.loads(raw or b"null")}
  107. return {"status": int(result.status_code), "text": raw.decode("utf-8", "replace"), "media_type": media}
  108. if hasattr(result, "path") and type(result).__name__ == "FileResponse" and not hasattr(result, "kwargs"):
  109. return {"status": int(getattr(result, "status_code", 200)), "file": str(result.path),
  110. "filename": getattr(result, "filename", None), "media_type": getattr(result, "media_type", None), "headers": {}}
  111. args = getattr(result, "args", None)
  112. options = getattr(result, "kwargs", None)
  113. if args is None or options is None:
  114. return {"status": 200, "json": result}
  115. kind = type(result).__name__
  116. if kind == "FileResponse":
  117. path = options.get("path", args[0] if args else None)
  118. return {"status": 200, "file": str(path), "filename": options.get("filename"),
  119. "media_type": options.get("media_type"), "headers": options.get("headers") or {}}
  120. status = int(options.get("status_code") or 200)
  121. if kind == "JSONResponse":
  122. return {"status": status, "json": options.get("content", args[0] if args else None)}
  123. content = options.get("content", args[0] if args else b"")
  124. if isinstance(content, bytes):
  125. content = content.decode("utf-8", "replace")
  126. return {"status": status, "text": content, "media_type": options.get("media_type")}
  127. def call(routes, error_type, args):
  128. _load(routes)
  129. method = str(args.get("method") or "GET").upper()
  130. path = str(args.get("path") or "")
  131. query = {k: v for k, v in (args.get("query") or {}).items() if k != "profile"}
  132. body = args.get("body")
  133. allowed = False
  134. for route_method, pattern, _names, fn in _compiled:
  135. match = pattern.match(path)
  136. if not match:
  137. continue
  138. allowed = True
  139. if route_method != method:
  140. continue
  141. try:
  142. result = fn(**_arguments(fn, match.groupdict(), query, body))
  143. if inspect.isawaitable(result):
  144. result = asyncio.run(result) if inspect.iscoroutine(result) else asyncio.run(_await(result))
  145. return _response(result)
  146. except error_type as exc:
  147. detail = getattr(exc, "detail", "") or str(exc)
  148. return {"status": int(getattr(exc, "status_code", 500) or 500), "json": {"detail": detail}}
  149. return {"status": 405 if allowed else 404, "json": {"detail": "Not Found" if not allowed else "Method Not Allowed"}}
  150. async def _await(value):
  151. return await value