Files

89 lines
2.6 KiB
Python

"""Shared stdlib hub bridge client for the ``background-shells`` plugin."""
from __future__ import annotations
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
sys.dont_write_bytecode = True
CID_RE = re.compile(r"^[A-Za-z0-9._/-]{4,200}$")
TASK_ID_RE = re.compile(r"^[A-Za-z0-9_.-]{1,120}$")
def fail(msg: str) -> None:
print(msg, file=sys.stderr)
sys.exit(1)
def read_payload() -> dict:
try:
p = json.loads(sys.stdin.read() or "{}")
except ValueError:
return {}
return p if isinstance(p, dict) else {}
def pick_cid(p: dict) -> str:
for key in ("conversationId", "sessionId", "id"):
v = p.get(key)
if isinstance(v, str) and CID_RE.fullmatch(v) and ".." not in v.split("/"):
return v
fail("which conversation? (conversationId or sessionId)")
return ""
def pick_task_id(p: dict) -> str:
v = p.get("taskId") or p.get("task")
if isinstance(v, str) and TASK_ID_RE.fullmatch(v):
return v
fail("which task? (taskId)")
return ""
def hub_request(method: str, path: str, *, query: dict | None = None, timeout: int = 15) -> tuple[int, dict]:
base = os.environ.get("AIA_TOOLS_URL", "").rstrip("/")
token = os.environ.get("AIA_TOOLS_TOKEN", "")
pid = os.environ.get("AIA_PLUGIN_ID", "").strip() or "background-shells"
if not base or not token:
fail("no hub to ask (AIA_TOOLS_URL / AIA_TOOLS_TOKEN unset)")
url = f"{base}/plugins/{pid}/hub/{path.lstrip('/')}"
if query:
url += "?" + urllib.parse.urlencode(query)
req = urllib.request.Request(
url,
data=b"{}" if method == "POST" else None,
method=method,
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/json",
**({"Content-Type": "application/json"} if method == "POST" else {}),
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as e:
try:
body = json.loads(e.read() or b"{}")
except ValueError:
body = {}
return e.code, body if isinstance(body, dict) else {}
except (urllib.error.URLError, TimeoutError, ValueError) as e:
fail(f"the hub didn't answer: {e}")
return 500, {}
def error_message(body: dict, status: int) -> str:
err = body.get("error")
if isinstance(err, dict) and err.get("message"):
return str(err["message"])
if isinstance(body.get("detail"), str):
return body["detail"]
return f"the hub answered {status}"