|
| 1 | +"""Lifecycle events for coded agent and coded function runs. |
| 2 | +
|
| 3 | +The coded counterpart to low-code's ``AgentRun.*``. Unlike ``Cli.*`` these are not |
| 4 | +suppressed under a job key, so cloud runs report too. |
| 5 | +""" |
| 6 | + |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import time |
| 10 | +import uuid |
| 11 | +from enum import Enum |
| 12 | +from importlib.metadata import version |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +from uipath.platform.common import UiPathConfig, resolve_trace_id |
| 16 | +from uipath.platform.constants import ENV_IMAGE_VERSION, ENV_JOB_ID |
| 17 | +from uipath.runtime.errors import UiPathBaseRuntimeError, UiPathErrorContract |
| 18 | +from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus |
| 19 | +from uipath.telemetry._track import is_telemetry_enabled, track_event |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | +APPLICATION_NAME = "UiPath.CodedAgent" |
| 24 | + |
| 25 | +SOURCE = "uipath-python-cli" |
| 26 | + |
| 27 | +NOT_AVAILABLE = "N/A" |
| 28 | + |
| 29 | +_LOWCODE_AGENT_TYPE = "uipath_lowcode" |
| 30 | +_FUNCTION_FRAMEWORK = "python" |
| 31 | + |
| 32 | + |
| 33 | +class RunKind(str, Enum): |
| 34 | + """Event-name prefix per run kind.""" |
| 35 | + |
| 36 | + CODED_AGENT = "CodedAgentRun" |
| 37 | + CODED_FUNCTION = "CodedFunctionRun" |
| 38 | + |
| 39 | + |
| 40 | +def classify_run(agent_type: str | None, agent_framework: str | None) -> RunKind | None: |
| 41 | + """Run kind from factory settings, or ``None`` when low-code owns the run. |
| 42 | +
|
| 43 | + Both coded kinds report ``agent_type`` ``uipath_coded``, so only the framework |
| 44 | + separates them. A factory reporting nothing is assumed to wrap one. |
| 45 | + """ |
| 46 | + if agent_type and agent_type.strip().lower() == _LOWCODE_AGENT_TYPE: |
| 47 | + return None |
| 48 | + if agent_framework and agent_framework.strip().lower() == _FUNCTION_FRAMEWORK: |
| 49 | + return RunKind.CODED_FUNCTION |
| 50 | + return RunKind.CODED_AGENT |
| 51 | + |
| 52 | + |
| 53 | +def _cloud_user_id() -> str | None: |
| 54 | + if configured := UiPathConfig.cloud_user_id: |
| 55 | + return configured |
| 56 | + try: |
| 57 | + from uipath._cli._utils._common import get_claim_from_token |
| 58 | + |
| 59 | + return get_claim_from_token("sub") |
| 60 | + except Exception: |
| 61 | + return None |
| 62 | + |
| 63 | + |
| 64 | +def _scope_properties() -> dict[str, Any]: |
| 65 | + """Identity and scope, on every event so each one stands alone. |
| 66 | +
|
| 67 | + The cloud identity trio is required, so it reports ``N/A`` rather than being |
| 68 | + dropped; optional scope is omitted, so a local run has no folder. |
| 69 | + """ |
| 70 | + properties: dict[str, Any] = { |
| 71 | + "FolderKey": UiPathConfig.folder_key, |
| 72 | + "JobKey": UiPathConfig.job_key, |
| 73 | + "JobId": os.getenv(ENV_JOB_ID), |
| 74 | + "CloudOrganizationId": UiPathConfig.organization_id or NOT_AVAILABLE, |
| 75 | + "CloudTenantId": UiPathConfig.tenant_id or NOT_AVAILABLE, |
| 76 | + "CloudUserId": _cloud_user_id() or NOT_AVAILABLE, |
| 77 | + "ProjectId": UiPathConfig.project_id, |
| 78 | + "ProjectKey": UiPathConfig.project_key, |
| 79 | + "ProcessName": UiPathConfig.process_key, |
| 80 | + "ProcessUuid": UiPathConfig.process_uuid, |
| 81 | + "ProcessVersion": UiPathConfig.process_version, |
| 82 | + "TraceId": resolve_trace_id(), |
| 83 | + "ImageVersion": os.getenv(ENV_IMAGE_VERSION), |
| 84 | + } |
| 85 | + return {key: value for key, value in properties.items() if value is not None} |
| 86 | + |
| 87 | + |
| 88 | +def _error_properties( |
| 89 | + error_type: str | None, contract: UiPathErrorContract | None |
| 90 | +) -> dict[str, Any]: |
| 91 | + """Error classification only, since message and traceback carry customer source. |
| 92 | +
|
| 93 | + ``ErrorType`` is the exception class, so it is absent for a faulted result that |
| 94 | + never raised rather than borrowing the contract code. |
| 95 | + """ |
| 96 | + properties: dict[str, Any] = {} |
| 97 | + if error_type: |
| 98 | + properties["ErrorType"] = error_type |
| 99 | + if contract is None: |
| 100 | + return properties |
| 101 | + properties["ErrorCode"] = contract.code |
| 102 | + properties["ErrorTitle"] = contract.title |
| 103 | + category = contract.category |
| 104 | + properties["ErrorCategory"] = getattr(category, "value", category) |
| 105 | + return properties |
| 106 | + |
| 107 | + |
| 108 | +class RunTelemetry: |
| 109 | + """Emits Start and one terminal event for a single coded run.""" |
| 110 | + |
| 111 | + def __init__( |
| 112 | + self, |
| 113 | + *, |
| 114 | + kind: RunKind, |
| 115 | + entrypoint: str | None, |
| 116 | + execution_source: str | None, |
| 117 | + is_conversational: bool, |
| 118 | + ) -> None: |
| 119 | + """Key the run on its job so a suspend/resume pair stays one run.""" |
| 120 | + self._kind = kind |
| 121 | + self._entrypoint = entrypoint |
| 122 | + self._execution_source = execution_source |
| 123 | + self._is_conversational = is_conversational |
| 124 | + self._run_id = UiPathConfig.job_key or str(uuid.uuid4()) |
| 125 | + self._started_at = time.monotonic() |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def start( |
| 129 | + cls, |
| 130 | + *, |
| 131 | + agent_type: str | None, |
| 132 | + agent_framework: str | None, |
| 133 | + entrypoint: str | None, |
| 134 | + execution_source: str | None = None, |
| 135 | + is_conversational: bool = False, |
| 136 | + ) -> "RunTelemetry | None": |
| 137 | + """Emit Start and return a handle, or ``None`` when not reporting. |
| 138 | +
|
| 139 | + ``None`` when telemetry is off, or for low-code, which reports itself. |
| 140 | + """ |
| 141 | + if not is_telemetry_enabled(): |
| 142 | + return None |
| 143 | + |
| 144 | + kind = classify_run(agent_type, agent_framework) |
| 145 | + if kind is None: |
| 146 | + return None |
| 147 | + |
| 148 | + instance = cls( |
| 149 | + kind=kind, |
| 150 | + entrypoint=entrypoint, |
| 151 | + execution_source=execution_source, |
| 152 | + is_conversational=is_conversational, |
| 153 | + ) |
| 154 | + instance._emit("Start", {}) |
| 155 | + return instance |
| 156 | + |
| 157 | + def finished(self, result: UiPathRuntimeResult | None) -> None: |
| 158 | + """Terminal event for a run that returned. |
| 159 | +
|
| 160 | + Faulted failed without raising; suspended is waiting, not broken. |
| 161 | + """ |
| 162 | + status = result.status if result else UiPathRuntimeStatus.SUCCESSFUL |
| 163 | + |
| 164 | + if status == UiPathRuntimeStatus.FAULTED: |
| 165 | + contract = result.error if result else None |
| 166 | + self._emit( |
| 167 | + "Failed", |
| 168 | + {"Status": "Failed", **_error_properties(None, contract)}, |
| 169 | + include_duration=True, |
| 170 | + ) |
| 171 | + return |
| 172 | + |
| 173 | + label = "Suspended" if status == UiPathRuntimeStatus.SUSPENDED else "Completed" |
| 174 | + self._emit("End", {"Status": label}, include_duration=True) |
| 175 | + |
| 176 | + def failed(self, exception: BaseException) -> None: |
| 177 | + """Terminal event for a run that raised.""" |
| 178 | + contract = getattr(exception, "error_info", None) |
| 179 | + if not isinstance(exception, UiPathBaseRuntimeError): |
| 180 | + contract = None |
| 181 | + self._emit( |
| 182 | + "Failed", |
| 183 | + { |
| 184 | + "Status": "Failed", |
| 185 | + **_error_properties(type(exception).__name__, contract), |
| 186 | + }, |
| 187 | + include_duration=True, |
| 188 | + ) |
| 189 | + |
| 190 | + def _emit( |
| 191 | + self, suffix: str, extra: dict[str, Any], include_duration: bool = False |
| 192 | + ) -> None: |
| 193 | + try: |
| 194 | + properties: dict[str, Any] = { |
| 195 | + "AgentRunId": self._run_id, |
| 196 | + "AgentType": "Coded", |
| 197 | + "AgentRunSource": self._execution_source, |
| 198 | + "Entrypoint": self._entrypoint, |
| 199 | + "IsConversational": self._is_conversational, |
| 200 | + "Runtime": "URT", |
| 201 | + "ApplicationName": APPLICATION_NAME, |
| 202 | + "Source": SOURCE, |
| 203 | + "SDKVersion": version("uipath"), |
| 204 | + } |
| 205 | + properties = { |
| 206 | + key: value for key, value in properties.items() if value is not None |
| 207 | + } |
| 208 | + properties.update(_scope_properties()) |
| 209 | + |
| 210 | + if include_duration: |
| 211 | + properties["DurationMs"] = int( |
| 212 | + (time.monotonic() - self._started_at) * 1000 |
| 213 | + ) |
| 214 | + |
| 215 | + properties.update(extra) |
| 216 | + track_event(f"{self._kind.value}.{suffix}", properties) |
| 217 | + except Exception: |
| 218 | + logger.debug("Failed to emit %s run event", suffix, exc_info=True) |
0 commit comments