#!/usr/bin/env python3 """Read one display-safe Agent9 Session or Operation through the Console API.""" from __future__ import annotations import argparse import json import os import re import sys import urllib.error import urllib.parse import urllib.request ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,160}$") def required_env(name: str) -> str: value = os.environ.get(name, "").strip() if not value: raise RuntimeError(f"{name} is required") return value def bounded_id(value: str, label: str) -> str: if not ID_PATTERN.fullmatch(value): raise ValueError(f"{label} has an invalid format") return value def main() -> int: parser = argparse.ArgumentParser( description="Read one Agent9 Console Session or Operation (GET only)." ) parser.add_argument("session_id") parser.add_argument("--operation-id") args = parser.parse_args() session_id = bounded_id(args.session_id, "session_id") operation_id = ( bounded_id(args.operation_id, "operation_id") if args.operation_id is not None else None ) base_url = required_env("AUTO_ONCALL_AGENT9_BASE_URL").rstrip("/") + "/" project_id = required_env("AUTO_ONCALL_AGENT9_PROJECT_ID") api_key = required_env("AUTO_ONCALL_AGENT9_API_KEY") path = f"api/console/sessions/{urllib.parse.quote(session_id, safe='')}" if operation_id is not None: path += f"/operations/{urllib.parse.quote(operation_id, safe='')}" request = urllib.request.Request( urllib.parse.urljoin(base_url, path), method="GET", headers={ "Authorization": f"Bearer {api_key}", "x-agent9-project-id": project_id, "Accept": "application/json", }, ) try: with urllib.request.urlopen(request, timeout=60) as response: payload = json.load(response) except urllib.error.HTTPError as error: body = error.read(1000).decode("utf-8", errors="replace") raise RuntimeError(f"Agent9 Console API returned HTTP {error.code}: {body}") from error json.dump(payload, sys.stdout, ensure_ascii=False, indent=2) sys.stdout.write("\n") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except (RuntimeError, ValueError, urllib.error.URLError) as error: print(str(error), file=sys.stderr) raise SystemExit(1) from error