cli.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. """CLI commands for the Teams meeting pipeline plugin."""
  2. from __future__ import annotations
  3. import argparse
  4. import asyncio
  5. import json
  6. import os
  7. from typing import Any, Callable
  8. from hermes_constants import display_hermes_home
  9. from gateway.config import Platform, load_gateway_config
  10. from plugins.teams_pipeline.meetings import (
  11. enrich_meeting_with_call_record, fetch_preferred_transcript_text, list_recording_artifacts, resolve_meeting_reference)
  12. from plugins.teams_pipeline.pipeline import TeamsMeetingPipeline
  13. from plugins.teams_pipeline.store import TeamsPipelineStore, resolve_teams_pipeline_store_path
  14. from plugins.teams_pipeline.subscriptions import (
  15. build_graph_client, maintain_graph_subscriptions, sync_graph_subscription_record, utc_timestamp)
  16. from tools.microsoft_graph_auth import MicrosoftGraphConfigError, MicrosoftGraphTokenProvider
  17. def register_cli(subparser: argparse.ArgumentParser) -> None:
  18. subs = subparser.add_subparsers(dest="teams_pipeline_action")
  19. for name, aliases, help_text, options, _handler in _SUBCOMMANDS:
  20. parser = subs.add_parser(name, aliases=aliases, help=help_text)
  21. for flag, kwargs in options:
  22. parser.add_argument(flag, **kwargs)
  23. subparser.set_defaults(func=teams_pipeline_command)
  24. def teams_pipeline_command(args: argparse.Namespace) -> int:
  25. action = getattr(args, "teams_pipeline_action", None)
  26. if not action:
  27. print(f"Usage: hermes teams-pipeline {{{'|'.join(spec[0] for spec in _SUBCOMMANDS)}}}")
  28. return 2
  29. handler = _ACTIONS.get(action)
  30. if handler is None:
  31. print(f"Unknown teams-pipeline action: {action}")
  32. return 2
  33. required, missing_message = _REQUIRED_ARGS.get(handler, ((), ""))
  34. if not all(_text(args, name) for name in required):
  35. print(missing_message)
  36. return 0
  37. try:
  38. handler(args)
  39. return 0
  40. except MicrosoftGraphConfigError:
  41. print(_graph_setup_hint())
  42. return 1
  43. def _text(args: argparse.Namespace, name: str) -> str:
  44. """Stripped string form of an optional CLI arg ('' when absent/None)."""
  45. return str(getattr(args, name, "") or "").strip()
  46. def _int_arg(args: argparse.Namespace, name: str, default: int) -> int:
  47. return int(getattr(args, name, default) or default)
  48. def _open_store(args: argparse.Namespace) -> TeamsPipelineStore:
  49. return TeamsPipelineStore(resolve_teams_pipeline_store_path(getattr(args, "store_path", None)))
  50. def _print_json(payload: Any) -> None:
  51. print(json.dumps(payload, indent=2, sort_keys=True))
  52. def _print_records(noun: str, empty_message: str, records: list[tuple[Any, list[tuple[str, Any, bool]]]]) -> None:
  53. """Print bulleted records; fields are (label, value, required) — optional fields skip falsy values."""
  54. if not records:
  55. print(empty_message)
  56. return
  57. print(f"\n{len(records)} {noun}:\n")
  58. for title, fields in records:
  59. print(f" ◆ {title}")
  60. for label, value, required in fields:
  61. if required or value:
  62. print(f" {label}: {value}")
  63. print()
  64. def _graph_setup_hint() -> str:
  65. return f"""
  66. Microsoft Graph is not configured. Add these to {display_hermes_home()}/.env:
  67. MSGRAPH_TENANT_ID=...
  68. MSGRAPH_CLIENT_ID=...
  69. MSGRAPH_CLIENT_SECRET=...
  70. Then restart the gateway or rerun this command.
  71. """
  72. # Graph only emits "created" for the artifact/callRecord collection resources; meetings use "updated".
  73. _CREATED_RESOURCE_PREFIXES = (
  74. "communications/onlinemeetings/getalltranscripts", "communications/onlinemeetings/getallrecordings", "communications/callrecords")
  75. def _default_change_type_for_resource(resource: str) -> str:
  76. return "created" if str(resource or "").strip().lower().startswith(_CREATED_RESOURCE_PREFIXES) else "updated"
  77. def _compact_job(job: dict) -> dict:
  78. payload = dict(job)
  79. summary = dict(payload.get("summary_payload") or {})
  80. if transcript := summary.pop("transcript_text", None):
  81. summary["transcript_preview"] = str(transcript)[:240]
  82. payload["summary_payload"] = summary or None
  83. return payload
  84. def _cmd_validate(args) -> None:
  85. store = _open_store(args)
  86. issues: list[str] = []
  87. warnings: list[str] = []
  88. gateway_config = load_gateway_config()
  89. webhook_config = gateway_config.platforms.get(Platform.MSGRAPH_WEBHOOK)
  90. teams_config = gateway_config.platforms.get(Platform("teams"))
  91. graph = {key: bool(os.environ.get(f"MSGRAPH_{key.upper()}")) for key in ("tenant_id", "client_id", "client_secret")}
  92. webhook_enabled = bool(webhook_config and webhook_config.enabled)
  93. teams_enabled = bool(teams_config and teams_config.enabled)
  94. teams_extra = dict((teams_config.extra or {}) if teams_config else {})
  95. teams_mode = str(teams_extra.get("delivery_mode") or "").strip() or None
  96. if not all(graph.values()):
  97. issues.append("Microsoft Graph app-only credentials are incomplete.")
  98. if not webhook_enabled:
  99. issues.append("MSGRAPH_WEBHOOK_ENABLED is not enabled.")
  100. if not teams_enabled:
  101. warnings.append("Teams outbound delivery is disabled.")
  102. elif teams_mode == "incoming_webhook":
  103. if not teams_extra.get("incoming_webhook_url"):
  104. issues.append("TEAMS_INCOMING_WEBHOOK_URL is required for incoming_webhook mode.")
  105. elif teams_mode == "graph":
  106. # Graph delivery can authenticate with either a dedicated delivery token or the app-only creds.
  107. if not (teams_config.token or teams_extra.get("access_token")) and not all(graph.values()):
  108. issues.append("TEAMS_GRAPH_ACCESS_TOKEN or complete MSGRAPH_* app credentials is required for graph delivery mode.")
  109. if not teams_extra.get("team_id"):
  110. issues.append("TEAMS_TEAM_ID is required for graph delivery mode.")
  111. if not (teams_extra.get("channel_id") or teams_extra.get("chat_id") or teams_config.home_channel):
  112. issues.append("TEAMS_CHANNEL_ID is required for graph delivery mode.")
  113. else:
  114. warnings.append("TEAMS_DELIVERY_MODE is not set.")
  115. _print_json({
  116. "ok": not issues, "issues": issues, "warnings": warnings, "graph_config": graph,
  117. "webhook_enabled": webhook_enabled, "teams_enabled": teams_enabled, "teams_delivery_mode": teams_mode,
  118. "store_path": str(store.path), "store_stats": store.stats()})
  119. def _cmd_list(args) -> None:
  120. jobs = list(_open_store(args).list_jobs().values())
  121. if status := _text(args, "status").lower():
  122. jobs = [job for job in jobs if str(job.get("status") or "").lower() == status]
  123. jobs.sort(key=lambda item: str((item or {}).get("updated_at") or ""), reverse=True)
  124. jobs = jobs[: max(1, min(_int_arg(args, "limit", 20), 100))]
  125. _print_records("Teams pipeline job(s)", "No Teams meeting pipeline jobs found.", [
  126. (job.get("job_id"), [
  127. ("status", job.get("status"), True),
  128. ("meeting", (job.get("meeting_ref") or {}).get("meeting_id") or "unknown", True),
  129. ("strategy", job.get("selected_artifact_strategy"), False),
  130. ("updated", job.get("updated_at"), False),
  131. ("error", job.get("error_info"), False)])
  132. for job in jobs])
  133. def _cmd_show(args) -> None:
  134. job_id = _text(args, "job_id")
  135. job = _open_store(args).get_job(job_id)
  136. if not job:
  137. print(f"Unknown job: {job_id}")
  138. return
  139. _print_json(_compact_job(job))
  140. def _cmd_run(args) -> None:
  141. pipeline = TeamsMeetingPipeline(graph_client=build_graph_client(), store=_open_store(args), config={})
  142. _print_json(_compact_job(asyncio.run(pipeline.run_job(_text(args, "job_id"))).to_dict()))
  143. def _cmd_fetch(args) -> None:
  144. meeting_id = _text(args, "meeting_id") or None
  145. join_web_url = _text(args, "join_web_url") or None
  146. if not meeting_id and not join_web_url:
  147. print("meeting_id or join_web_url is required")
  148. return
  149. client = build_graph_client()
  150. meeting_ref = asyncio.run(resolve_meeting_reference(
  151. client, meeting_id=meeting_id, join_web_url=join_web_url,
  152. tenant_id=_text(args, "tenant_id") or None, organizer_user_id=_text(args, "organizer_user_id") or None))
  153. transcript_artifact, transcript_text = asyncio.run(fetch_preferred_transcript_text(client, meeting_ref))
  154. recordings = asyncio.run(list_recording_artifacts(client, meeting_ref))
  155. call_record = asyncio.run(enrich_meeting_with_call_record(client, meeting_ref, call_record_id=_text(args, "call_record_id") or None))
  156. _print_json({
  157. "meeting_ref": meeting_ref.to_dict(),
  158. "transcript_available": bool(transcript_artifact and transcript_text),
  159. "transcript_artifact": transcript_artifact.to_dict() if transcript_artifact else None,
  160. "transcript_preview": (transcript_text or "")[:240] or None,
  161. "recording_count": len(recordings),
  162. "recordings": [recording.to_dict() for recording in recordings[:5]],
  163. "call_record": call_record.to_dict() if call_record else None})
  164. def _cmd_subscriptions(args) -> None:
  165. store = _open_store(args)
  166. subscriptions = asyncio.run(build_graph_client().collect_paginated("/subscriptions"))
  167. for sub in subscriptions:
  168. try:
  169. sync_graph_subscription_record(store, sub, status="active")
  170. except Exception:
  171. continue
  172. _print_records("Microsoft Graph subscription(s)", "No Microsoft Graph subscriptions found.", [
  173. (sub.get("id") or "unknown", [
  174. ("resource", sub.get("resource") or "unknown", True),
  175. ("changeType", sub.get("changeType") or "unknown", True),
  176. ("expires", sub.get("expirationDateTime"), False),
  177. ("notify", sub.get("notificationUrl"), False)])
  178. for sub in subscriptions])
  179. def _cmd_subscribe(args) -> None:
  180. store = _open_store(args)
  181. resource = _text(args, "resource")
  182. payload = {
  183. "changeType": _text(args, "change_type") or _default_change_type_for_resource(resource),
  184. "notificationUrl": _text(args, "notification_url"),
  185. "resource": resource,
  186. "expirationDateTime": _text(args, "expiration") or utc_timestamp(1),
  187. "latestSupportedTlsVersion": _text(args, "latest_supported_tls_version") or "v1_2"}
  188. if client_state := _text(args, "client_state"):
  189. payload["clientState"] = client_state
  190. if lifecycle_url := _text(args, "lifecycle_notification_url"):
  191. payload["lifecycleNotificationUrl"] = lifecycle_url
  192. result = asyncio.run(build_graph_client().post_json("/subscriptions", json_body=payload))
  193. sync_graph_subscription_record(store, result, status="active")
  194. _print_json(result)
  195. def _cmd_renew_subscription(args) -> None:
  196. subscription_id = _text(args, "subscription_id")
  197. expiration = _text(args, "expiration")
  198. store = _open_store(args)
  199. result = asyncio.run(build_graph_client().patch_json(f"/subscriptions/{subscription_id}", json_body={"expirationDateTime": expiration}))
  200. merged = {"id": subscription_id, **(result or {}), "expirationDateTime": expiration}
  201. sync_graph_subscription_record(store, merged, status="active", renewed=True)
  202. _print_json(merged)
  203. def _cmd_delete_subscription(args) -> None:
  204. subscription_id = _text(args, "subscription_id")
  205. store = _open_store(args)
  206. result = asyncio.run(build_graph_client().delete(f"/subscriptions/{subscription_id}"))
  207. store.delete_subscription(subscription_id)
  208. _print_json({"subscription_id": subscription_id, "result": result})
  209. def _cmd_maintain_subscriptions(args) -> None:
  210. _print_json(asyncio.run(maintain_graph_subscriptions(
  211. client=build_graph_client(), store=_open_store(args),
  212. renew_within_hours=_int_arg(args, "renew_within_hours", 24), extend_hours=_int_arg(args, "extend_hours", 24),
  213. dry_run=bool(getattr(args, "dry_run", False)), client_state=_text(args, "client_state") or None)))
  214. def _cmd_token_health(args) -> None:
  215. provider = MicrosoftGraphTokenProvider.from_env()
  216. payload = dict(provider.inspect_token_health())
  217. if getattr(args, "force_refresh", False):
  218. try:
  219. token = asyncio.run(provider.get_access_token(force_refresh=True))
  220. payload["last_refresh_succeeded"] = True
  221. payload["access_token_length"] = len(token or "")
  222. except Exception as exc:
  223. payload["last_refresh_succeeded"] = False
  224. payload["refresh_error"] = str(exc)
  225. _print_json(payload)
  226. def _opt(flag: str, **kwargs: Any) -> tuple[str, dict[str, Any]]:
  227. return flag, kwargs
  228. _STORE_PATH = _opt("--store-path", default="")
  229. _EMPTY = {"default": ""}
  230. # Single source of truth for subcommands: (name, aliases, help, arguments, handler).
  231. # Order defines both the --help listing and the usage string.
  232. _SUBCOMMANDS: list[tuple[str, list[str], str, list[tuple[str, dict[str, Any]]], Callable[[Any], None]]] = [
  233. ("list", ["ls"], "List recent Teams pipeline jobs",
  234. [_opt("--limit", type=int, default=20), _opt("--status", **_EMPTY), _STORE_PATH], _cmd_list),
  235. ("show", [], "Show a stored Teams pipeline job", [_opt("job_id"), _STORE_PATH], _cmd_show),
  236. ("run", ["replay"], "Replay a stored Teams pipeline job", [_opt("job_id"), _STORE_PATH], _cmd_run),
  237. ("fetch", ["test"], "Dry-run meeting artifact resolution",
  238. [_opt("--meeting-id", **_EMPTY), _opt("--join-web-url", **_EMPTY),
  239. _opt("--organizer-user-id", default="", help="Microsoft Entra user ID for organizer-scoped online meeting lookup"),
  240. _opt("--tenant-id", **_EMPTY), _opt("--call-record-id", **_EMPTY)], _cmd_fetch),
  241. ("subscriptions", ["subs"], "List Graph subscriptions", [_STORE_PATH], _cmd_subscriptions),
  242. ("subscribe", [], "Create a Microsoft Graph subscription",
  243. [_opt("--resource", required=True), _opt("--notification-url", required=True), _opt("--change-type", **_EMPTY),
  244. _opt("--expiration", **_EMPTY), _opt("--client-state", **_EMPTY), _opt("--lifecycle-notification-url", **_EMPTY),
  245. _opt("--latest-supported-tls-version", default="v1_2"), _STORE_PATH], _cmd_subscribe),
  246. ("renew-subscription", [], "Renew a Microsoft Graph subscription",
  247. [_opt("subscription_id"), _opt("--expiration", required=True), _STORE_PATH], _cmd_renew_subscription),
  248. ("delete-subscription", [], "Delete a Microsoft Graph subscription", [_opt("subscription_id"), _STORE_PATH], _cmd_delete_subscription),
  249. ("maintain-subscriptions", [], "Renew near-expiry managed subscriptions",
  250. [_opt("--renew-within-hours", type=int, default=24), _opt("--extend-hours", type=int, default=24),
  251. _opt("--dry-run", action="store_true"), _STORE_PATH, _opt("--client-state", **_EMPTY)], _cmd_maintain_subscriptions),
  252. ("token-health", ["token"], "Inspect Graph token health", [_opt("--force-refresh", action="store_true")], _cmd_token_health),
  253. ("validate", [], "Validate Teams pipeline configuration snapshot", [_STORE_PATH], _cmd_validate)]
  254. _ACTIONS = {alias: handler for name, aliases, _help, _options, handler in _SUBCOMMANDS for alias in (name, *aliases)}
  255. # Handlers whose positional/required args are validated up front (all must be non-blank), with the message printed.
  256. _REQUIRED_ARGS: dict[Callable[[Any], None], tuple[tuple[str, ...], str]] = {
  257. _cmd_show: (("job_id",), "job_id is required"),
  258. _cmd_run: (("job_id",), "job_id is required"),
  259. _cmd_renew_subscription: (("subscription_id", "expiration"), "subscription_id and --expiration are required"),
  260. _cmd_delete_subscription: (("subscription_id",), "subscription_id is required")}