The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(plugins/teams_pipeline): subcommand dispatch, unified download/Graph helpers, compact models
Tekniumeb60dd519e65
diff --git a/plugins/teams_pipeline/__init__.py b/plugins/teams_pipeline/__init__.pyindex 75d631fa41a..62523655c57 100644--- a/plugins/teams_pipeline/__init__.py+++ b/plugins/teams_pipeline/__init__.py@@ -1,7 +1,6 @@"""Teams meeting pipeline plugin.-Registers only operator-facing CLI surfaces. The agent should invoke these via-the terminal tool; no model tools are added by this plugin.+Registers only operator-facing CLI surfaces (invoked by the agent via the terminal tool); no model tools."""from __future__ import annotationsdiff --git a/plugins/teams_pipeline/cli.py b/plugins/teams_pipeline/cli.pyindex c13cfd69ffa..6ac69b8e17d 100644--- a/plugins/teams_pipeline/cli.py+++ b/plugins/teams_pipeline/cli.py@@ -6,9 +6,7 @@ import argparseimport asyncioimport jsonimport os-from datetime import datetime, timedelta, timezone-from pathlib import Path-from typing import Any+from typing import Any, Callablefrom hermes_constants import display_hermes_homefrom gateway.config import Platform, load_gateway_config@@ -18,128 +16,72 @@ from plugins.teams_pipeline.meetings import (list_recording_artifacts,resolve_meeting_reference,)-from plugins.teams_pipeline.models import GraphSubscriptionfrom plugins.teams_pipeline.pipeline import TeamsMeetingPipelinefrom plugins.teams_pipeline.store import TeamsPipelineStore, resolve_teams_pipeline_store_pathfrom plugins.teams_pipeline.subscriptions import (build_graph_client,maintain_graph_subscriptions,+ sync_graph_subscription_record,+ utc_timestamp,)from tools.microsoft_graph_auth import MicrosoftGraphConfigError, MicrosoftGraphTokenProviderdef register_cli(subparser: argparse.ArgumentParser) -> None:subs = subparser.add_subparsers(dest="teams_pipeline_action")-- list_p = subs.add_parser("list", aliases=["ls"], help="List recent Teams pipeline jobs")- list_p.add_argument("--limit", type=int, default=20)- list_p.add_argument("--status", default="")- list_p.add_argument("--store-path", default="")-- show_p = subs.add_parser("show", help="Show a stored Teams pipeline job")- show_p.add_argument("job_id")- show_p.add_argument("--store-path", default="")-- run_p = subs.add_parser("run", aliases=["replay"], help="Replay a stored Teams pipeline job")- run_p.add_argument("job_id")- run_p.add_argument("--store-path", default="")-- fetch_p = subs.add_parser("fetch", aliases=["test"], help="Dry-run meeting artifact resolution")- fetch_p.add_argument("--meeting-id", default="")- fetch_p.add_argument("--join-web-url", default="")- fetch_p.add_argument(- "--organizer-user-id",- default="",- help="Microsoft Entra user ID for organizer-scoped online meeting lookup",- )- fetch_p.add_argument("--tenant-id", default="")- fetch_p.add_argument("--call-record-id", default="")-- subs_p = subs.add_parser("subscriptions", aliases=["subs"], help="List Graph subscriptions")- subs_p.add_argument("--store-path", default="")-- sub_p = subs.add_parser("subscribe", help="Create a Microsoft Graph subscription")- sub_p.add_argument("--resource", required=True)- sub_p.add_argument("--notification-url", required=True)- sub_p.add_argument("--change-type", default="")- sub_p.add_argument("--expiration", default="")- sub_p.add_argument("--client-state", default="")- sub_p.add_argument("--lifecycle-notification-url", default="")- sub_p.add_argument("--latest-supported-tls-version", default="v1_2")- sub_p.add_argument("--store-path", default="")-- renew_p = subs.add_parser("renew-subscription", help="Renew a Microsoft Graph subscription")- renew_p.add_argument("subscription_id")- renew_p.add_argument("--expiration", required=True)- renew_p.add_argument("--store-path", default="")-- delete_p = subs.add_parser("delete-subscription", help="Delete a Microsoft Graph subscription")- delete_p.add_argument("subscription_id")- delete_p.add_argument("--store-path", default="")-- maintain_p = subs.add_parser("maintain-subscriptions", help="Renew near-expiry managed subscriptions")- maintain_p.add_argument("--renew-within-hours", type=int, default=24)- maintain_p.add_argument("--extend-hours", type=int, default=24)- maintain_p.add_argument("--dry-run", action="store_true")- maintain_p.add_argument("--store-path", default="")- maintain_p.add_argument("--client-state", default="")-- token_p = subs.add_parser("token-health", aliases=["token"], help="Inspect Graph token health")- token_p.add_argument("--force-refresh", action="store_true")-- validate_p = subs.add_parser("validate", help="Validate Teams pipeline configuration snapshot")- validate_p.add_argument("--store-path", default="")-+ for name, aliases, help_text, options, _handler in _SUBCOMMANDS:+ parser = subs.add_parser(name, aliases=aliases, help=help_text)+ for flag, kwargs in options:+ parser.add_argument(flag, **kwargs)subparser.set_defaults(func=teams_pipeline_command)def teams_pipeline_command(args: argparse.Namespace) -> int:action = getattr(args, "teams_pipeline_action", None)if not action:- print(- "Usage: hermes teams-pipeline "- "{list|show|run|fetch|subscriptions|subscribe|renew-subscription|delete-subscription|maintain-subscriptions|token-health|validate}"- )+ print(f"Usage: hermes teams-pipeline {{{'|'.join(spec[0] for spec in _SUBCOMMANDS)}}}")return 2-+ handler = _ACTIONS.get(action)+ if handler is None:+ print(f"Unknown teams-pipeline action: {action}")+ return 2+ required, missing_message = _REQUIRED_ARGS.get(handler, ((), ""))+ if not all(_text(args, name) for name in required):+ print(missing_message)+ return 0try:- if action in {"list", "ls"}:- _cmd_list(args)- elif action == "show":- _cmd_show(args)- elif action in {"run", "replay"}:- _cmd_run(args)- elif action in {"fetch", "test"}:- _cmd_fetch(args)- elif action in {"subscriptions", "subs"}:- _cmd_subscriptions(args)- elif action == "subscribe":- _cmd_subscribe(args)- elif action == "renew-subscription":- _cmd_renew_subscription(args)- elif action == "delete-subscription":- _cmd_delete_subscription(args)- elif action == "maintain-subscriptions":- _cmd_maintain_subscriptions(args)- elif action in {"token-health", "token"}:- _cmd_token_health(args)- elif action == "validate":- _cmd_validate(args)- else:- print(f"Unknown teams-pipeline action: {action}")- return 2+ handler(args)return 0except MicrosoftGraphConfigError:print(_graph_setup_hint())return 1-def _run_async(coro):- return asyncio.run(coro)+def _text(args: argparse.Namespace, name: str) -> str:+ """Stripped string form of an optional CLI arg ('' when absent/None)."""+ return str(getattr(args, name, "") or "").strip()-def _store_path(path_arg: str | None) -> Path:- return resolve_teams_pipeline_store_path(path_arg)+def _open_store(args: argparse.Namespace) -> TeamsPipelineStore:+ return TeamsPipelineStore(resolve_teams_pipeline_store_path(getattr(args, "store_path", None)))+++def _print_json(payload: Any) -> None:+ print(json.dumps(payload, indent=2, sort_keys=True))+++def _print_records(noun: str, empty_message: str, records: list[tuple[Any, list[tuple[str, Any, bool]]]]) -> None:+ """Print bulleted records; fields are (label, value, required) — optional fields skip falsy values."""+ if not records:+ print(empty_message)+ return+ print(f"\n{len(records)} {noun}:\n")+ for title, fields in records:+ print(f" ◆ {title}")+ for label, value, required in fields:+ if required or value:+ print(f" {label}: {value}")+ print()def _graph_setup_hint() -> str:@@ -154,21 +96,17 @@ def _graph_setup_hint() -> str:"""-def _iso_utc_timestamp(hours_from_now: int) -> str:- return (datetime.now(timezone.utc) + timedelta(hours=hours_from_now)).replace(- microsecond=0- ).isoformat().replace("+00:00", "Z")+# Graph only emits "created" for the artifact/callRecord collection resources; meetings use "updated".+_CREATED_RESOURCE_PREFIXES = (+ "communications/onlinemeetings/getalltranscripts",+ "communications/onlinemeetings/getallrecordings",+ "communications/callrecords",+)def _default_change_type_for_resource(resource: str) -> str:normalized = str(resource or "").strip().lower()- if normalized.startswith("communications/onlinemeetings/getalltranscripts"):- return "created"- if normalized.startswith("communications/onlinemeetings/getallrecordings"):- return "created"- if normalized.startswith("communications/callrecords"):- return "created"- return "updated"+ return "created" if normalized.startswith(_CREATED_RESOURCE_PREFIXES) else "updated"def _compact_job(job: dict) -> dict:@@ -181,21 +119,8 @@ def _compact_job(job: dict) -> dict:return payload-def _sync_subscription_record(- store: TeamsPipelineStore,- subscription_payload: dict[str, Any],- *,- status: str = "active",- renewed: bool = False,-) -> dict[str, Any]:- normalized = GraphSubscription.from_dict(subscription_payload).to_dict()- normalized["status"] = status- if renewed:- normalized["latest_renewal_at"] = _iso_utc_timestamp(0)- return store.upsert_subscription(normalized["subscription_id"], normalized)---def _validate_configuration_snapshot(store: TeamsPipelineStore) -> dict[str, Any]:+def _cmd_validate(args) -> None:+ store = _open_store(args)env = os.environissues: list[str] = []warnings: list[str] = []@@ -203,11 +128,7 @@ def _validate_configuration_snapshot(store: TeamsPipelineStore) -> dict[str, Anywebhook_config = gateway_config.platforms.get(Platform.MSGRAPH_WEBHOOK)teams_config = gateway_config.platforms.get(Platform("teams"))- graph = {- "tenant_id": bool(env.get("MSGRAPH_TENANT_ID")),- "client_id": bool(env.get("MSGRAPH_CLIENT_ID")),- "client_secret": bool(env.get("MSGRAPH_CLIENT_SECRET")),- }+ graph = {key: bool(env.get(f"MSGRAPH_{key.upper()}")) for key in ("tenant_id", "client_id", "client_secret")}webhook_enabled = bool(webhook_config and webhook_config.enabled)teams_enabled = bool(teams_config and teams_config.enabled)teams_extra = dict((teams_config.extra or {}) if teams_config else {})@@ -223,246 +144,205 @@ def _validate_configuration_snapshot(store: TeamsPipelineStore) -> dict[str, Anyif not teams_extra.get("incoming_webhook_url"):issues.append("TEAMS_INCOMING_WEBHOOK_URL is required for incoming_webhook mode.")elif teams_mode == "graph":- missing: list[str] = []- has_graph_delivery_token = bool(- (teams_config.token if teams_config else "") or teams_extra.get("access_token")- )- has_graph_app_credentials = all(graph.values())- if not has_graph_delivery_token and not has_graph_app_credentials:- missing.append(- "TEAMS_GRAPH_ACCESS_TOKEN or complete MSGRAPH_* app credentials"- )+ # Graph delivery can authenticate with either a dedicated delivery token or the app-only creds.+ has_graph_delivery_token = bool(teams_config.token or teams_extra.get("access_token"))+ if not has_graph_delivery_token and not all(graph.values()):+ issues.append("TEAMS_GRAPH_ACCESS_TOKEN or complete MSGRAPH_* app credentials is required for graph delivery mode.")if not teams_extra.get("team_id"):- missing.append("TEAMS_TEAM_ID")- channel_id = teams_extra.get("channel_id") or teams_extra.get("chat_id")- if not channel_id and not (teams_config and teams_config.home_channel):- missing.append("TEAMS_CHANNEL_ID")- for key in missing:- issues.append(f"{key} is required for graph delivery mode.")+ issues.append("TEAMS_TEAM_ID is required for graph delivery mode.")+ if not (teams_extra.get("channel_id") or teams_extra.get("chat_id") or teams_config.home_channel):+ issues.append("TEAMS_CHANNEL_ID is required for graph delivery mode.")else:warnings.append("TEAMS_DELIVERY_MODE is not set.")- return {- "ok": not issues,- "issues": issues,- "warnings": warnings,- "graph_config": graph,- "webhook_enabled": webhook_enabled,- "teams_enabled": teams_enabled,- "teams_delivery_mode": teams_mode,- "store_path": str(store.path),- "store_stats": store.stats(),- }+ _print_json({+ "ok": not issues, "issues": issues, "warnings": warnings, "graph_config": graph,+ "webhook_enabled": webhook_enabled, "teams_enabled": teams_enabled, "teams_delivery_mode": teams_mode,+ "store_path": str(store.path), "store_stats": store.stats(),+ })def _cmd_list(args) -> None:- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- jobs = list(store.list_jobs().values())- status = str(getattr(args, "status", "") or "").strip().lower()+ jobs = list(_open_store(args).list_jobs().values())+ status = _text(args, "status").lower()if status:jobs = [job for job in jobs if str(job.get("status") or "").lower() == status]jobs.sort(key=lambda item: str((item or {}).get("updated_at") or ""), reverse=True)- limit = max(1, min(int(getattr(args, "limit", 20) or 20), 100))- jobs = jobs[:limit]-- if not jobs:- print("No Teams meeting pipeline jobs found.")- return-- print(f"\n{len(jobs)} Teams pipeline job(s):\n")- for job in jobs:- meeting_id = ((job.get("meeting_ref") or {}).get("meeting_id") or "unknown")- print(f" ◆ {job.get('job_id')}")- print(f" status: {job.get('status')}")- print(f" meeting: {meeting_id}")- if job.get("selected_artifact_strategy"):- print(f" strategy: {job.get('selected_artifact_strategy')}")- if job.get("updated_at"):- print(f" updated: {job.get('updated_at')}")- if job.get("error_info"):- print(f" error: {job.get('error_info')}")- print()+ jobs = jobs[: max(1, min(int(getattr(args, "limit", 20) or 20), 100))]+ _print_records("Teams pipeline job(s)", "No Teams meeting pipeline jobs found.", [+ (job.get("job_id"), [+ ("status", job.get("status"), True),+ ("meeting", (job.get("meeting_ref") or {}).get("meeting_id") or "unknown", True),+ ("strategy", job.get("selected_artifact_strategy"), False),+ ("updated", job.get("updated_at"), False),+ ("error", job.get("error_info"), False),+ ])+ for job in jobs+ ])def _cmd_show(args) -> None:- job_id = str(getattr(args, "job_id", "") or "").strip()- if not job_id:- print("job_id is required")- return- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- job = store.get_job(job_id)+ job_id = _text(args, "job_id")+ job = _open_store(args).get_job(job_id)if not job:print(f"Unknown job: {job_id}")return- print(json.dumps(_compact_job(job), indent=2, sort_keys=True))+ _print_json(_compact_job(job))def _cmd_run(args) -> None:- job_id = str(getattr(args, "job_id", "") or "").strip()- if not job_id:- print("job_id is required")- return- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- pipeline = TeamsMeetingPipeline(graph_client=build_graph_client(), store=store, config={})- result = _run_async(pipeline.run_job(job_id))- print(json.dumps(_compact_job(result.to_dict()), indent=2, sort_keys=True))+ pipeline = TeamsMeetingPipeline(graph_client=build_graph_client(), store=_open_store(args), config={})+ _print_json(_compact_job(asyncio.run(pipeline.run_job(_text(args, "job_id"))).to_dict()))def _cmd_fetch(args) -> None:- meeting_id = str(getattr(args, "meeting_id", "") or "").strip() or None- join_web_url = str(getattr(args, "join_web_url", "") or "").strip() or None- organizer_user_id = str(getattr(args, "organizer_user_id", "") or "").strip() or None- tenant_id = str(getattr(args, "tenant_id", "") or "").strip() or None- call_record_id = str(getattr(args, "call_record_id", "") or "").strip() or None+ meeting_id = _text(args, "meeting_id") or None+ join_web_url = _text(args, "join_web_url") or Noneif not meeting_id and not join_web_url:print("meeting_id or join_web_url is required")returnclient = build_graph_client()- meeting_ref = _run_async(- resolve_meeting_reference(- client,- meeting_id=meeting_id,- join_web_url=join_web_url,- tenant_id=tenant_id,- organizer_user_id=organizer_user_id,- )- )- transcript_artifact, transcript_text = _run_async(fetch_preferred_transcript_text(client, meeting_ref))- recordings = _run_async(list_recording_artifacts(client, meeting_ref))- call_record = _run_async(- enrich_meeting_with_call_record(client, meeting_ref, call_record_id=call_record_id)- )- print(- json.dumps(- {- "meeting_ref": meeting_ref.to_dict(),- "transcript_available": bool(transcript_artifact and transcript_text),- "transcript_artifact": transcript_artifact.to_dict() if transcript_artifact else None,- "transcript_preview": (transcript_text or "")[:240] or None,- "recording_count": len(recordings),- "recordings": [recording.to_dict() for recording in recordings[:5]],- "call_record": call_record.to_dict() if call_record else None,- },- indent=2,- sort_keys=True,- )+ meeting_ref = asyncio.run(resolve_meeting_reference(+ client, meeting_id=meeting_id, join_web_url=join_web_url,+ tenant_id=_text(args, "tenant_id") or None, organizer_user_id=_text(args, "organizer_user_id") or None,+ ))+ transcript_artifact, transcript_text = asyncio.run(fetch_preferred_transcript_text(client, meeting_ref))+ recordings = asyncio.run(list_recording_artifacts(client, meeting_ref))+ call_record = asyncio.run(+ enrich_meeting_with_call_record(client, meeting_ref, call_record_id=_text(args, "call_record_id") or None))+ _print_json({+ "meeting_ref": meeting_ref.to_dict(),+ "transcript_available": bool(transcript_artifact and transcript_text),+ "transcript_artifact": transcript_artifact.to_dict() if transcript_artifact else None,+ "transcript_preview": (transcript_text or "")[:240] or None,+ "recording_count": len(recordings),+ "recordings": [recording.to_dict() for recording in recordings[:5]],+ "call_record": call_record.to_dict() if call_record else None,+ })def _cmd_subscriptions(args) -> None:- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- client = build_graph_client()- subscriptions = _run_async(client.collect_paginated("/subscriptions"))+ store = _open_store(args)+ subscriptions = asyncio.run(build_graph_client().collect_paginated("/subscriptions"))for sub in subscriptions:try:- _sync_subscription_record(store, sub, status="active")+ sync_graph_subscription_record(store, sub, status="active")except Exception:continue- if not subscriptions:- print("No Microsoft Graph subscriptions found.")- return-- print(f"\n{len(subscriptions)} Microsoft Graph subscription(s):\n")- for sub in subscriptions:- print(f" ◆ {sub.get('id') or 'unknown'}")- print(f" resource: {sub.get('resource') or 'unknown'}")- print(f" changeType: {sub.get('changeType') or 'unknown'}")- if sub.get("expirationDateTime"):- print(f" expires: {sub.get('expirationDateTime')}")- if sub.get("notificationUrl"):- print(f" notify: {sub.get('notificationUrl')}")- print()+ _print_records("Microsoft Graph subscription(s)", "No Microsoft Graph subscriptions found.", [+ (sub.get("id") or "unknown", [+ ("resource", sub.get("resource") or "unknown", True),+ ("changeType", sub.get("changeType") or "unknown", True),+ ("expires", sub.get("expirationDateTime"), False),+ ("notify", sub.get("notificationUrl"), False),+ ])+ for sub in subscriptions+ ])def _cmd_subscribe(args) -> None:- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- resource = str(getattr(args, "resource", "") or "").strip()- notification_url = str(getattr(args, "notification_url", "") or "").strip()- change_type = str(getattr(args, "change_type", "") or "").strip() or _default_change_type_for_resource(resource)- expiration = str(getattr(args, "expiration", "") or "").strip() or _iso_utc_timestamp(1)- client_state = str(getattr(args, "client_state", "") or "").strip()- lifecycle_url = str(getattr(args, "lifecycle_notification_url", "") or "").strip()- tls_version = str(getattr(args, "latest_supported_tls_version", "") or "").strip() or "v1_2"-+ store = _open_store(args)+ resource = _text(args, "resource")payload = {- "changeType": change_type,- "notificationUrl": notification_url,+ "changeType": _text(args, "change_type") or _default_change_type_for_resource(resource),+ "notificationUrl": _text(args, "notification_url"),"resource": resource,- "expirationDateTime": expiration,- "latestSupportedTlsVersion": tls_version,+ "expirationDateTime": _text(args, "expiration") or utc_timestamp(1),+ "latestSupportedTlsVersion": _text(args, "latest_supported_tls_version") or "v1_2",}- if client_state:+ if client_state := _text(args, "client_state"):payload["clientState"] = client_state- if lifecycle_url:+ if lifecycle_url := _text(args, "lifecycle_notification_url"):payload["lifecycleNotificationUrl"] = lifecycle_url- result = _run_async(build_graph_client().post_json("/subscriptions", json_body=payload))- _sync_subscription_record(store, result, status="active")- print(json.dumps(result, indent=2, sort_keys=True))+ result = asyncio.run(build_graph_client().post_json("/subscriptions", json_body=payload))+ sync_graph_subscription_record(store, result, status="active")+ _print_json(result)def _cmd_renew_subscription(args) -> None:- subscription_id = str(getattr(args, "subscription_id", "") or "").strip()- expiration = str(getattr(args, "expiration", "") or "").strip()- if not subscription_id or not expiration:- print("subscription_id and --expiration are required")- return-- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- result = _run_async(- build_graph_client().patch_json(- f"/subscriptions/{subscription_id}",- json_body={"expirationDateTime": expiration},- )- )+ subscription_id = _text(args, "subscription_id")+ expiration = _text(args, "expiration")+ store = _open_store(args)+ result = asyncio.run(build_graph_client().patch_json(f"/subscriptions/{subscription_id}", json_body={"expirationDateTime": expiration}))merged = {"id": subscription_id, **(result or {}), "expirationDateTime": expiration}- _sync_subscription_record(store, merged, status="active", renewed=True)- print(json.dumps(merged, indent=2, sort_keys=True))+ sync_graph_subscription_record(store, merged, status="active", renewed=True)+ _print_json(merged)def _cmd_delete_subscription(args) -> None:- subscription_id = str(getattr(args, "subscription_id", "") or "").strip()- if not subscription_id:- print("subscription_id is required")- return- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- result = _run_async(build_graph_client().delete(f"/subscriptions/{subscription_id}"))+ subscription_id = _text(args, "subscription_id")+ store = _open_store(args)+ result = asyncio.run(build_graph_client().delete(f"/subscriptions/{subscription_id}"))store.delete_subscription(subscription_id)- print(json.dumps({"subscription_id": subscription_id, "result": result}, indent=2, sort_keys=True))+ _print_json({"subscription_id": subscription_id, "result": result})def _cmd_maintain_subscriptions(args) -> None:- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- result = _run_async(- maintain_graph_subscriptions(- client=build_graph_client(),- store=store,- renew_within_hours=int(getattr(args, "renew_within_hours", 24) or 24),- extend_hours=int(getattr(args, "extend_hours", 24) or 24),- dry_run=bool(getattr(args, "dry_run", False)),- client_state=str(getattr(args, "client_state", "") or "").strip() or None,- )- )- print(json.dumps(result, indent=2, sort_keys=True))+ _print_json(asyncio.run(maintain_graph_subscriptions(+ client=build_graph_client(), store=_open_store(args),+ renew_within_hours=int(getattr(args, "renew_within_hours", 24) or 24),+ extend_hours=int(getattr(args, "extend_hours", 24) or 24),+ dry_run=bool(getattr(args, "dry_run", False)), client_state=_text(args, "client_state") or None,+ )))def _cmd_token_health(args) -> None:provider = MicrosoftGraphTokenProvider.from_env()- health = provider.inspect_token_health()- payload = dict(health)+ payload = dict(provider.inspect_token_health())if getattr(args, "force_refresh", False):try:- token = _run_async(provider.get_access_token(force_refresh=True))+ token = asyncio.run(provider.get_access_token(force_refresh=True))payload["last_refresh_succeeded"] = Truepayload["access_token_length"] = len(token or "")except Exception as exc:payload["last_refresh_succeeded"] = Falsepayload["refresh_error"] = str(exc)- print(json.dumps(payload, indent=2, sort_keys=True))---def _cmd_validate(args) -> None:- store = TeamsPipelineStore(_store_path(getattr(args, "store_path", None)))- snapshot = _validate_configuration_snapshot(store)- print(json.dumps(snapshot, indent=2, sort_keys=True))+ _print_json(payload)+++def _opt(flag: str, **kwargs: Any) -> tuple[str, dict[str, Any]]:+ return flag, kwargs+++_STORE_PATH = _opt("--store-path", default="")+_EMPTY = {"default": ""}++# Single source of truth for subcommands: (name, aliases, help, arguments, handler).+# Order defines both the --help listing and the usage string.+_SUBCOMMANDS: list[tuple[str, list[str], str, list[tuple[str, dict[str, Any]]], Callable[[Any], None]]] = [+ ("list", ["ls"], "List recent Teams pipeline jobs",+ [_opt("--limit", type=int, default=20), _opt("--status", **_EMPTY), _STORE_PATH], _cmd_list),+ ("show", [], "Show a stored Teams pipeline job", [_opt("job_id"), _STORE_PATH], _cmd_show),+ ("run", ["replay"], "Replay a stored Teams pipeline job", [_opt("job_id"), _STORE_PATH], _cmd_run),+ ("fetch", ["test"], "Dry-run meeting artifact resolution",+ [_opt("--meeting-id", **_EMPTY), _opt("--join-web-url", **_EMPTY),+ _opt("--organizer-user-id", default="", help="Microsoft Entra user ID for organizer-scoped online meeting lookup"),+ _opt("--tenant-id", **_EMPTY), _opt("--call-record-id", **_EMPTY)], _cmd_fetch),+ ("subscriptions", ["subs"], "List Graph subscriptions", [_STORE_PATH], _cmd_subscriptions),+ ("subscribe", [], "Create a Microsoft Graph subscription",+ [_opt("--resource", required=True), _opt("--notification-url", required=True), _opt("--change-type", **_EMPTY),+ _opt("--expiration", **_EMPTY), _opt("--client-state", **_EMPTY), _opt("--lifecycle-notification-url", **_EMPTY),+ _opt("--latest-supported-tls-version", default="v1_2"), _STORE_PATH], _cmd_subscribe),+ ("renew-subscription", [], "Renew a Microsoft Graph subscription",+ [_opt("subscription_id"), _opt("--expiration", required=True), _STORE_PATH], _cmd_renew_subscription),+ ("delete-subscription", [], "Delete a Microsoft Graph subscription",+ [_opt("subscription_id"), _STORE_PATH], _cmd_delete_subscription),+ ("maintain-subscriptions", [], "Renew near-expiry managed subscriptions",+ [_opt("--renew-within-hours", type=int, default=24), _opt("--extend-hours", type=int, default=24),+ _opt("--dry-run", action="store_true"), _STORE_PATH, _opt("--client-state", **_EMPTY)], _cmd_maintain_subscriptions),+ ("token-health", ["token"], "Inspect Graph token health", [_opt("--force-refresh", action="store_true")], _cmd_token_health),+ ("validate", [], "Validate Teams pipeline configuration snapshot", [_STORE_PATH], _cmd_validate),+]++_ACTIONS = {alias: handler for name, aliases, _help, _options, handler in _SUBCOMMANDS for alias in (name, *aliases)}++# Handlers whose positional/required args are validated up front (all must be non-blank), with the message printed.+_REQUIRED_ARGS: dict[Callable[[Any], None], tuple[tuple[str, ...], str]] = {+ _cmd_show: (("job_id",), "job_id is required"),+ _cmd_run: (("job_id",), "job_id is required"),+ _cmd_renew_subscription: (("subscription_id", "expiration"), "subscription_id and --expiration are required"),+ _cmd_delete_subscription: (("subscription_id",), "subscription_id is required"),+}diff --git a/plugins/teams_pipeline/meetings.py b/plugins/teams_pipeline/meetings.pyindex c6f6ec3d9cd..97a24cd692e 100644--- a/plugins/teams_pipeline/meetings.py+++ b/plugins/teams_pipeline/meetings.py@@ -6,107 +6,76 @@ import base64import binasciiimport reimport tempfile+from functools import partialfrom pathlib import Path-from typing import Any+from typing import Any, Awaitablefrom urllib.parse import quote, unquotefrom plugins.teams_pipeline.models import MeetingArtifact, TeamsMeetingReffrom tools.microsoft_graph_client import MicrosoftGraphAPIError, MicrosoftGraphClient-# Graph uses both slash keys (users/{id}/...) and quoted keys (users('{id}')/...).+# Graph uses both slash keys (users/{id}/...) and quoted keys (users('{id}')/...),+# so every segment pattern has a quoted group and a slash group._USERS_MEETING_RE = re.compile(r"(?i)(?:^|/)users(?:\('([^']+)'\)|/([^/'()]+))/onlineMeetings(?:\('([^']+)'\)|/([^/'?]+))")-_COMM_MEETING_RE = re.compile(- r"(?i)(?:^|/)communications/onlineMeetings(?:\('([^']+)'\)|/([^/'?]+))"-)+_COMM_MEETING_RE = re.compile(r"(?i)(?:^|/)communications/onlineMeetings(?:\('([^']+)'\)|/([^/'?]+))")_TRANSCRIPT_RE = re.compile(r"(?i)/transcripts(?:\('([^']+)'\)|/([^/'?]+))")_RECORDING_RE = re.compile(r"(?i)/recordings(?:\('([^']+)'\)|/([^/'?]+))")-_RESOURCE_SENTINELS = frozenset(- {- "getalltranscripts",- "getallrecordings",- "transcripts",- "recordings",- }-)+# Collection function names that the meeting regex can capture in place of a real meeting id.+_RESOURCE_SENTINELS = frozenset({"getalltranscripts", "getallrecordings", "transcripts", "recordings"})class TeamsMeetingError(RuntimeError):"""Base class for Teams meeting pipeline failures."""-class TeamsMeetingNotFoundError(TeamsMeetingError):"""Raised when the meeting cannot be resolved from Graph."""-class TeamsMeetingArtifactNotFoundError(TeamsMeetingError):"""Raised when a transcript or recording cannot be found."""-class TeamsMeetingPermissionError(TeamsMeetingError):"""Raised when Graph access is denied for the requested resource."""+def _match_id(match: re.Match[str] | None, *groups: int) -> str | None:+ """Unquoted, stripped value of the first non-empty capture group, or None."""+ if match is None:+ return None+ return unquote(next((match.group(g) for g in groups if match.group(g)), "")).strip() or None++def parse_graph_meeting_resource(resource: str) -> dict[str, str | None]:"""Parse organizer, meeting, and artifact ids from a Graph resource or @odata.id."""-text = str(resource or "").strip()- organizer_user_id: str | None = None- meeting_id: str | None = None- transcript_id: str | None = None- recording_id: str | None = None-users_match = _USERS_MEETING_RE.search(text)- if users_match:- organizer_user_id = unquote(users_match.group(1) or users_match.group(2) or "").strip() or None- meeting_id = unquote(users_match.group(3) or users_match.group(4) or "").strip() or None-- if not meeting_id:- comm_match = _COMM_MEETING_RE.search(text)- if comm_match:- meeting_id = unquote(comm_match.group(1) or comm_match.group(2) or "").strip() or None-+ meeting_id = _match_id(users_match, 3, 4) or _match_id(_COMM_MEETING_RE.search(text), 1, 2)if meeting_id and meeting_id.lower() in _RESOURCE_SENTINELS:meeting_id = None-- transcript_match = _TRANSCRIPT_RE.search(text)- if transcript_match:- transcript_id = unquote(transcript_match.group(1) or transcript_match.group(2) or "").strip() or None-- recording_match = _RECORDING_RE.search(text)- if recording_match:- recording_id = unquote(recording_match.group(1) or recording_match.group(2) or "").strip() or None-return {- "organizer_user_id": organizer_user_id,+ "organizer_user_id": _match_id(users_match, 1, 2),"meeting_id": meeting_id,- "transcript_id": transcript_id,- "recording_id": recording_id,+ "transcript_id": _match_id(_TRANSCRIPT_RE.search(text), 1, 2),+ "recording_id": _match_id(_RECORDING_RE.search(text), 1, 2),}def looks_like_transcript_id(value: str, *, odata_type: str | None = None) -> bool:"""True when a Graph id is a callTranscript artifact rather than an onlineMeeting."""-if "calltranscript" in str(odata_type or "").lower():return Truetext = str(value or "")- if "transcript" in text.lower():- return True- return "transcript" in _decoded_id_hint(text)+ return "transcript" in text.lower() or "transcript" in _decoded_id_hint(text)def _decoded_id_hint(value: str) -> str:"""Best-effort base64 decode of a Graph id for artifact-marker sniffing.- Graph transcript ids are base64url blobs whose *decoded* payload carries a- ``...-TranscriptV2`` suffix while the encoded form contains no readable- marker (this is exactly the id shape from getAllTranscripts- ``resourceData.id``). Returns lowercase decoded text, or "" when the value- does not decode.+ Transcript ids from getAllTranscripts ``resourceData.id`` are base64url blobs whose+ *decoded* payload carries a ``...-TranscriptV2`` suffix while the encoded form has+ no readable marker. Returns lowercase decoded text, or "" when it does not decode."""-stripped = value.strip()if len(stripped) < 16:return ""@@ -119,19 +88,15 @@ def _decoded_id_hint(value: str) -> str:return ""-def _meeting_path(meeting_ref: TeamsMeetingRef | str) -> str:- if isinstance(meeting_ref, TeamsMeetingRef):- meeting_id = meeting_ref.meeting_id- organizer_user_id = meeting_ref.organizer_user_id- else:- meeting_id = str(meeting_ref)- organizer_user_id = None- encoded_meeting_id = quote(meeting_id, safe="")+def _meetings_collection(organizer_user_id: str | None) -> str:+ """Organizer-scoped collection when the organizer is known (required for app-only Graph access)."""if organizer_user_id:- return (- f"/users/{quote(organizer_user_id, safe='')}/onlineMeetings/{encoded_meeting_id}"- )- return f"/communications/onlineMeetings/{encoded_meeting_id}"+ return f"/users/{quote(organizer_user_id, safe='')}/onlineMeetings"+ return "/communications/onlineMeetings"+++def _meeting_path(meeting_ref: TeamsMeetingRef) -> str:+ return f"{_meetings_collection(meeting_ref.organizer_user_id)}/{quote(meeting_ref.meeting_id, safe='')}"def _wrap_graph_error(exc: MicrosoftGraphAPIError, *, missing_message: str) -> TeamsMeetingError:@@ -142,231 +107,149 @@ def _wrap_graph_error(exc: MicrosoftGraphAPIError, *, missing_message: str) -> Treturn TeamsMeetingError(str(exc))-def _parse_organizer_user_id(payload: dict[str, Any]) -> str | None:- organizer = payload.get("organizer")- if not isinstance(organizer, dict):- return None- identity = organizer.get("identity")- if not isinstance(identity, dict):- return None- user = identity.get("user")- if not isinstance(user, dict):- return None- return user.get("id")+async def _graph(awaitable: Awaitable[Any], *, missing_message: str) -> Any:+ """Await a Graph client call, translating MicrosoftGraphAPIError into TeamsMeetingError subclasses."""+ try:+ return await awaitable+ except MicrosoftGraphAPIError as exc:+ raise _wrap_graph_error(exc, missing_message=missing_message) from exc-def _parse_thread_id(payload: dict[str, Any]) -> str | None:- chat = payload.get("chatInfo")- if isinstance(chat, dict):- thread_id = chat.get("threadId")- if thread_id:- return str(thread_id)- return payload.get("threadId")+def _parse_organizer_user_id(payload: dict[str, Any]) -> str | None:+ organizer = payload.get("organizer")+ identity = organizer.get("identity") if isinstance(organizer, dict) else None+ user = identity.get("user") if isinstance(identity, dict) else None+ return user.get("id") if isinstance(user, dict) else Nonedef _normalize_meeting_ref(- payload: dict[str, Any],- *,- tenant_id: str | None = None,- organizer_user_id: str | None = None,+ payload: dict[str, Any], *, tenant_id: str | None = None, organizer_user_id: str | None = None) -> TeamsMeetingRef:metadata = {key: payload.get(key)- for key in ("subject", "startDateTime", "endDateTime", "createdDateTime")+ for key in ("subject", "startDateTime", "endDateTime", "createdDateTime", "participants")if payload.get(key) is not None}- participants = payload.get("participants")- if participants is not None:- metadata["participants"] = participants+ chat = payload.get("chatInfo")+ thread_id = str(chat["threadId"]) if isinstance(chat, dict) and chat.get("threadId") else payload.get("threadId")return TeamsMeetingRef(meeting_id=str(payload.get("id") or "").strip(),organizer_user_id=organizer_user_id or _parse_organizer_user_id(payload),- join_web_url=payload.get("joinWebUrl"),- calendar_event_id=payload.get("calendarEventId"),- thread_id=_parse_thread_id(payload),- tenant_id=tenant_id or payload.get("tenantId"),- metadata=metadata,+ join_web_url=payload.get("joinWebUrl"), calendar_event_id=payload.get("calendarEventId"),+ thread_id=thread_id, tenant_id=tenant_id or payload.get("tenantId"), metadata=metadata,)-def _normalize_artifact(- artifact_type: str,- payload: dict[str, Any],- *,- default_source_url: str | None = None,-) -> MeetingArtifact:- metadata = dict(payload)- download_url = (- payload.get("@microsoft.graph.downloadUrl")- or payload.get("downloadUrl")- or payload.get("recordingContentUrl")- or payload.get("transcriptContentUrl")- )- source_url = payload.get("webUrl") or payload.get("contentUrl") or default_source_url+def _normalize_artifact(artifact_type: str, payload: dict[str, Any]) -> MeetingArtifact:return MeetingArtifact(artifact_type=artifact_type, # type: ignore[arg-type]artifact_id=str(payload.get("id") or "").strip(),display_name=payload.get("displayName") or payload.get("name"),content_type=payload.get("contentType") or payload.get("fileMimeType"),- source_url=source_url,- download_url=download_url,+ source_url=payload.get("webUrl") or payload.get("contentUrl"),+ download_url=(+ payload.get("@microsoft.graph.downloadUrl") or payload.get("downloadUrl")+ or payload.get("recordingContentUrl") or payload.get("transcriptContentUrl")+ ),created_at=payload.get("createdDateTime"),available_at=payload.get("lastModifiedDateTime") or payload.get("meetingEndDateTime"),- size_bytes=payload.get("size"),- metadata=metadata,+ size_bytes=payload.get("size"), metadata=dict(payload),)def _transcript_sort_key(artifact: MeetingArtifact) -> tuple[int, int, str]:+ """Prefer completed, downloadable, most recent transcripts (in that priority order)."""status = str(artifact.metadata.get("status") or "").lower()has_download = int(bool(artifact.download_url or artifact.source_url))is_completed = int(status in {"available", "completed", "succeeded"})- timestamp = ""- if artifact.available_at is not None:- timestamp = artifact.available_at.isoformat()- elif artifact.created_at is not None:- timestamp = artifact.created_at.isoformat()- return (is_completed, has_download, timestamp)---def _recording_download_path(meeting_ref: TeamsMeetingRef, artifact: MeetingArtifact) -> str:- if artifact.download_url:- return artifact.download_url- return f"{_meeting_path(meeting_ref)}/recordings/{quote(artifact.artifact_id, safe='')}/content"---def _transcript_download_path(meeting_ref: TeamsMeetingRef, artifact: MeetingArtifact) -> str:- if artifact.download_url:- return artifact.download_url- return f"{_meeting_path(meeting_ref)}/transcripts/{quote(artifact.artifact_id, safe='')}/content"+ stamp = artifact.available_at or artifact.created_at+ return (is_completed, has_download, stamp.isoformat() if stamp is not None else "")async def resolve_meeting_reference(- client: MicrosoftGraphClient,- *,- meeting_id: str | None = None,- join_web_url: str | None = None,- tenant_id: str | None = None,- organizer_user_id: str | None = None,+ client: MicrosoftGraphClient, *, meeting_id: str | None = None, join_web_url: str | None = None,+ tenant_id: str | None = None, organizer_user_id: str | None = None,) -> TeamsMeetingRef:if meeting_id and looks_like_transcript_id(meeting_id):- if join_web_url:- meeting_id = None- else:+ if not join_web_url:raise TeamsMeetingError("Refusing to GET /communications/onlineMeetings/{id} with a transcript id. ""Graph v1.0 does not support that id format; use the organizer-scoped meeting ""id from the notification @odata.id, or a join URL.")+ meeting_id = None+ collection = _meetings_collection(organizer_user_id)if meeting_id:- try:- payload = await client.get_json(- _meeting_path(- TeamsMeetingRef(meeting_id=meeting_id, organizer_user_id=organizer_user_id)- )- )- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(exc, missing_message=f"Teams meeting not found: {meeting_id}") from exc+ missing = f"Teams meeting not found: {meeting_id}"+ path = f"{collection}/{quote(meeting_id, safe='')}"+ payload = await _graph(client.get_json(path), missing_message=missing)if not isinstance(payload, dict) or not payload.get("id"):- raise TeamsMeetingNotFoundError(f"Teams meeting not found: {meeting_id}")- return _normalize_meeting_ref(- payload,- tenant_id=tenant_id,- organizer_user_id=organizer_user_id,- )-- if join_web_url:- escaped_join_url = join_web_url.replace("'", "''")- lookup_path = "/communications/onlineMeetings"- if organizer_user_id:- lookup_path = f"/users/{quote(organizer_user_id, safe='')}/onlineMeetings"- try:- payload = await client.get_json(- lookup_path,- params={"$filter": f"JoinWebUrl eq '{escaped_join_url}'"},- )- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(- exc,- missing_message=f"Teams meeting not found for join URL: {join_web_url}",- ) from exc- candidates = payload.get("value") if isinstance(payload, dict) else None+ raise TeamsMeetingNotFoundError(missing)+ elif join_web_url:+ missing = f"Teams meeting not found for join URL: {join_web_url}"+ params = {"$filter": f"JoinWebUrl eq '{join_web_url.replace(chr(39), chr(39) * 2)}'"}+ listing = await _graph(client.get_json(collection, params=params), missing_message=missing)+ candidates = listing.get("value") if isinstance(listing, dict) else Noneif not isinstance(candidates, list) or not candidates:- raise TeamsMeetingNotFoundError(f"Teams meeting not found for join URL: {join_web_url}")- return _normalize_meeting_ref(- candidates[0],- tenant_id=tenant_id,- organizer_user_id=organizer_user_id,- )-- raise ValueError("Either meeting_id or join_web_url is required.")+ raise TeamsMeetingNotFoundError(missing)+ payload = candidates[0]+ else:+ raise ValueError("Either meeting_id or join_web_url is required.")+ return _normalize_meeting_ref(payload, tenant_id=tenant_id, organizer_user_id=organizer_user_id)-async def list_transcript_artifacts(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,+async def _list_artifacts(+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef, *, artifact_type: str) -> list[MeetingArtifact]:- try:- payloads = await client.collect_paginated(f"{_meeting_path(meeting_ref)}/transcripts")- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(- exc,- missing_message=f"No transcripts found for Teams meeting {meeting_ref.meeting_id}",- ) from exc- return [_normalize_artifact("transcript", payload) for payload in payloads if isinstance(payload, dict)]+ collection = f"{artifact_type}s"+ payloads = await _graph(+ client.collect_paginated(f"{_meeting_path(meeting_ref)}/{collection}"),+ missing_message=f"No {collection} found for Teams meeting {meeting_ref.meeting_id}",+ )+ return [_normalize_artifact(artifact_type, payload) for payload in payloads if isinstance(payload, dict)]+++list_transcript_artifacts = partial(_list_artifacts, artifact_type="transcript")+list_recording_artifacts = partial(_list_artifacts, artifact_type="recording")+++async def _download_artifact(+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef, artifact: MeetingArtifact, destination: Path, *,+ kind: str, **download_kwargs: Any,+) -> dict[str, Any]:+ path = artifact.download_url or f"{_meeting_path(meeting_ref)}/{kind}s/{quote(artifact.artifact_id, safe='')}/content"+ return await _graph(+ client.download_to_file(path, destination, **download_kwargs),+ missing_message=f"{kind.capitalize()} {artifact.artifact_id} not found for meeting {meeting_ref.meeting_id}",+ )def select_preferred_transcript(candidates: list[MeetingArtifact]) -> MeetingArtifact | None:transcripts = [candidate for candidate in candidates if candidate.artifact_type == "transcript"]- if not transcripts:- return None- return sorted(transcripts, key=_transcript_sort_key, reverse=True)[0]+ return max(transcripts, key=_transcript_sort_key) if transcripts else Noneasync def download_transcript_text(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,- transcript: MeetingArtifact,- *,+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef, transcript: MeetingArtifact, *,encoding: str = "utf-8",) -> str:suffix = Path(transcript.display_name or "transcript.vtt").suffix or ".txt"- with tempfile.NamedTemporaryFile(prefix="teams-transcript-", suffix=suffix, delete=False) as handle:- destination = Path(handle.name)- try:+ with tempfile.TemporaryDirectory(prefix="teams-transcript-", ignore_cleanup_errors=True) as tmp_dir:+ destination = Path(tmp_dir) / f"transcript{suffix}"# Graph's transcript /content endpoint rejects JSON content negotiation.- await client.download_to_file(- _transcript_download_path(meeting_ref, transcript),- destination,- headers={"Accept": "text/vtt"},+ await _download_artifact(+ client, meeting_ref, transcript, destination, kind="transcript", headers={"Accept": "text/vtt"})text = destination.read_text(encoding=encoding).strip()- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(- exc,- missing_message=(- f"Transcript {transcript.artifact_id} not found for meeting {meeting_ref.meeting_id}"- ),- ) from exc- finally:- try:- destination.unlink(missing_ok=True)- except OSError:- pass-if not text:- raise TeamsMeetingArtifactNotFoundError(- f"Transcript {transcript.artifact_id} for meeting {meeting_ref.meeting_id} was empty."- )+ raise TeamsMeetingArtifactNotFoundError(f"Transcript {transcript.artifact_id} for meeting {meeting_ref.meeting_id} was empty.")return textasync def fetch_preferred_transcript_text(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef) -> tuple[MeetingArtifact | None, str | None]:- transcripts = await list_transcript_artifacts(client, meeting_ref)- transcript = select_preferred_transcript(transcripts)+ transcript = select_preferred_transcript(await list_transcript_artifacts(client, meeting_ref))if transcript is None:return None, Nonetry:@@ -375,57 +258,30 @@ async def fetch_preferred_transcript_text(return None, None-async def list_recording_artifacts(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,-) -> list[MeetingArtifact]:- try:- payloads = await client.collect_paginated(f"{_meeting_path(meeting_ref)}/recordings")- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(- exc,- missing_message=f"No recordings found for Teams meeting {meeting_ref.meeting_id}",- ) from exc- return [_normalize_artifact("recording", payload) for payload in payloads if isinstance(payload, dict)]--async def download_recording_artifact(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,- recording: MeetingArtifact,- destination: str | Path,+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef, recording: MeetingArtifact, destination: str | Path,) -> dict[str, Any]:destination_path = Path(destination)- try:- result = await client.download_to_file(- _recording_download_path(meeting_ref, recording),- destination_path,- )- except MicrosoftGraphAPIError as exc:- raise _wrap_graph_error(- exc,- missing_message=f"Recording {recording.artifact_id} not found for meeting {meeting_ref.meeting_id}",- ) from exc+ result = await _download_artifact(client, meeting_ref, recording, destination_path, kind="recording")return {- "artifact": recording.to_dict(),- "path": str(destination_path),+ "artifact": recording.to_dict(), "path": str(destination_path),"size_bytes": result.get("size_bytes") or recording.size_bytes,"content_type": result.get("content_type") or recording.content_type,}-async def fetch_call_record_artifact(- client: MicrosoftGraphClient,- *,- call_record_id: str,+async def enrich_meeting_with_call_record(+ client: MicrosoftGraphClient, meeting_ref: TeamsMeetingRef, *, call_record_id: str | None = None,allow_permission_errors: bool = True,) -> MeetingArtifact | None:+ """Call records need the extra CallRecords.Read.All scope, so denial is optional-soft (None)."""+ call_record_id = str(call_record_id or meeting_ref.metadata.get("call_record_id") or "")+ if not call_record_id:+ return Nonetry:payload = await client.get_json(f"/communications/callRecords/{quote(call_record_id, safe='')}")except MicrosoftGraphAPIError as exc:- if exc.status_code in {401, 403} and allow_permission_errors:- return None- if exc.status_code == 404:+ if exc.status_code == 404 or (exc.status_code in {401, 403} and allow_permission_errors):return Noneraise _wrap_graph_error(exc, missing_message=f"Call record not found: {call_record_id}") from exc@@ -433,38 +289,14 @@ async def fetch_call_record_artifact(return Nonemetrics = {- "version": payload.get("version"),- "modalities": payload.get("modalities"),- "participant_count": len(payload.get("participants") or []),- "organizer": _parse_organizer_user_id(payload),+ "version": payload.get("version"), "modalities": payload.get("modalities"),+ "participant_count": len(payload.get("participants") or []), "organizer": _parse_organizer_user_id(payload),}- sessions = payload.get("sessions") or []- if sessions:+ if sessions := payload.get("sessions"):metrics["session_count"] = len(sessions)return MeetingArtifact(- artifact_type="call_record",- artifact_id=str(payload["id"]),- display_name=payload.get("type") or "call_record",- source_url=payload.get("webUrl"),- created_at=payload.get("startDateTime"),- available_at=payload.get("endDateTime"),+ artifact_type="call_record", artifact_id=str(payload["id"]), display_name=payload.get("type") or "call_record",+ source_url=payload.get("webUrl"), created_at=payload.get("startDateTime"), available_at=payload.get("endDateTime"),metadata={"call_record": payload, "metrics": metrics},)---async def enrich_meeting_with_call_record(- client: MicrosoftGraphClient,- meeting_ref: TeamsMeetingRef,- *,- call_record_id: str | None = None,- allow_permission_errors: bool = True,-) -> MeetingArtifact | None:- resolved_call_record_id = call_record_id or meeting_ref.metadata.get("call_record_id")- if not resolved_call_record_id:- return None- return await fetch_call_record_artifact(- client,- call_record_id=str(resolved_call_record_id),- allow_permission_errors=allow_permission_errors,- )diff --git a/plugins/teams_pipeline/models.py b/plugins/teams_pipeline/models.pyindex b1ae5196f51..3fcbf9801e2 100644--- a/plugins/teams_pipeline/models.py+++ b/plugins/teams_pipeline/models.py@@ -2,15 +2,16 @@from __future__ import annotations-from dataclasses import dataclass, field+from dataclasses import dataclass, field, fieldsfrom datetime import datetime, timezone-from typing import Any, Literal+from typing import Any, Callable, ClassVar, LiteralArtifactType = Literal["transcript", "recording", "call_record"]def _parse_datetime(value: Any) -> datetime | None:+ """Parse ISO-8601 (``Z`` accepted); naive values are assumed UTC, aware values keep their offset."""if value is None or isinstance(value, datetime):return valuetext = str(value).strip()@@ -19,24 +20,93 @@ def _parse_datetime(value: Any) -> datetime | None:if text.endswith("Z"):text = f"{text[:-1]}+00:00"parsed = datetime.fromisoformat(text)- if parsed.tzinfo is None:- return parsed.replace(tzinfo=timezone.utc)- return parsed+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parseddef _serialize_datetime(value: datetime | None) -> str | None:if value is None:return None- normalized = value.astimezone(timezone.utc)- return normalized.isoformat().replace("+00:00", "Z")+ return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")-def _clean_dict(values: dict[str, Any]) -> dict[str, Any]:- return {key: value for key, value in values.items() if value is not None}+def _camel(name: str) -> str:+ head, *rest = name.split("_")+ return head + "".join(part.title() for part in rest)+++def _pick(payload: dict[str, Any], *keys: str) -> Any:+ """Equivalent of ``payload.get(k1) or payload.get(k2) or ...`` (returns the last value when all are falsy)."""+ value = None+ for key in keys:+ value = payload.get(key)+ if value:+ return value+ return value+++def _str(value: Any) -> str:+ return str(value or "").strip()+++def _list(value: Any) -> list[Any]:+ return list(value or [])+++def _dict(value: Any) -> dict[str, Any]:+ return dict(value or {})+++def _nested(model: type["_Model"]) -> Callable[[Any], Any]:+ return lambda value: model.from_dict(value) if value else None+++class _Model:+ """Shared snake/camelCase ``from_dict`` and None-dropping ``to_dict`` for the dataclasses below.++ ``_ALIASES`` overrides the default ``(snake_name, camelName)`` lookup keys; ``_CONVERT`` post-processes+ the picked raw value; ``_REQUIRED`` string fields must be non-blank; ``_DATETIMES`` are parsed in place.+ """++ _ALIASES: ClassVar[dict[str, tuple[str, ...]]] = {}+ _CONVERT: ClassVar[dict[str, Callable[[Any], Any]]] = {}+ _REQUIRED: ClassVar[tuple[str, ...]] = ()+ _DATETIMES: ClassVar[tuple[str, ...]] = ()++ @classmethod+ def from_dict(cls, payload: dict[str, Any]):+ kwargs = {}+ for spec in fields(cls):+ value = _pick(payload, *cls._ALIASES.get(spec.name, (spec.name, _camel(spec.name))))+ convert = cls._CONVERT.get(spec.name)+ kwargs[spec.name] = convert(value) if convert else value+ return cls(**kwargs)++ def to_dict(self) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for spec in fields(self):+ value = getattr(self, spec.name)+ if isinstance(value, datetime):+ value = _serialize_datetime(value)+ elif isinstance(value, list):+ value = [item.to_dict() if isinstance(item, _Model) else item for item in value] or None+ elif isinstance(value, dict):+ value = value or None+ elif isinstance(value, _Model):+ value = value.to_dict()+ if value is not None:+ result[spec.name] = value+ return result++ def __post_init__(self) -> None:+ for name in self._REQUIRED:+ if not getattr(self, name).strip():+ raise ValueError(f"{type(self).__name__}.{name} is required.")+ for name in self._DATETIMES:+ setattr(self, name, _parse_datetime(getattr(self, name)))@dataclass-class GraphSubscription:+class GraphSubscription(_Model):subscription_id: strresource: strchange_type: str@@ -46,53 +116,22 @@ class GraphSubscription:latest_renewal_at: datetime | None = Nonestatus: str | None = None+ _ALIASES = {+ "subscription_id": ("subscription_id", "id"),+ "expiration_datetime": ("expiration_datetime", "expirationDateTime"),+ }+ _REQUIRED = ("subscription_id", "resource", "change_type", "notification_url")+ _CONVERT = dict.fromkeys(_REQUIRED, _str)+ _DATETIMES = ("expiration_datetime", "latest_renewal_at")+def __post_init__(self) -> None:- if not self.subscription_id.strip():- raise ValueError("GraphSubscription.subscription_id is required.")- if not self.resource.strip():- raise ValueError("GraphSubscription.resource is required.")- if not self.change_type.strip():- raise ValueError("GraphSubscription.change_type is required.")- if not self.notification_url.strip():- raise ValueError("GraphSubscription.notification_url is required.")- self.expiration_datetime = _parse_datetime(self.expiration_datetime)- self.latest_renewal_at = _parse_datetime(self.latest_renewal_at)+ super().__post_init__()if self.expiration_datetime is None:raise ValueError("GraphSubscription.expiration_datetime is required.")- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "GraphSubscription":- return cls(- subscription_id=str(payload.get("subscription_id") or payload.get("id") or "").strip(),- resource=str(payload.get("resource") or "").strip(),- change_type=str(payload.get("change_type") or payload.get("changeType") or "").strip(),- notification_url=str(- payload.get("notification_url") or payload.get("notificationUrl") or ""- ).strip(),- expiration_datetime=payload.get("expiration_datetime")- or payload.get("expirationDateTime"),- client_state=payload.get("client_state") or payload.get("clientState"),- latest_renewal_at=payload.get("latest_renewal_at") or payload.get("latestRenewalAt"),- status=payload.get("status"),- )-- def to_dict(self) -> dict[str, Any]:- return _clean_dict(- {- "subscription_id": self.subscription_id,- "resource": self.resource,- "change_type": self.change_type,- "notification_url": self.notification_url,- "expiration_datetime": _serialize_datetime(self.expiration_datetime),- "client_state": self.client_state,- "latest_renewal_at": _serialize_datetime(self.latest_renewal_at),- "status": self.status,- }- )-@dataclass-class TeamsMeetingRef:+class TeamsMeetingRef(_Model):meeting_id: strorganizer_user_id: str | None = Nonejoin_web_url: str | None = None@@ -101,38 +140,13 @@ class TeamsMeetingRef:tenant_id: str | None = Nonemetadata: dict[str, Any] = field(default_factory=dict)- def __post_init__(self) -> None:- if not self.meeting_id.strip():- raise ValueError("TeamsMeetingRef.meeting_id is required.")-- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "TeamsMeetingRef":- return cls(- meeting_id=str(payload.get("meeting_id") or payload.get("id") or "").strip(),- organizer_user_id=payload.get("organizer_user_id") or payload.get("organizerUserId"),- join_web_url=payload.get("join_web_url") or payload.get("joinWebUrl"),- calendar_event_id=payload.get("calendar_event_id") or payload.get("calendarEventId"),- thread_id=payload.get("thread_id") or payload.get("threadId"),- tenant_id=payload.get("tenant_id") or payload.get("tenantId"),- metadata=dict(payload.get("metadata") or {}),- )-- def to_dict(self) -> dict[str, Any]:- return _clean_dict(- {- "meeting_id": self.meeting_id,- "organizer_user_id": self.organizer_user_id,- "join_web_url": self.join_web_url,- "calendar_event_id": self.calendar_event_id,- "thread_id": self.thread_id,- "tenant_id": self.tenant_id,- "metadata": self.metadata or None,- }- )+ _ALIASES = {"meeting_id": ("meeting_id", "id")}+ _CONVERT = {"meeting_id": _str, "metadata": _dict}+ _REQUIRED = ("meeting_id",)@dataclass-class MeetingArtifact:+class MeetingArtifact(_Model):artifact_type: ArtifactTypeartifact_id: strdisplay_name: str | None = None@@ -144,58 +158,29 @@ class MeetingArtifact:size_bytes: int | None = Nonemetadata: dict[str, Any] = field(default_factory=dict)+ _ALIASES = {+ "artifact_id": ("artifact_id", "id"),+ "display_name": ("display_name", "displayName", "name"),+ "source_url": ("source_url", "sourceUrl", "webUrl"),+ "download_url": ("download_url", "downloadUrl", "@microsoft.graph.downloadUrl"),+ "created_at": ("created_at", "createdDateTime"),+ "available_at": ("available_at", "availableDateTime", "lastModifiedDateTime"),+ "size_bytes": ("size_bytes", "size"),+ }+ _CONVERT = {"artifact_id": _str, "metadata": _dict}+ _REQUIRED = ("artifact_id",)+ _DATETIMES = ("created_at", "available_at")+def __post_init__(self) -> None:if self.artifact_type not in {"transcript", "recording", "call_record"}:- raise ValueError(- "MeetingArtifact.artifact_type must be transcript, recording, or call_record."- )- if not self.artifact_id.strip():- raise ValueError("MeetingArtifact.artifact_id is required.")- self.created_at = _parse_datetime(self.created_at)- self.available_at = _parse_datetime(self.available_at)+ raise ValueError("MeetingArtifact.artifact_type must be transcript, recording, or call_record.")+ super().__post_init__()if self.size_bytes is not None:self.size_bytes = int(self.size_bytes)- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "MeetingArtifact":- return cls(- artifact_type=payload.get("artifact_type") or payload.get("artifactType"),- artifact_id=str(payload.get("artifact_id") or payload.get("id") or "").strip(),- display_name=payload.get("display_name")- or payload.get("displayName")- or payload.get("name"),- content_type=payload.get("content_type") or payload.get("contentType"),- source_url=payload.get("source_url") or payload.get("sourceUrl") or payload.get("webUrl"),- download_url=payload.get("download_url")- or payload.get("downloadUrl")- or payload.get("@microsoft.graph.downloadUrl"),- created_at=payload.get("created_at") or payload.get("createdDateTime"),- available_at=payload.get("available_at")- or payload.get("availableDateTime")- or payload.get("lastModifiedDateTime"),- size_bytes=payload.get("size_bytes") or payload.get("size"),- metadata=dict(payload.get("metadata") or {}),- )-- def to_dict(self) -> dict[str, Any]:- return _clean_dict(- {- "artifact_type": self.artifact_type,- "artifact_id": self.artifact_id,- "display_name": self.display_name,- "content_type": self.content_type,- "source_url": self.source_url,- "download_url": self.download_url,- "created_at": _serialize_datetime(self.created_at),- "available_at": _serialize_datetime(self.available_at),- "size_bytes": self.size_bytes,- "metadata": self.metadata or None,- }- )-@dataclass-class TeamsMeetingSummaryPayload:+class TeamsMeetingSummaryPayload(_Model):meeting_ref: TeamsMeetingReftitle: str | None = Nonestart_time: datetime | None = None@@ -214,61 +199,24 @@ class TeamsMeetingSummaryPayload:linear_target: str | None = Noneteams_target: str | None = None- def __post_init__(self) -> None:- self.start_time = _parse_datetime(self.start_time)- self.end_time = _parse_datetime(self.end_time)+ # Nested payloads are only read from their snake_case keys.+ _ALIASES = {"meeting_ref": ("meeting_ref",), "source_artifacts": ("source_artifacts",)}+ _CONVERT = {+ **dict.fromkeys(("participants", "key_decisions", "action_items", "risks"), _list),+ "call_metrics": _dict,+ "meeting_ref": TeamsMeetingRef.from_dict,+ "source_artifacts": lambda value: [MeetingArtifact.from_dict(item) for item in value or []],+ }+ _DATETIMES = ("start_time", "end_time")@classmethoddef from_dict(cls, payload: dict[str, Any]) -> "TeamsMeetingSummaryPayload":- return cls(- meeting_ref=TeamsMeetingRef.from_dict(payload["meeting_ref"]),- title=payload.get("title"),- start_time=payload.get("start_time") or payload.get("startTime"),- end_time=payload.get("end_time") or payload.get("endTime"),- participants=list(payload.get("participants") or []),- transcript_text=payload.get("transcript_text") or payload.get("transcriptText"),- summary=payload.get("summary"),- key_decisions=list(payload.get("key_decisions") or payload.get("keyDecisions") or []),- action_items=list(payload.get("action_items") or payload.get("actionItems") or []),- risks=list(payload.get("risks") or []),- call_metrics=dict(payload.get("call_metrics") or payload.get("callMetrics") or {}),- source_artifacts=[- MeetingArtifact.from_dict(item) for item in payload.get("source_artifacts", [])- ],- confidence=payload.get("confidence"),- confidence_notes=payload.get("confidence_notes") or payload.get("confidenceNotes"),- notion_target=payload.get("notion_target") or payload.get("notionTarget"),- linear_target=payload.get("linear_target") or payload.get("linearTarget"),- teams_target=payload.get("teams_target") or payload.get("teamsTarget"),- )-- def to_dict(self) -> dict[str, Any]:- return _clean_dict(- {- "meeting_ref": self.meeting_ref.to_dict(),- "title": self.title,- "start_time": _serialize_datetime(self.start_time),- "end_time": _serialize_datetime(self.end_time),- "participants": self.participants or None,- "transcript_text": self.transcript_text,- "summary": self.summary,- "key_decisions": self.key_decisions or None,- "action_items": self.action_items or None,- "risks": self.risks or None,- "call_metrics": self.call_metrics or None,- "source_artifacts": [artifact.to_dict() for artifact in self.source_artifacts]- or None,- "confidence": self.confidence,- "confidence_notes": self.confidence_notes,- "notion_target": self.notion_target,- "linear_target": self.linear_target,- "teams_target": self.teams_target,- }- )+ # meeting_ref is mandatory: a missing key raises KeyError rather than building a half-empty payload.+ return super().from_dict({**payload, "meeting_ref": payload["meeting_ref"]})@dataclass-class TeamsMeetingPipelineJob:+class TeamsMeetingPipelineJob(_Model):job_id: strevent_id: strsource_event_type: str@@ -282,69 +230,22 @@ class TeamsMeetingPipelineJob:summary_payload: TeamsMeetingSummaryPayload | None = Noneerror_info: dict[str, Any] = field(default_factory=dict)+ _REQUIRED = ("job_id", "event_id", "source_event_type", "dedupe_key", "status")+ _CONVERT = {+ **dict.fromkeys(_REQUIRED, _str),+ "retry_count": lambda value: value or 0,+ "meeting_ref": _nested(TeamsMeetingRef),+ "summary_payload": _nested(TeamsMeetingSummaryPayload),+ "error_info": _dict,+ }+ _DATETIMES = ("created_at", "updated_at")+def __post_init__(self) -> None:- if not self.job_id.strip():- raise ValueError("TeamsMeetingPipelineJob.job_id is required.")- if not self.event_id.strip():- raise ValueError("TeamsMeetingPipelineJob.event_id is required.")- if not self.source_event_type.strip():- raise ValueError("TeamsMeetingPipelineJob.source_event_type is required.")- if not self.dedupe_key.strip():- raise ValueError("TeamsMeetingPipelineJob.dedupe_key is required.")- if not self.status.strip():- raise ValueError("TeamsMeetingPipelineJob.status is required.")+ super().__post_init__()self.retry_count = int(self.retry_count)- self.created_at = _parse_datetime(self.created_at)- self.updated_at = _parse_datetime(self.updated_at)-- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "TeamsMeetingPipelineJob":- meeting_ref_payload = payload.get("meeting_ref") or payload.get("meetingRef")- summary_payload = payload.get("summary_payload") or payload.get("summaryPayload")- return cls(- job_id=str(payload.get("job_id") or payload.get("jobId") or "").strip(),- event_id=str(payload.get("event_id") or payload.get("eventId") or "").strip(),- source_event_type=str(- payload.get("source_event_type") or payload.get("sourceEventType") or ""- ).strip(),- dedupe_key=str(payload.get("dedupe_key") or payload.get("dedupeKey") or "").strip(),- status=str(payload.get("status") or "").strip(),- retry_count=payload.get("retry_count") or payload.get("retryCount") or 0,- created_at=payload.get("created_at") or payload.get("createdAt"),- updated_at=payload.get("updated_at") or payload.get("updatedAt"),- meeting_ref=TeamsMeetingRef.from_dict(meeting_ref_payload) if meeting_ref_payload else None,- selected_artifact_strategy=payload.get("selected_artifact_strategy")- or payload.get("selectedArtifactStrategy"),- summary_payload=TeamsMeetingSummaryPayload.from_dict(summary_payload)- if summary_payload- else None,- error_info=dict(payload.get("error_info") or payload.get("errorInfo") or {}),- )-- def to_dict(self) -> dict[str, Any]:- return _clean_dict(- {- "job_id": self.job_id,- "event_id": self.event_id,- "source_event_type": self.source_event_type,- "dedupe_key": self.dedupe_key,- "status": self.status,- "retry_count": self.retry_count,- "created_at": _serialize_datetime(self.created_at),- "updated_at": _serialize_datetime(self.updated_at),- "meeting_ref": self.meeting_ref.to_dict() if self.meeting_ref else None,- "selected_artifact_strategy": self.selected_artifact_strategy,- "summary_payload": self.summary_payload.to_dict() if self.summary_payload else None,- "error_info": self.error_info or None,- }- )__all__ = [- "ArtifactType",- "GraphSubscription",- "MeetingArtifact",- "TeamsMeetingPipelineJob",- "TeamsMeetingRef",- "TeamsMeetingSummaryPayload",+ "ArtifactType", "GraphSubscription", "MeetingArtifact",+ "TeamsMeetingPipelineJob", "TeamsMeetingRef", "TeamsMeetingSummaryPayload",]diff --git a/plugins/teams_pipeline/pipeline.py b/plugins/teams_pipeline/pipeline.pyindex 5f8ac912028..4b55479a04c 100644--- a/plugins/teams_pipeline/pipeline.py+++ b/plugins/teams_pipeline/pipeline.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import osimport shutilimport tempfileimport uuid@@ -15,9 +14,8 @@ from typing import Any, Awaitable, Callable, Optionalimport httpx-from agent.secret_scope import get_secret-from agent.auxiliary_client import async_call_llm, extract_content_or_reasoning+from agent.secret_scope import get_secretfrom hermes_constants import get_hermes_homefrom plugins.teams_pipeline.meetings import (download_recording_artifact,@@ -41,40 +39,32 @@ logger = logging.getLogger(__name__)TERMINAL_PIPELINE_STATES = {"completed", "failed", "retry_scheduled"}ACTIVE_PIPELINE_STATES = {- "received",- "resolving_meeting",- "fetching_transcript",- "downloading_recording",- "transcribing_audio",- "summarizing",- "writing_notion",- "writing_linear",- "sending_teams",+ "received", "resolving_meeting", "fetching_transcript", "downloading_recording",+ "transcribing_audio", "summarizing", "writing_notion", "writing_linear", "sending_teams",}+_AUDIO_SUFFIXES = {".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aac", ".webm"}+_SUMMARY_SYSTEM_PROMPT = (+ "You summarize meeting transcripts. Return only valid JSON with keys: "+ "summary, key_decisions, action_items, risks, confidence, confidence_notes."+)class TeamsPipelineError(RuntimeError):"""Base class for Teams meeting pipeline failures."""-class TeamsPipelineRetryableError(TeamsPipelineError):"""Raised when the pipeline should be retried later."""-class TeamsPipelineSinkError(TeamsPipelineError):"""Raised when an output sink fails."""-class TeamsPipelineArtifactNotFoundError(TeamsPipelineRetryableError):"""Raised when meeting artifacts are not yet available."""TranscribeFn = Callable[[str, Optional[str]], dict[str, Any]]SummarizeFn = Callable[..., Awaitable[dict[str, Any] | TeamsMeetingSummaryPayload]]-SinkFn = Callable[- [TeamsMeetingSummaryPayload, dict[str, Any], Optional[dict[str, Any]]],- Awaitable[dict[str, Any]],-]+SinkFn = Callable[[TeamsMeetingSummaryPayload, dict[str, Any], Optional[dict[str, Any]]], Awaitable[dict[str, Any]]]@dataclass@@ -102,171 +92,127 @@ class TeamsPipelineConfig:ffmpeg_extract_audio=bool(data.get("ffmpeg_extract_audio", True)),transcript_min_chars=int(data.get("transcript_min_chars", 80)),tmp_dir=Path(tmp_dir) if tmp_dir else None,- notion=data.get("notion"),- linear=data.get("linear"),+ notion=data.get("notion"), linear=data.get("linear"),teams_delivery=data.get("teams_delivery") or data.get("teamsDelivery"),)-class NotionWriter:- API_BASE = "https://api.notion.com/v1"- API_VERSION = "2025-09-03"+def _rich_text(content: str) -> dict[str, Any]:+ return {"rich_text": [{"text": {"content": content}}]}+++def _bullets(items: list[str]) -> str:+ return "\n".join(f"- {item}" for item in items)+++def _sections(payload: TeamsMeetingSummaryPayload) -> list[tuple[str, str]]:+ return [+ ("Summary", payload.summary or ""),+ ("Key Decisions", _bullets(payload.key_decisions)),+ ("Action Items", _bullets(payload.action_items)),+ ("Risks", _bullets(payload.risks)),+ ]+++class _HttpSinkWriter:+ """Shared API-key + httpx transport plumbing for the Notion/Linear sinks."""++ SECRET_NAME = ""def __init__(self, *, api_key: str | None = None, transport: httpx.AsyncBaseTransport | None = None) -> None:- self.api_key = (api_key or get_secret("NOTION_API_KEY", "") or "").strip()+ self.api_key = (api_key or get_secret(self.SECRET_NAME, "") or "").strip()self._transport = transport+ def _require_api_key(self) -> None:+ if not self.api_key:+ raise TeamsPipelineSinkError(f"{self.SECRET_NAME} is not configured.")++ async def _request(self, method: str, url: str, *, headers: dict[str, str], body: dict[str, Any]) -> dict[str, Any]:+ async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:+ response = await client.request(method, url, headers=headers, json=body)+ response.raise_for_status()+ return response.json()+++class NotionWriter(_HttpSinkWriter):+ API_BASE = "https://api.notion.com/v1"+ API_VERSION = "2025-09-03"+ SECRET_NAME = "NOTION_API_KEY"+async def write_summary(- self,- payload: TeamsMeetingSummaryPayload,- config: dict[str, Any],+ self, payload: TeamsMeetingSummaryPayload, config: dict[str, Any],existing_record: Optional[dict[str, Any]] = None,) -> dict[str, Any]:- if not self.api_key:- raise TeamsPipelineSinkError("NOTION_API_KEY is not configured.")-+ self._require_api_key()database_id = str(config.get("database_id") or config.get("databaseId") or "").strip()page_id = (existing_record or {}).get("page_id")if not database_id and not page_id:raise TeamsPipelineSinkError("Notion sink requires database_id or an existing page_id.")- headers = {- "Authorization": f"Bearer {self.api_key}",- "Notion-Version": self.API_VERSION,- "Content-Type": "application/json",- }- async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:- if page_id:- response = await client.patch(- f"{self.API_BASE}/pages/{page_id}",- headers=headers,- json={"properties": self._build_properties(payload, config)},- )- response.raise_for_status()- record = response.json()- else:- response = await client.post(- f"{self.API_BASE}/pages",- headers=headers,- json={- "parent": {"database_id": database_id},- "properties": self._build_properties(payload, config),- "children": self._build_blocks(payload),- },- )- response.raise_for_status()- record = response.json()-+ headers = {"Authorization": f"Bearer {self.api_key}", "Notion-Version": self.API_VERSION, "Content-Type": "application/json"}+ properties = self._build_properties(payload, config)+ # Re-runs update the existing page's properties only; body blocks are written once on create.+ if page_id:+ record = await self._request(+ "PATCH", f"{self.API_BASE}/pages/{page_id}", headers=headers, body={"properties": properties}+ )+ else:+ body = {"parent": {"database_id": database_id}, "properties": properties, "children": self._build_blocks(payload)}+ record = await self._request("POST", f"{self.API_BASE}/pages", headers=headers, body=body)return {"page_id": record["id"], "url": record.get("url")}def _build_properties(self, payload: TeamsMeetingSummaryPayload, config: dict[str, Any]) -> dict[str, Any]:- title_property = config.get("title_property", "Name")- summary_property = config.get("summary_property")- meeting_id_property = config.get("meeting_id_property")-- properties: dict[str, Any] = {- title_property: {- "title": [{"text": {"content": payload.title or f"Meeting {payload.meeting_ref.meeting_id}"}}]- }- }- if summary_property:- properties[summary_property] = {- "rich_text": [{"text": {"content": (payload.summary or "")[:1900]}}]- }- if meeting_id_property:- properties[meeting_id_property] = {- "rich_text": [{"text": {"content": payload.meeting_ref.meeting_id}}]- }+ title = payload.title or f"Meeting {payload.meeting_ref.meeting_id}"+ properties: dict[str, Any] = {config.get("title_property", "Name"): {"title": [{"text": {"content": title}}]}}+ if summary_property := config.get("summary_property"):+ properties[summary_property] = _rich_text((payload.summary or "")[:1900])+ if meeting_id_property := config.get("meeting_id_property"):+ properties[meeting_id_property] = _rich_text(payload.meeting_ref.meeting_id)return propertiesdef _build_blocks(self, payload: TeamsMeetingSummaryPayload) -> list[dict[str, Any]]:- sections = [- ("Summary", payload.summary or ""),- ("Key Decisions", "\n".join(f"- {item}" for item in payload.key_decisions)),- ("Action Items", "\n".join(f"- {item}" for item in payload.action_items)),- ("Risks", "\n".join(f"- {item}" for item in payload.risks)),- ]blocks: list[dict[str, Any]] = []- for heading, body in sections:- blocks.append(- {- "object": "block",- "type": "heading_2",- "heading_2": {"rich_text": [{"text": {"content": heading}}]},- }- )- blocks.append(- {- "object": "block",- "type": "paragraph",- "paragraph": {"rich_text": [{"text": {"content": body or "None"}}]},- }- )+ for heading, body in _sections(payload):+ blocks.append({"object": "block", "type": "heading_2", "heading_2": _rich_text(heading)})+ blocks.append({"object": "block", "type": "paragraph", "paragraph": _rich_text(body or "None")})return blocks-class LinearWriter:+class LinearWriter(_HttpSinkWriter):API_URL = "https://api.linear.app/graphql"-- def __init__(self, *, api_key: str | None = None, transport: httpx.AsyncBaseTransport | None = None) -> None:- self.api_key = (api_key or get_secret("LINEAR_API_KEY", "") or "").strip()- self._transport = transport+ SECRET_NAME = "LINEAR_API_KEY"+ _UPDATE_MUTATION = (+ "mutation($id: String!, $input: IssueUpdateInput!) "+ "{ issueUpdate(id: $id, input: $input) { success issue { id identifier url } } }"+ )+ _CREATE_MUTATION = (+ "mutation($input: IssueCreateInput!) "+ "{ issueCreate(input: $input) { success issue { id identifier url } } }"+ )async def write_summary(- self,- payload: TeamsMeetingSummaryPayload,- config: dict[str, Any],+ self, payload: TeamsMeetingSummaryPayload, config: dict[str, Any],existing_record: Optional[dict[str, Any]] = None,) -> dict[str, Any]:- if not self.api_key:- raise TeamsPipelineSinkError("LINEAR_API_KEY is not configured.")-+ self._require_api_key()headers = {"Authorization": self.api_key, "Content-Type": "application/json"}team_id = str(config.get("team_id") or config.get("teamId") or "").strip()- title = payload.title or f"Meeting Summary: {payload.meeting_ref.meeting_id}"- description = _render_summary_markdown(payload)+ issue_input = {"title": payload.title or f"Meeting Summary: {payload.meeting_ref.meeting_id}",+ "description": _render_summary_markdown(payload)}existing_issue_id = (existing_record or {}).get("issue_id")- async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:- if existing_issue_id:- response = await client.post(- self.API_URL,- headers=headers,- json={- "query": (- "mutation($id: String!, $input: IssueUpdateInput!) "- "{ issueUpdate(id: $id, input: $input) { success issue { id identifier url } } }"- ),- "variables": {- "id": existing_issue_id,- "input": {"title": title, "description": description},- },- },- )- else:- if not team_id:- raise TeamsPipelineSinkError("Linear sink requires team_id when creating a new issue.")- response = await client.post(- self.API_URL,- headers=headers,- json={- "query": (- "mutation($input: IssueCreateInput!) "- "{ issueCreate(input: $input) { success issue { id identifier url } } }"- ),- "variables": {"input": {"teamId": team_id, "title": title, "description": description}},- },- )- response.raise_for_status()- payload_json = response.json()+ if existing_issue_id:+ body = {"query": self._UPDATE_MUTATION, "variables": {"id": existing_issue_id, "input": issue_input}}+ else:+ if not team_id:+ raise TeamsPipelineSinkError("Linear sink requires team_id when creating a new issue.")+ body = {"query": self._CREATE_MUTATION, "variables": {"input": {"teamId": team_id, **issue_input}}}- issue = (- (((payload_json.get("data") or {}).get("issueUpdate") or {}).get("issue"))- or (((payload_json.get("data") or {}).get("issueCreate") or {}).get("issue"))- )+ payload_json = await self._request("POST", self.API_URL, headers=headers, body=body)+ data = payload_json.get("data") or {}+ issue = (data.get("issueUpdate") or {}).get("issue") or (data.get("issueCreate") or {}).get("issue")if not isinstance(issue, dict) or not issue.get("id"):raise TeamsPipelineSinkError(f"Linear write failed: {payload_json}")-return {"issue_id": issue["id"], "identifier": issue.get("identifier"), "url": issue.get("url")}@@ -274,16 +220,10 @@ class TeamsMeetingPipeline:"""Transcript-first Teams meeting pipeline with durable lifecycle state."""def __init__(- self,- *,- graph_client: Any,- store: TeamsPipelineStore,- config: TeamsPipelineConfig | dict[str, Any] | None = None,- transcribe_fn: TranscribeFn = transcribe_audio,- summarize_fn: Optional[SummarizeFn] = None,- notion_writer: Optional[NotionWriter] = None,- linear_writer: Optional[LinearWriter] = None,- teams_sender: Optional[SinkFn] = None,+ self, *, graph_client: Any, store: TeamsPipelineStore,+ config: TeamsPipelineConfig | dict[str, Any] | None = None, transcribe_fn: TranscribeFn = transcribe_audio,+ summarize_fn: Optional[SummarizeFn] = None, notion_writer: Optional[NotionWriter] = None,+ linear_writer: Optional[LinearWriter] = None, teams_sender: Optional[SinkFn] = None,) -> None:self.graph_client = graph_clientself.store = store@@ -313,8 +253,7 @@ class TeamsMeetingPipeline:organizer_user_id=organizer_user_id,tenant_id=resource_data.get("tenantId") or notification.get("tenantId"),metadata={- "notification": dict(notification),- "join_web_url": resource_data.get("joinWebUrl"),+ "notification": dict(notification), "join_web_url": resource_data.get("joinWebUrl"),"call_record_id": resource_data.get("callRecordId") or notification.get("callRecordId"),**extra_metadata,},@@ -325,6 +264,7 @@ class TeamsMeetingPipeline:async def run_notification(self, notification: dict[str, Any]) -> TeamsMeetingPipelineJob:job = self.create_job_from_notification(notification)+ # Only freshly "received" jobs run; terminal or in-flight duplicates are returned as-is.if job.status in TERMINAL_PIPELINE_STATES or job.status in ACTIVE_PIPELINE_STATES - {"received"}:return jobreturn await self.run_job(job.job_id)@@ -336,12 +276,11 @@ class TeamsMeetingPipeline:raise TeamsPipelineError(f"Job {job.job_id} has no meeting_ref.")artifacts: list[MeetingArtifact] = []-try:job = self._persist_job(job, status="resolving_meeting")notification = meeting_ref.metadata.get("notification") if isinstance(meeting_ref.metadata, dict) else {}- meeting_id = meeting_ref.meeting_id- organizer_user_id = meeting_ref.organizer_user_id+ meeting_id, organizer_user_id = meeting_ref.meeting_id, meeting_ref.organizer_user_id+ # Re-parse the stored notification: older jobs may have persisted a transcript id as meeting_id.if isinstance(notification, dict) and notification:parsed_id, parsed_org, _extra = _meeting_ids_from_notification(notification)if parsed_org:@@ -349,16 +288,13 @@ class TeamsMeetingPipeline:if parsed_id and not looks_like_transcript_id(parsed_id):meeting_id = parsed_idresolved_meeting = await resolve_meeting_reference(- self.graph_client,- meeting_id=meeting_id,+ self.graph_client, meeting_id=meeting_id, tenant_id=meeting_ref.tenant_id,join_web_url=meeting_ref.join_web_url or meeting_ref.metadata.get("join_web_url"),- tenant_id=meeting_ref.tenant_id,organizer_user_id=organizer_user_id,)if meeting_ref.metadata:resolved_meeting.metadata = {**meeting_ref.metadata, **resolved_meeting.metadata}- if not resolved_meeting.organizer_user_id:- resolved_meeting.organizer_user_id = meeting_ref.organizer_user_id+ resolved_meeting.organizer_user_id = resolved_meeting.organizer_user_id or meeting_ref.organizer_user_idjob.meeting_ref = resolved_meetingjob = self._persist_job(job, meeting_ref=resolved_meeting.to_dict())@@ -373,69 +309,43 @@ class TeamsMeetingPipeline:if len(transcript_text.strip()) < self.config.transcript_min_chars:transcript_text = None- if not transcript_text:- if self.config.transcript_required:- raise TeamsPipelineRetryableError(- f"Transcript unavailable for meeting {resolved_meeting.meeting_id}."- )- if not self.config.transcription_fallback:- raise TeamsPipelineArtifactNotFoundError(- "No transcript available and transcription fallback disabled "- f"for {resolved_meeting.meeting_id}."- )+ if transcript_text:+ job = self._persist_job(job, selected_artifact_strategy="transcript_first")+ elif self.config.transcript_required:+ raise TeamsPipelineRetryableError(f"Transcript unavailable for meeting {resolved_meeting.meeting_id}.")+ elif not self.config.transcription_fallback:+ raise TeamsPipelineArtifactNotFoundError(+ f"No transcript available and transcription fallback disabled for {resolved_meeting.meeting_id}."+ )+ else:job = self._persist_job(job, status="downloading_recording")recordings = await list_recording_artifacts(self.graph_client, resolved_meeting)if not recordings:- raise TeamsPipelineRetryableError(- f"Recording unavailable for meeting {resolved_meeting.meeting_id}."- )- recording = recordings[0]- artifacts.append(recording)- transcript_text = await self._transcribe_recording(job, resolved_meeting, recording)+ raise TeamsPipelineRetryableError(f"Recording unavailable for meeting {resolved_meeting.meeting_id}.")+ artifacts.append(recordings[0])+ transcript_text = await self._transcribe_recording(job, resolved_meeting, recordings[0])job = self._persist_job(job, selected_artifact_strategy="recording_stt_fallback")- else:- job = self._persist_job(job, selected_artifact_strategy="transcript_first")call_record_id = notification.get("callRecordId") or (meeting_ref.metadata or {}).get("call_record_id")- call_record = await enrich_meeting_with_call_record(- self.graph_client,- resolved_meeting,- call_record_id=call_record_id,- )+ call_record = await enrich_meeting_with_call_record(self.graph_client, resolved_meeting, call_record_id=call_record_id)if call_record is not None:artifacts.append(call_record)job = self._persist_job(job, status="summarizing")- generated = await self.summarize_fn(- resolved_meeting=resolved_meeting,- transcript_text=transcript_text or "",- artifacts=artifacts,- )- summary_payload = (- generated- if isinstance(generated, TeamsMeetingSummaryPayload)- else TeamsMeetingSummaryPayload.from_dict(generated)+ summary_payload = await self.summarize_fn(+ resolved_meeting=resolved_meeting, transcript_text=transcript_text or "", artifacts=artifacts)+ if not isinstance(summary_payload, TeamsMeetingSummaryPayload):+ summary_payload = TeamsMeetingSummaryPayload.from_dict(summary_payload)job.summary_payload = summary_payloadjob = self._persist_job(job, summary_payload=summary_payload.to_dict())await self._write_sinks(job, summary_payload)- job = self._persist_job(job, status="completed")- return job+ return self._persist_job(job, status="completed")except TeamsPipelineRetryableError as exc:- job = self._persist_job(- job,- status="retry_scheduled",- error_info={"message": str(exc), "retryable": True},- )- return job+ return self._persist_job(job, status="retry_scheduled", error_info={"message": str(exc), "retryable": True})except Exception as exc:- job = self._persist_job(- job,- status="failed",- error_info={"message": str(exc), "type": type(exc).__name__},- )- return job+ return self._persist_job(job, status="failed", error_info={"message": str(exc), "type": type(exc).__name__})def _coerce_job(self, job_or_id: TeamsMeetingPipelineJob | str) -> TeamsMeetingPipelineJob:if isinstance(job_or_id, TeamsMeetingPipelineJob):@@ -447,46 +357,27 @@ class TeamsMeetingPipeline:def _find_job_by_dedupe_key(self, dedupe_key: str) -> TeamsMeetingPipelineJob | None:for payload in self.store.list_jobs().values():- if not isinstance(payload, dict):- continue- if str(payload.get("dedupe_key") or "") != dedupe_key:- continue- return TeamsMeetingPipelineJob.from_dict(payload)+ if isinstance(payload, dict) and str(payload.get("dedupe_key") or "") == dedupe_key:+ return TeamsMeetingPipelineJob.from_dict(payload)return Nonedef _persist_job(self, job: TeamsMeetingPipelineJob, **updates: Any) -> TeamsMeetingPipelineJob:- payload = job.to_dict()- payload.update(updates)- stored = self.store.upsert_job(job.job_id, payload)+ stored = self.store.upsert_job(job.job_id, {**job.to_dict(), **updates})return TeamsMeetingPipelineJob.from_dict(stored)async def _transcribe_recording(- self,- job: TeamsMeetingPipelineJob,- meeting_ref: TeamsMeetingRef,- recording: MeetingArtifact,+ self, job: TeamsMeetingPipelineJob, meeting_ref: TeamsMeetingRef, recording: MeetingArtifact) -> str:temp_root = self.config.tmp_dir or (get_hermes_home() / "tmp" / "teams_pipeline")temp_root.mkdir(parents=True, exist_ok=True)with tempfile.TemporaryDirectory(dir=str(temp_root), prefix="teams-recording-") as tmp_dir:- # display_name comes from Graph API and is ultimately set by- # the meeting organizer — strip any directory components so a- # crafted name like "../../etc/cron.d/evil" can't escape tmp_dir.- # Path(...).name reduces "." / ".." / "" to themselves, so the- # dot-only basenames must be rejected explicitly (joining "tmp/.."- # resolves to the parent dir); fall back to the artifact id.+ # display_name is organizer-controlled Graph data: keep only the basename so a crafted+ # "../../etc/cron.d/evil" cannot escape tmp_dir. Path(...).name leaves "." / ".." / ""+ # unchanged (joining "tmp/.." resolves to the parent), so reject those explicitly.fallback_name = f"{recording.artifact_id}.mp4"- raw_name = recording.display_name or fallback_name- recording_name = Path(raw_name).name- if recording_name in ("", ".", ".."):- recording_name = fallback_name- recording_path = Path(tmp_dir) / recording_name- await download_recording_artifact(- self.graph_client,- meeting_ref,- recording,- recording_path,- )+ recording_name = Path(recording.display_name or fallback_name).name+ recording_path = Path(tmp_dir) / (fallback_name if recording_name in ("", ".", "..") else recording_name)+ await download_recording_artifact(self.graph_client, meeting_ref, recording, recording_path)audio_path = await self._prepare_audio_path(recording_path)job = self._persist_job(job, status="transcribing_audio")result = await asyncio.to_thread(self.transcribe_fn, str(audio_path), self.config.stt_model)@@ -498,62 +389,38 @@ class TeamsMeetingPipeline:return transcriptasync def _prepare_audio_path(self, recording_path: Path) -> Path:- if recording_path.suffix.lower() in {".wav", ".mp3", ".m4a", ".ogg", ".flac", ".aac", ".webm"}:- return recording_path- if not self.config.ffmpeg_extract_audio:+ if recording_path.suffix.lower() in _AUDIO_SUFFIXES or not self.config.ffmpeg_extract_audio:return recording_pathffmpeg = shutil.which("ffmpeg")if not ffmpeg:- raise TeamsPipelineRetryableError(- "Recording fallback requires ffmpeg for audio extraction, but ffmpeg was not found."- )+ raise TeamsPipelineRetryableError("Recording fallback requires ffmpeg for audio extraction, but ffmpeg was not found.")audio_path = recording_path.with_suffix(".wav")proc = await asyncio.create_subprocess_exec(- ffmpeg,- "-y",- "-i",- str(recording_path),- str(audio_path),- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,+ ffmpeg, "-y", "-i", str(recording_path), str(audio_path),+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,)_stdout, stderr = await proc.communicate()if proc.returncode != 0:- detail = stderr.decode("utf-8", errors="replace").strip()- raise TeamsPipelineRetryableError(f"ffmpeg audio extraction failed: {detail}")+ raise TeamsPipelineRetryableError(+ f"ffmpeg audio extraction failed: {stderr.decode('utf-8', errors='replace').strip()}"+ )return audio_pathasync def _generate_summary_payload(- self,- *,- resolved_meeting: TeamsMeetingRef,- transcript_text: str,- artifacts: list[MeetingArtifact],+ self, *, resolved_meeting: TeamsMeetingRef, transcript_text: str, artifacts: list[MeetingArtifact]) -> TeamsMeetingSummaryPayload:prompt = _build_summary_prompt(resolved_meeting, transcript_text, artifacts)try:response = await async_call_llm(- task="call",- messages=[- {- "role": "system",- "content": (- "You summarize meeting transcripts. Return only valid JSON with keys: "- "summary, key_decisions, action_items, risks, confidence, confidence_notes."- ),- },- {"role": "user", "content": prompt},- ],- temperature=0.2,- max_tokens=900,+ task="call", temperature=0.2, max_tokens=900,+ messages=[{"role": "system", "content": _SUMMARY_SYSTEM_PROMPT}, {"role": "user", "content": prompt}],)- content = extract_content_or_reasoning(response)- parsed = _parse_summary_json(content)+ parsed = _parse_summary_json(extract_content_or_reasoning(response))except Exception as exc:logger.info("Teams pipeline LLM summary unavailable, using heuristic summary: %s", exc)parsed = _heuristic_summary(transcript_text)- metrics = _collect_call_metrics(artifacts)+ teams_delivery = self.config.teams_delivery or {}return TeamsMeetingSummaryPayload(meeting_ref=resolved_meeting,title=str(resolved_meeting.metadata.get("subject") or f"Meeting {resolved_meeting.meeting_id}"),@@ -565,42 +432,30 @@ class TeamsMeetingPipeline:key_decisions=list(parsed.get("key_decisions") or []),action_items=list(parsed.get("action_items") or []),risks=list(parsed.get("risks") or []),- call_metrics=metrics,+ call_metrics=_collect_call_metrics(artifacts),source_artifacts=artifacts,- confidence=parsed.get("confidence"),- confidence_notes=parsed.get("confidence_notes"),+ confidence=parsed.get("confidence"), confidence_notes=parsed.get("confidence_notes"),notion_target=(self.config.notion or {}).get("database_id"),linear_target=(self.config.linear or {}).get("team_id"),- teams_target=(- (self.config.teams_delivery or {}).get("channel_id")- or (self.config.teams_delivery or {}).get("chat_id")- ),+ teams_target=teams_delivery.get("channel_id") or teams_delivery.get("chat_id"),)async def _write_sinks(self, job: TeamsMeetingPipelineJob, payload: TeamsMeetingSummaryPayload) -> None:- if self.config.notion and self.config.notion.get("enabled") and self.notion_writer:- job = self._persist_job(job, status="writing_notion")- sink_key = f"notion:{payload.meeting_ref.meeting_id}"- existing = self.store.get_sink_record(sink_key)- result = await self.notion_writer.write_summary(payload, self.config.notion, existing)- self.store.upsert_sink_record(sink_key, result)-- if self.config.linear and self.config.linear.get("enabled") and self.linear_writer:- job = self._persist_job(job, status="writing_linear")- sink_key = f"linear:{payload.meeting_ref.meeting_id}"- existing = self.store.get_sink_record(sink_key)- result = await self.linear_writer.write_summary(payload, self.config.linear, existing)- self.store.upsert_sink_record(sink_key, result)-- if self.config.teams_delivery and self.config.teams_delivery.get("enabled") and self.teams_sender:- job = self._persist_job(job, status="sending_teams")- sink_key = f"teams:{payload.meeting_ref.meeting_id}"+ # Sink order is part of the contract: Notion, then Linear, then Teams delivery.+ sinks = (+ ("notion", "writing_notion", self.config.notion, self.notion_writer),+ ("linear", "writing_linear", self.config.linear, self.linear_writer),+ ("teams", "sending_teams", self.config.teams_delivery, self.teams_sender),+ )+ for name, status, config, sink in sinks:+ if not (config and config.get("enabled") and sink):+ continue+ job = self._persist_job(job, status=status)+ sink_key = f"{name}:{payload.meeting_ref.meeting_id}"existing = self.store.get_sink_record(sink_key)- if hasattr(self.teams_sender, "write_summary"):- result = await self.teams_sender.write_summary(payload, self.config.teams_delivery, existing)- else:- result = await self.teams_sender(payload, self.config.teams_delivery, existing)- self.store.upsert_sink_record(sink_key, result)+ # Sinks may be writer objects (write_summary) or bare async callables.+ write: Any = getattr(sink, "write_summary", sink)+ self.store.upsert_sink_record(sink_key, await write(payload, config, existing))def _collect_call_metrics(artifacts: list[MeetingArtifact]) -> dict[str, Any]:@@ -608,20 +463,19 @@ def _collect_call_metrics(artifacts: list[MeetingArtifact]) -> dict[str, Any]:for artifact in artifacts:if artifact.artifact_type == "call_record":metrics.update(dict(artifact.metadata.get("metrics") or {}))- metrics["artifact_count"] = len(artifacts)- return metrics+ return {**metrics, "artifact_count": len(artifacts)}def _collect_participants(meeting_ref: TeamsMeetingRef) -> list[str]:participants = meeting_ref.metadata.get("participants") or []- result: list[str] = []- if isinstance(participants, list):- for item in participants:- if isinstance(item, dict):- name = item.get("displayName") or (((item.get("identity") or {}).get("user") or {}).get("displayName"))- if name:- result.append(str(name))- return result+ if not isinstance(participants, list):+ return []+ names = (+ item.get("displayName") or (((item.get("identity") or {}).get("user") or {}).get("displayName"))+ for item in participants+ if isinstance(item, dict)+ )+ return [str(name) for name in names if name]def _odata_field(payload: dict[str, Any], name: str) -> Any:@@ -631,15 +485,12 @@ def _odata_field(payload: dict[str, Any], name: str) -> Any:def _organizer_user_id_from_payload(payload: dict[str, Any]) -> str | None:organizer = payload.get("meetingOrganizer") or payload.get("organizer")if isinstance(organizer, dict):- identity = organizer.get("identity")user = organizer.get("user")- if user is None and isinstance(identity, dict):- user = identity.get("user")+ if user is None and isinstance(organizer.get("identity"), dict):+ user = organizer["identity"].get("user")if isinstance(user, dict) and user.get("id"):return str(user["id"]).strip() or None- return (- str(payload.get("organizerUserId") or payload.get("organizer_user_id") or "").strip() or None- )+ return str(payload.get("organizerUserId") or payload.get("organizer_user_id") or "").strip() or Nonedef _resource_data_id_is_artifact(notification: dict[str, Any], resource_data: dict[str, Any]) -> bool:@@ -647,105 +498,78 @@ def _resource_data_id_is_artifact(notification: dict[str, Any], resource_data: dif "calltranscript" in odata_type.lower() or "callrecording" in odata_type.lower():return Trueresource = str(notification.get("resource") or "").lower()- if "getalltranscripts" in resource or "getallrecordings" in resource:- return True- if "/transcripts" in resource or "/recordings" in resource:+ if any(marker in resource for marker in ("getalltranscripts", "getallrecordings", "/transcripts", "/recordings")):return Truereturn looks_like_transcript_id(str(resource_data.get("id") or ""), odata_type=odata_type)def _meeting_ids_from_notification(notification: dict[str, Any]) -> tuple[str, str | None, dict[str, Any]]:- resource_data = notification.get("resourceData") or {}- if not isinstance(resource_data, dict):- resource_data = {}-+ """Return (meeting_id, organizer_user_id, extra_metadata) from a Graph change notification.++ Ids are taken from parsed resource paths first (odata.id, resource, transcriptContentUrl),+ then from flat fields. resourceData.id is a meeting id only when it is not an artifact id.+ The meeting_id never comes back empty: it falls back to an artifact id, then the receipt key.+ """+ resource_data = notification.get("resourceData")+ resource_data = resource_data if isinstance(resource_data, dict) else {}+ odata_type = str(_odata_field(resource_data, "odata.type") or "")parsed_paths = [parse_graph_meeting_resource(str(_odata_field(resource_data, "odata.id") or "")),parse_graph_meeting_resource(str(notification.get("resource") or "")),parse_graph_meeting_resource(str(resource_data.get("transcriptContentUrl") or "")),]- organizer_user_id = next(- (parsed["organizer_user_id"] for parsed in parsed_paths if parsed.get("organizer_user_id")),- None,- ) or _organizer_user_id_from_payload(resource_data) or _organizer_user_id_from_payload(notification)-- meeting_id = next(- (parsed["meeting_id"] for parsed in parsed_paths if parsed.get("meeting_id")),- None,- ) or (- str(resource_data.get("meetingId") or notification.get("meetingId") or "").strip() or None- )-- transcript_id = next(- (parsed["transcript_id"] for parsed in parsed_paths if parsed.get("transcript_id")),- None,+ first = {+ key: next((parsed[key] for parsed in parsed_paths if parsed.get(key)), None)+ for key in ("organizer_user_id", "meeting_id", "transcript_id", "recording_id")+ }+ organizer_user_id = (+ first["organizer_user_id"]+ or _organizer_user_id_from_payload(resource_data)+ or _organizer_user_id_from_payload(notification))- recording_id = next(- (parsed["recording_id"] for parsed in parsed_paths if parsed.get("recording_id")),- None,+ meeting_id = first["meeting_id"] or (+ str(resource_data.get("meetingId") or notification.get("meetingId") or "").strip() or None)+ transcript_id, recording_id = first["transcript_id"], first["recording_id"]resource_data_id = str(resource_data.get("id") or "").strip() or Noneif resource_data_id and not _resource_data_id_is_artifact(notification, resource_data):meeting_id = meeting_id or resource_data_id- elif resource_data_id and not transcript_id and looks_like_transcript_id(- resource_data_id, odata_type=str(_odata_field(resource_data, "odata.type") or "")- ):+ elif resource_data_id and not transcript_id and looks_like_transcript_id(resource_data_id, odata_type=odata_type):transcript_id = resource_data_id- meeting_id = (- meeting_id- or _extract_meeting_id_from_resource(str(notification.get("resource") or ""))- or transcript_id- or recording_id- or TeamsPipelineStore.build_notification_receipt_key(notification)- )-- extra_metadata = {- key: value- for key, value in {- "transcript_id": transcript_id,- "recording_id": recording_id,- }.items()- if value- }+ meeting_id = meeting_id or transcript_id or recording_id or TeamsPipelineStore.build_notification_receipt_key(notification)+ extra_metadata = {k: v for k, v in (("transcript_id", transcript_id), ("recording_id", recording_id)) if v}return str(meeting_id), organizer_user_id, extra_metadata-def _extract_meeting_id_from_resource(resource: str) -> str | None:- return parse_graph_meeting_resource(resource).get("meeting_id")---def _build_summary_prompt(- meeting_ref: TeamsMeetingRef,- transcript_text: str,- artifacts: list[MeetingArtifact],-) -> str:+def _build_summary_prompt(meeting_ref: TeamsMeetingRef, transcript_text: str, artifacts: list[MeetingArtifact]) -> str:artifact_lines = [f"- {artifact.artifact_type}:{artifact.artifact_id}:{artifact.display_name or ''}" for artifact in artifacts]return (f"Meeting ID: {meeting_ref.meeting_id}\n"f"Title: {meeting_ref.metadata.get('subject') or 'Unknown'}\n"f"Artifacts:\n{chr(10).join(artifact_lines) or '- none'}\n\n"- "Transcript:\n"- f"{transcript_text[:18000]}"+ f"Transcript:\n{transcript_text[:18000]}")+def _clean_items(values: Any) -> list[str]:+ return [str(item).strip() for item in values if str(item).strip()]++def _parse_summary_json(content: str) -> dict[str, Any]:text = (content or "").strip()if not text:return _heuristic_summary("")- start = text.find("{")- end = text.rfind("}")+ # Tolerate prose or code fences around the JSON object.+ start, end = text.find("{"), text.rfind("}")if start >= 0 and end > start:text = text[start : end + 1]payload = json.loads(text)return {"summary": str(payload.get("summary") or "").strip(),- "key_decisions": [str(item).strip() for item in payload.get("key_decisions", []) if str(item).strip()],- "action_items": [str(item).strip() for item in payload.get("action_items", []) if str(item).strip()],- "risks": [str(item).strip() for item in payload.get("risks", []) if str(item).strip()],+ **{key: _clean_items(payload.get(key, [])) for key in ("key_decisions", "action_items", "risks")},"confidence": str(payload.get("confidence") or "medium").strip(),"confidence_notes": str(payload.get("confidence_notes") or "").strip(),}@@ -753,40 +577,22 @@ def _parse_summary_json(content: str) -> dict[str, Any]:def _heuristic_summary(transcript_text: str) -> dict[str, Any]:lines = [line.strip(" -*\t") for line in transcript_text.splitlines() if line.strip()]- summary = " ".join(lines[:3])[:1200] or "Transcript unavailable or too sparse for a confident summary."- action_items = [- line for line in lines if line.lower().startswith(("action:", "todo:", "next step:", "follow up:"))- ][:8]- risks = [line for line in lines if "risk" in line.lower() or "blocker" in line.lower()][:6]- decisions = [line for line in lines if "decide" in line.lower() or "decision" in line.lower()][:6]- confidence = "low" if len(transcript_text.strip()) < 300 else "medium"+ lowered = [line.lower() for line in lines]return {- "summary": summary,- "key_decisions": decisions,- "action_items": action_items,- "risks": risks,- "confidence": confidence,+ "summary": " ".join(lines[:3])[:1200] or "Transcript unavailable or too sparse for a confident summary.",+ "key_decisions": [line for line, low in zip(lines, lowered) if "decide" in low or "decision" in low][:6],+ "action_items": [+ line for line, low in zip(lines, lowered) if low.startswith(("action:", "todo:", "next step:", "follow up:"))+ ][:8],+ "risks": [line for line, low in zip(lines, lowered) if "risk" in low or "blocker" in low][:6],+ "confidence": "low" if len(transcript_text.strip()) < 300 else "medium","confidence_notes": "Generated with heuristic fallback because no LLM summary response was available.",}def _render_summary_markdown(payload: TeamsMeetingSummaryPayload) -> str:- lines = [- f"# {payload.title or f'Meeting {payload.meeting_ref.meeting_id}'}",- "",- "## Summary",- payload.summary or "No summary available.",- "",- "## Key Decisions",- *([f"- {item}" for item in payload.key_decisions] or ["- None"]),- "",- "## Action Items",- *([f"- {item}" for item in payload.action_items] or ["- None"]),- "",- "## Risks",- *([f"- {item}" for item in payload.risks] or ["- None"]),- "",- f"Confidence: {payload.confidence or 'unknown'}",- payload.confidence_notes or "",- ]+ lines = [f"# {payload.title or f'Meeting {payload.meeting_ref.meeting_id}'}"]+ for heading, body in _sections(payload):+ lines += ["", f"## {heading}", body or ("No summary available." if heading == "Summary" else "- None")]+ lines += ["", f"Confidence: {payload.confidence or 'unknown'}", payload.confidence_notes or ""]return "\n".join(lines).strip()diff --git a/plugins/teams_pipeline/runtime.py b/plugins/teams_pipeline/runtime.pyindex f51be5e19e3..40f272b0238 100644--- a/plugins/teams_pipeline/runtime.py+++ b/plugins/teams_pipeline/runtime.py@@ -12,59 +12,38 @@ from plugins.teams_pipeline.subscriptions import build_graph_clientlogger = logging.getLogger(__name__)+# Teams platform settings mirrored into the pipeline's teams_delivery config (pipeline keys win).+_DELIVERY_KEYS = ("incoming_webhook_url", "access_token", "team_id", "channel_id", "chat_id")+def _teams_delivery_is_configured(teams_extra: dict[str, Any], teams_delivery: dict[str, Any]) -> bool:- delivery_mode = str(- teams_delivery.get("mode")- or teams_delivery.get("delivery_mode")- or teams_extra.get("delivery_mode")- or ""- ).strip().lower()+ def pick(key: str) -> Any:+ return teams_delivery.get(key) or teams_extra.get(key)+ delivery_mode = str(teams_delivery.get("mode") or pick("delivery_mode") or "").strip().lower()if delivery_mode == "incoming_webhook":- return bool(- teams_delivery.get("incoming_webhook_url")- or teams_extra.get("incoming_webhook_url")- )+ return bool(pick("incoming_webhook_url"))if delivery_mode == "graph":- chat_id = teams_delivery.get("chat_id") or teams_extra.get("chat_id")- team_id = teams_delivery.get("team_id") or teams_extra.get("team_id")- channel_id = teams_delivery.get("channel_id") or teams_extra.get("channel_id")- return bool(chat_id or (team_id and channel_id))-+ return bool(pick("chat_id") or (pick("team_id") and pick("channel_id")))return Falsedef build_pipeline_runtime_config(gateway_config: Any) -> dict[str, Any]:- """Build pipeline config from gateway platform config.-- Pipeline-specific knobs live under ``teams.extra.meeting_pipeline`` while- Teams delivery continues to source its target details from the existing- Teams platform config.- """-+ """Pipeline knobs live under ``teams.extra.meeting_pipeline``; Teams delivery targets are+ mirrored from the Teams platform config so they are not configured twice."""teams_config = gateway_config.platforms.get(Platform("teams"))teams_extra = dict((teams_config.extra or {}) if teams_config else {})pipeline_config = dict(teams_extra.get("meeting_pipeline") or {})if teams_config and teams_config.enabled:teams_delivery = dict(pipeline_config.get("teams_delivery") or {})-delivery_mode = str(teams_extra.get("delivery_mode") or "").strip()if delivery_mode:teams_delivery["mode"] = delivery_mode-- for key in (- "incoming_webhook_url",- "access_token",- "team_id",- "channel_id",- "chat_id",- ):+ for key in _DELIVERY_KEYS:value = teams_extra.get(key)if value not in {None, ""}:teams_delivery[key] = value-if teams_delivery:teams_delivery["enabled"] = _teams_delivery_is_configured(teams_extra, teams_delivery)pipeline_config["teams_delivery"] = teams_delivery@@ -76,8 +55,7 @@ def build_pipeline_runtime(gateway: Any) -> TeamsMeetingPipeline:teams_sender = Noneteams_config = gateway.config.platforms.get(Platform("teams"))pipeline_config = build_pipeline_runtime_config(gateway.config)- teams_delivery = dict(pipeline_config.get("teams_delivery") or {})- if teams_config and teams_config.enabled and teams_delivery.get("enabled"):+ if teams_config and teams_config.enabled and (pipeline_config.get("teams_delivery") or {}).get("enabled"):try:from plugins.platforms.teams.adapter import TeamsSummaryWriterexcept ImportError:@@ -97,7 +75,6 @@ def build_pipeline_runtime(gateway: Any) -> TeamsMeetingPipeline:def bind_gateway_runtime(gateway: Any) -> bool:"""Attach the Teams pipeline runtime to the msgraph webhook adapter."""-adapter = gateway.adapters.get(Platform.MSGRAPH_WEBHOOK)if adapter is None:return False@@ -108,12 +85,12 @@ def bind_gateway_runtime(gateway: Any) -> bool:try:runtime = build_pipeline_runtime(gateway)except Exception as exc:- error_message = str(exc)- gateway._teams_pipeline_runtime_error = error_message+ # Without a runtime, notifications must still be acked (and dropped) so Graph does not retry-storm.+ gateway._teams_pipeline_runtime_error = str(exc)logger.warning("Teams pipeline runtime unavailable: %s. Installing a drop-scheduler ""so Graph notifications ack cleanly without piling up unbound.",- error_message,+ exc,)async def _drop(notification: dict[str, Any], event: Any) -> None:diff --git a/plugins/teams_pipeline/store.py b/plugins/teams_pipeline/store.pyindex ceab28cb7ef..c86c90a63c3 100644--- a/plugins/teams_pipeline/store.py+++ b/plugins/teams_pipeline/store.py@@ -16,6 +16,8 @@ from hermes_constants import get_hermes_homeDEFAULT_TEAMS_PIPELINE_STORE_FILENAME = "teams_pipeline_store.json"+# Persisted top-level buckets; the on-disk JSON shape must stay stable for existing user stores.+_BUCKETS = ("subscriptions", "notification_receipts", "event_timestamps", "jobs", "sink_records")def _utc_now_iso() -> str:@@ -23,31 +25,18 @@ def _utc_now_iso() -> str:def resolve_teams_pipeline_store_path(path: str | Path | None = None) -> Path:- if path is not None:- explicit = str(path).strip()- if explicit:- return Path(explicit)-+ explicit = str(path).strip() if path is not None else ""env_path = os.getenv("MSGRAPH_WEBHOOK_STORE_PATH", "").strip()- if env_path:- return Path(env_path)-- return get_hermes_home() / DEFAULT_TEAMS_PIPELINE_STORE_FILENAME+ return Path(explicit or env_path) if (explicit or env_path) else get_hermes_home() / DEFAULT_TEAMS_PIPELINE_STORE_FILENAMEclass TeamsPipelineStore:- """JSON-backed durable store for Teams pipeline state."""+ """JSON-backed durable store for Teams pipeline state; every write is an atomic temp-file replace."""def __init__(self, path: str | Path):self.path = Path(path)self._lock = threading.RLock()- self._state: Dict[str, Dict[str, Any]] = {- "subscriptions": {},- "notification_receipts": {},- "event_timestamps": {},- "jobs": {},- "sink_records": {},- }+ self._state: Dict[str, Dict[str, Any]] = {bucket: {} for bucket in _BUCKETS}self._load()def _load(self) -> None:@@ -55,75 +44,65 @@ class TeamsPipelineStore:if not self.path.exists():returndata = json.loads(self.path.read_text(encoding="utf-8") or "{}")- if not isinstance(data, dict):- return- self._state["subscriptions"] = dict(data.get("subscriptions") or {})- self._state["notification_receipts"] = dict(data.get("notification_receipts") or {})- self._state["event_timestamps"] = dict(data.get("event_timestamps") or {})- self._state["jobs"] = dict(data.get("jobs") or {})- self._state["sink_records"] = dict(data.get("sink_records") or {})+ if isinstance(data, dict):+ self._state = {bucket: dict(data.get(bucket) or {}) for bucket in _BUCKETS}def _persist(self) -> None:self.path.parent.mkdir(parents=True, exist_ok=True)- with NamedTemporaryFile(- "w",- encoding="utf-8",- dir=str(self.path.parent),- delete=False,- ) as tmp:+ with NamedTemporaryFile("w", encoding="utf-8", dir=str(self.path.parent), delete=False) as tmp:json.dump(self._state, tmp, indent=2, sort_keys=True)tmp.flush()tmp_path = Path(tmp.name)tmp_path.replace(self.path)- def list_subscriptions(self) -> Dict[str, Dict[str, Any]]:+ def _list(self, bucket: str) -> Dict[str, Dict[str, Any]]:with self._lock:- return deepcopy(self._state["subscriptions"])+ return deepcopy(self._state[bucket])- def get_subscription(self, subscription_id: str) -> Optional[Dict[str, Any]]:+ def _get(self, bucket: str, key: str) -> Optional[Dict[str, Any]]:with self._lock:- record = self._state["subscriptions"].get(subscription_id)+ record = self._state[bucket].get(key)return deepcopy(record) if isinstance(record, dict) else None- def upsert_subscription(self, subscription_id: str, payload: Dict[str, Any]) -> Dict[str, Any]:+ def _upsert(self, bucket: str, id_field: str, key: str, payload: Dict[str, Any]) -> Dict[str, Any]:+ """Merge ``payload`` over the existing record, stamping ``id_field`` and created/updated timestamps."""with self._lock:- existing = self._state["subscriptions"].get(subscription_id, {})+ existing = self._state[bucket].get(key, {})merged = {**existing, **deepcopy(payload)}- merged["subscription_id"] = subscription_id+ merged[id_field] = keymerged.setdefault("created_at", existing.get("created_at") or _utc_now_iso())merged["updated_at"] = _utc_now_iso()- self._state["subscriptions"][subscription_id] = merged+ self._state[bucket][key] = mergedself._persist()return deepcopy(merged)+ def list_subscriptions(self) -> Dict[str, Dict[str, Any]]:+ return self._list("subscriptions")++ def get_subscription(self, subscription_id: str) -> Optional[Dict[str, Any]]:+ return self._get("subscriptions", subscription_id)++ def upsert_subscription(self, subscription_id: str, payload: Dict[str, Any]) -> Dict[str, Any]:+ return self._upsert("subscriptions", "subscription_id", subscription_id, payload)+def delete_subscription(self, subscription_id: str) -> bool:with self._lock:- removed = self._state["subscriptions"].pop(subscription_id, None)- if removed is None:+ if self._state["subscriptions"].pop(subscription_id, None) is None:return Falseself._persist()return True@classmethoddef build_notification_receipt_key(cls, notification: Dict[str, Any]) -> str:- explicit_id = notification.get("id")- if explicit_id:+ if explicit_id := notification.get("id"):return f"id:{explicit_id}"canonical = json.dumps(notification, sort_keys=True, separators=(",", ":"))- digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()- return f"sha256:{digest}"-- def has_notification_receipt(self, receipt_key: str) -> bool:- with self._lock:- return receipt_key in self._state["notification_receipts"]+ return f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}"def record_notification_receipt(- self,- receipt_key: str,- payload: Optional[Dict[str, Any]] = None,- *,- received_at: Optional[str] = None,+ self, receipt_key: str, payload: Optional[Dict[str, Any]] = None, *, received_at: Optional[str] = None) -> bool:+ """Record a receipt once; returns False when the key was already seen (duplicate delivery)."""with self._lock:if receipt_key in self._state["notification_receipts"]:return False@@ -134,60 +113,21 @@ class TeamsPipelineStore:self._persist()return True- def record_event_timestamp(self, event_key: str, timestamp: Optional[str] = None) -> str:- with self._lock:- value = timestamp or _utc_now_iso()- self._state["event_timestamps"][event_key] = value- self._persist()- return value-- def get_event_timestamp(self, event_key: str) -> Optional[str]:- with self._lock:- value = self._state["event_timestamps"].get(event_key)- return str(value) if value is not None else None-def stats(self) -> Dict[str, int]:with self._lock:- return {- "subscriptions": len(self._state["subscriptions"]),- "notification_receipts": len(self._state["notification_receipts"]),- "event_timestamps": len(self._state["event_timestamps"]),- "jobs": len(self._state["jobs"]),- "sink_records": len(self._state["sink_records"]),- }+ return {bucket: len(self._state[bucket]) for bucket in _BUCKETS}def upsert_job(self, job_id: str, payload: Dict[str, Any]) -> Dict[str, Any]:- with self._lock:- existing = self._state["jobs"].get(job_id, {})- merged = {**existing, **deepcopy(payload)}- merged["job_id"] = job_id- merged.setdefault("created_at", existing.get("created_at") or _utc_now_iso())- merged["updated_at"] = _utc_now_iso()- self._state["jobs"][job_id] = merged- self._persist()- return deepcopy(merged)+ return self._upsert("jobs", "job_id", job_id, payload)def get_job(self, job_id: str) -> Optional[Dict[str, Any]]:- with self._lock:- record = self._state["jobs"].get(job_id)- return deepcopy(record) if isinstance(record, dict) else None+ return self._get("jobs", job_id)def list_jobs(self) -> Dict[str, Dict[str, Any]]:- with self._lock:- return deepcopy(self._state["jobs"])+ return self._list("jobs")def upsert_sink_record(self, sink_key: str, payload: Dict[str, Any]) -> Dict[str, Any]:- with self._lock:- existing = self._state["sink_records"].get(sink_key, {})- merged = {**existing, **deepcopy(payload)}- merged["sink_key"] = sink_key- merged.setdefault("created_at", existing.get("created_at") or _utc_now_iso())- merged["updated_at"] = _utc_now_iso()- self._state["sink_records"][sink_key] = merged- self._persist()- return deepcopy(merged)+ return self._upsert("sink_records", "sink_key", sink_key, payload)def get_sink_record(self, sink_key: str) -> Optional[Dict[str, Any]]:- with self._lock:- record = self._state["sink_records"].get(sink_key)- return deepcopy(record) if isinstance(record, dict) else None+ return self._get("sink_records", sink_key)diff --git a/plugins/teams_pipeline/subscriptions.py b/plugins/teams_pipeline/subscriptions.pyindex ff9cce3c9dd..3142a68afdd 100644--- a/plugins/teams_pipeline/subscriptions.py+++ b/plugins/teams_pipeline/subscriptions.py@@ -3,125 +3,65 @@from __future__ import annotationsfrom datetime import datetime, timedelta, timezone+from os import getenvfrom typing import Any-from plugins.teams_pipeline.models import GraphSubscription-from plugins.teams_pipeline.store import TeamsPipelineStore, resolve_teams_pipeline_store_path+from plugins.teams_pipeline.models import GraphSubscription, _parse_datetime+from plugins.teams_pipeline.models import _serialize_datetime as _iso_z+from plugins.teams_pipeline.store import TeamsPipelineStorefrom tools.microsoft_graph_auth import MicrosoftGraphTokenProviderfrom tools.microsoft_graph_client import MicrosoftGraphClientdef build_graph_client() -> MicrosoftGraphClient:- provider = MicrosoftGraphTokenProvider.from_env()- return MicrosoftGraphClient(provider)---def _parse_bool(value: Any, *, default: bool = False) -> bool:- if isinstance(value, bool):- return value- if isinstance(value, str):- lowered = value.strip().lower()- if lowered in {"1", "true", "yes", "on"}:- return True- if lowered in {"0", "false", "no", "off"}:- return False- return default---def _parse_int(value: Any, default: int) -> int:- try:- return int(value)- except (TypeError, ValueError):- return default+ return MicrosoftGraphClient(MicrosoftGraphTokenProvider.from_env())def _utc_now() -> datetime:return datetime.now(timezone.utc)-def _utc_now_iso() -> str:- return _utc_now().replace(microsecond=0).isoformat().replace("+00:00", "Z")---def _parse_datetime(value: Any) -> datetime | None:- if value is None:- return None- text = str(value).strip()- if not text:- return None- if text.endswith("Z"):- text = f"{text[:-1]}+00:00"- parsed = datetime.fromisoformat(text)- if parsed.tzinfo is None:- return parsed.replace(tzinfo=timezone.utc)- return parsed.astimezone(timezone.utc)---def resolve_store_path(path: str | None) -> str:- return str(resolve_teams_pipeline_store_path(path))---def build_store(path: str | None = None) -> TeamsPipelineStore:- return TeamsPipelineStore(resolve_store_path(path))+def utc_timestamp(hours_from_now: int = 0, *, base: datetime | None = None) -> str:+ """Second-precision UTC ISO timestamp with a ``Z`` suffix (Graph's expirationDateTime format)."""+ return _iso_z(((base or _utc_now()) + timedelta(hours=hours_from_now)).replace(microsecond=0))def sync_graph_subscription_record(- store: TeamsPipelineStore,- subscription_payload: dict[str, Any],- *,- status: str | None = None,+ store: TeamsPipelineStore, subscription_payload: dict[str, Any], *, status: str | None = None,renewed: bool = False,) -> dict[str, Any]:normalized = GraphSubscription.from_dict(subscription_payload).to_dict()- expiration = _parse_datetime(normalized.get("expiration_datetime"))- effective_status = status- if effective_status is None:- effective_status = "expired" if expiration and expiration <= _utc_now() else "active"- normalized["status"] = effective_status+ if status is None:+ expiration = _parse_datetime(normalized.get("expiration_datetime"))+ status = "expired" if expiration and expiration <= _utc_now() else "active"+ normalized["status"] = statusif renewed:- normalized["latest_renewal_at"] = _utc_now_iso()+ normalized["latest_renewal_at"] = utc_timestamp()return store.upsert_subscription(normalized["subscription_id"], normalized)def expected_client_state(raw: str | None = None) -> str | None:if raw is None:- from os import getenv-raw = getenv("MSGRAPH_WEBHOOK_CLIENT_STATE", "")- value = str(raw or "").strip()- return value or None+ return str(raw or "").strip() or Nonedef is_managed_subscription(- store: TeamsPipelineStore,- subscription_payload: dict[str, Any],- *,- expected_client_state_value: str | None,+ store: TeamsPipelineStore, subscription_payload: dict[str, Any], *, expected_client_state_value: str | None,) -> bool:- subscription_id = str(- subscription_payload.get("subscription_id") or subscription_payload.get("id") or ""- ).strip()+ """A subscription is ours if the store knows it or its clientState matches the configured one."""+ subscription_id = str(subscription_payload.get("subscription_id") or subscription_payload.get("id") or "").strip()if subscription_id and store.get_subscription(subscription_id):return True-- if expected_client_state_value:- candidate_state = str(- subscription_payload.get("client_state") or subscription_payload.get("clientState") or ""- ).strip()- if candidate_state and candidate_state == expected_client_state_value:- return True-- return False+ candidate_state = str(+ subscription_payload.get("client_state") or subscription_payload.get("clientState") or ""+ ).strip()+ return bool(expected_client_state_value and candidate_state == expected_client_state_value)async def maintain_graph_subscriptions(- *,- client: MicrosoftGraphClient,- store: TeamsPipelineStore,- renew_within_hours: int = 24,- extend_hours: int = 24,- dry_run: bool = False,- client_state: str | None = None,+ *, client: MicrosoftGraphClient, store: TeamsPipelineStore, renew_within_hours: int = 24, extend_hours: int = 24,+ dry_run: bool = False, client_state: str | None = None,) -> dict[str, Any]:threshold_hours = max(1, int(renew_within_hours))extend_hours = max(1, int(extend_hours))@@ -141,18 +81,12 @@ async def maintain_graph_subscriptions(subscription_id = str(raw.get("id") or "").strip()if not subscription_id:continue- managed = is_managed_subscription(- store,- raw,- expected_client_state_value=managed_client_state,- )- if not managed:- skipped.append(- {- "subscription_id": subscription_id,- "reason": "not_managed_by_teams_pipeline",- }- )++ def skip(reason: str, **extra: Any) -> None:+ skipped.append({"subscription_id": subscription_id, "reason": reason, **extra})++ if not is_managed_subscription(store, raw, expected_client_state_value=managed_client_state):+ skip("not_managed_by_teams_pipeline")continueremote_ids.add(subscription_id)@@ -160,90 +94,50 @@ async def maintain_graph_subscriptions(sync_graph_subscription_record(store, raw)synced += 1except Exception as exc:- skipped.append(- {- "subscription_id": subscription_id,- "reason": f"failed_to_sync_local_store: {exc}",- }- )+ skip(f"failed_to_sync_local_store: {exc}")continueexpiration = _parse_datetime(raw.get("expirationDateTime"))if expiration is None:- skipped.append({"subscription_id": subscription_id, "reason": "missing_expiration"})+ skip("missing_expiration")continueseconds_until_expiry = int((expiration - now).total_seconds())if seconds_until_expiry < 0:- store.upsert_subscription(- subscription_id,- {- "status": "expired",- "expiration_datetime": expiration.isoformat().replace("+00:00", "Z"),- },- )- skipped.append(- {- "subscription_id": subscription_id,- "reason": "already_expired",- "expiration_datetime": expiration.isoformat().replace("+00:00", "Z"),- }- )+ store.upsert_subscription(subscription_id, {"status": "expired", "expiration_datetime": _iso_z(expiration)})+ skip("already_expired", expiration_datetime=_iso_z(expiration))continue-if seconds_until_expiry > threshold_hours * 3600:- skipped.append(- {- "subscription_id": subscription_id,- "reason": "not_due",- "expires_in_seconds": seconds_until_expiry,- }- )+ skip("not_due", expires_in_seconds=seconds_until_expiry)continue- new_expiration = (max(now, expiration) + timedelta(hours=extend_hours)).replace(- microsecond=0- ).isoformat().replace("+00:00", "Z")+ new_expiration = utc_timestamp(extend_hours, base=max(now, expiration))candidate = {- "subscription_id": subscription_id,- "resource": raw.get("resource"),- "current_expiration": expiration.isoformat().replace("+00:00", "Z"),- "new_expiration": new_expiration,+ "subscription_id": subscription_id, "resource": raw.get("resource"),+ "current_expiration": _iso_z(expiration), "new_expiration": new_expiration,}candidates.append(candidate)if dry_run:continuepatched = await client.patch_json(- f"/subscriptions/{subscription_id}",- json_body={"expirationDateTime": new_expiration},+ f"/subscriptions/{subscription_id}", json_body={"expirationDateTime": new_expiration})merged = {**raw, **(patched or {}), "id": subscription_id, "expirationDateTime": new_expiration}sync_graph_subscription_record(store, merged, status="active", renewed=True)renewed.append({**candidate, "result": patched})+ # Locally-known subscriptions Graph no longer reports are flagged, never deleted.for subscription_id in store.list_subscriptions():- if subscription_id in remote_ids:- continue- store.upsert_subscription(- subscription_id,- {- "status": "missing_remote",- "last_seen_missing_remote_at": _utc_now_iso(),- },- )+ if subscription_id not in remote_ids:+ store.upsert_subscription(+ subscription_id, {"status": "missing_remote", "last_seen_missing_remote_at": utc_timestamp()}+ )return {- "success": True,- "dry_run": bool(dry_run),- "store_path": str(store.path),- "remote_subscription_count": len(remote_subscriptions),- "synced_subscription_count": synced,- "candidate_count": len(candidates),- "renewed_count": len(renewed),- "threshold_hours": threshold_hours,- "extend_hours": extend_hours,- "candidates": candidates,- "renewed": renewed,- "skipped": skipped,+ "success": True, "dry_run": bool(dry_run), "store_path": str(store.path),+ "remote_subscription_count": len(remote_subscriptions), "synced_subscription_count": synced,+ "candidate_count": len(candidates), "renewed_count": len(renewed),+ "threshold_hours": threshold_hours, "extend_hours": extend_hours,+ "candidates": candidates, "renewed": renewed, "skipped": skipped,}diff --git a/tests/plugins/test_teams_pipeline_plugin.py b/tests/plugins/test_teams_pipeline_plugin.pyindex b7335cb8e77..d996c30ef72 100644--- a/tests/plugins/test_teams_pipeline_plugin.py+++ b/tests/plugins/test_teams_pipeline_plugin.py@@ -168,7 +168,6 @@ def test_store_persists_subscription_event_and_job_state(tmp_path):"sub-1",{"client_state": "abc", "resource": "communications/onlineMeetings"},)- store.record_event_timestamp("evt-1", "2026-05-03T19:30:00Z")store.upsert_job("job-1", {"status": "received", "event_id": "evt-1"})store.upsert_sink_record("notion:meeting-1", {"page_id": "page-1"})@@ -180,7 +179,6 @@ def test_store_persists_subscription_event_and_job_state(tmp_path):assert subscription is not Noneassert subscription["subscription_id"] == "sub-1"assert subscription["client_state"] == "abc"- assert reloaded.get_event_timestamp("evt-1") == "2026-05-03T19:30:00Z"assert job is not Noneassert job["status"] == "received"assert sink is not None@@ -430,7 +428,7 @@ class TestTeamsMeetingPipeline:assert summarize_calls == 1assert len(store.list_jobs()) == 1receipt_key = TeamsPipelineStore.build_notification_receipt_key(notification)- assert store.has_notification_receipt(receipt_key) is True+ assert store.record_notification_receipt(receipt_key) is Falsedef test_parse_graph_meeting_resource_reads_quoted_users_transcript_path():