fix: skills_api aiohttp

This commit is contained in:
Felipe Domingues 2026-04-27 17:36:15 -03:00
parent 1f2fc5f5a9
commit a68af047c2
4 changed files with 350 additions and 39 deletions

View file

@ -1,25 +1,39 @@
"""
Injeta `from skills_api import router as skills_router` + `app.include_router(...)`
no api_server.py do Hermes durante o build da imagem.
Injeta o registro das rotas aiohttp do skills_api dentro do método start()
do APIServerAdapter no api_server.py do Hermes.
Idempotente: se o marcador existir, não faz nada.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
MARKER = "# >>> hermes-custom: skills_api <<<"
INJECT = f"""
{MARKER}
try:
from skills_api import router as _skills_router
app.include_router(_skills_router)
print("[hermes-custom] skills_api router registered", flush=True)
except Exception as _e:
print(f"[hermes-custom] failed to register skills_api: {{_e}}", flush=True)
# <<< hermes-custom: skills_api >>>
"""
# Regex: captura uma linha que cria a aiohttp Application, ex:
# self._app = web.Application(...)
# app = web.Application(...)
APP_ASSIGN_RE = re.compile(
r"^(?P<indent>[ \t]+)(?P<lhs>(?:self\._?app|app))\s*=\s*web\.Application\([^)]*\)\s*$",
re.MULTILINE,
)
def build_injection(indent: str, app_var: str) -> str:
lines = [
"",
f"{indent}{MARKER}",
f"{indent}try:",
f"{indent} from skills_api import skills_routes as _skills_routes",
f"{indent} {app_var}.add_routes(_skills_routes)",
f'{indent} print("[hermes-custom] skills_api routes registered", flush=True)',
f"{indent}except Exception as _e:",
f'{indent} print(f"[hermes-custom] failed to register skills_api: {{_e}}", flush=True)',
f"{indent}# <<< hermes-custom: skills_api >>>",
]
return "\n".join(lines)
def main(target: str) -> int:
@ -33,12 +47,25 @@ def main(target: str) -> int:
print("[apply_patch] already applied, skipping")
return 0
# Procura a linha onde o `app = FastAPI(...)` é instanciado e injeta logo
# após o bloco de criação. Estratégia: anexa no final do arquivo — mais
# robusto contra mudanças upstream do que tentar achar a linha exata.
new_src = src.rstrip() + "\n\n" + INJECT + "\n"
match = APP_ASSIGN_RE.search(src)
if not match:
print(
"[apply_patch] ERROR: não encontrei `... = web.Application(...)` no api_server.py",
file=sys.stderr,
)
return 2
indent = match.group("indent")
app_var = match.group("lhs")
insert_at = match.end()
injection = build_injection(indent, app_var)
new_src = src[:insert_at] + injection + src[insert_at:]
p.write_text(new_src, encoding="utf-8")
print(f"[apply_patch] injected at offset {len(src)}")
print(
f"[apply_patch] injected after `{app_var} = web.Application(...)` "
f"at offset {insert_at} (indent={len(indent)} spaces)"
)
return 0