|
| 1 | +import json |
| 2 | +import uuid |
| 3 | +from dataclasses import dataclass |
| 4 | +from functools import cached_property |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from uipath import UiPath |
| 8 | +from uipath.models import CreateAction, InvokeProcess, WaitAction, WaitJob |
| 9 | + |
| 10 | +from .._cli._runtime._contracts import ( |
| 11 | + UiPathApiTrigger, |
| 12 | + UiPathErrorCategory, |
| 13 | + UiPathResumeTrigger, |
| 14 | + UiPathResumeTriggerType, |
| 15 | + UiPathRuntimeError, |
| 16 | + UiPathRuntimeStatus, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +def _try_convert_to_json_format(value: str) -> str: |
| 21 | + try: |
| 22 | + return json.loads(value) |
| 23 | + except json.decoder.JSONDecodeError: |
| 24 | + return value |
| 25 | + |
| 26 | + |
| 27 | +async def _get_api_payload(inbox_id: str) -> Any: |
| 28 | + """Fetch payload data for API triggers. |
| 29 | +
|
| 30 | + Args: |
| 31 | + inbox_id: The Id of the inbox to fetch the payload for. |
| 32 | +
|
| 33 | + Returns: |
| 34 | + The value field from the API response payload, or None if an error occurs. |
| 35 | + """ |
| 36 | + response = None |
| 37 | + try: |
| 38 | + uipath = UiPath() |
| 39 | + response = uipath.api_client.request( |
| 40 | + "GET", |
| 41 | + f"/orchestrator_/api/JobTriggers/GetPayload/{inbox_id}", |
| 42 | + include_folder_headers=True, |
| 43 | + ) |
| 44 | + data = response.json() |
| 45 | + return data.get("payload") |
| 46 | + except Exception as e: |
| 47 | + raise UiPathRuntimeError( |
| 48 | + "API_CONNECTION_ERROR", |
| 49 | + "Failed to get trigger payload", |
| 50 | + f"Error fetching API trigger payload for inbox {inbox_id}: {str(e)}", |
| 51 | + UiPathErrorCategory.SYSTEM, |
| 52 | + response.status_code if response else None, |
| 53 | + ) from e |
| 54 | + |
| 55 | + |
| 56 | +class HitlReader: |
| 57 | + @classmethod |
| 58 | + async def read(cls, resume_trigger: UiPathResumeTrigger) -> Optional[str]: |
| 59 | + uipath = UiPath() |
| 60 | + match resume_trigger.trigger_type: |
| 61 | + case UiPathResumeTriggerType.ACTION: |
| 62 | + if resume_trigger.item_key: |
| 63 | + action = await uipath.actions.retrieve_async( |
| 64 | + resume_trigger.item_key, |
| 65 | + app_folder_key=resume_trigger.folder_key, |
| 66 | + app_folder_path=resume_trigger.folder_path, |
| 67 | + ) |
| 68 | + return action.data |
| 69 | + |
| 70 | + case UiPathResumeTriggerType.JOB: |
| 71 | + if resume_trigger.item_key: |
| 72 | + job = await uipath.jobs.retrieve_async( |
| 73 | + resume_trigger.item_key, |
| 74 | + folder_key=resume_trigger.folder_key, |
| 75 | + folder_path=resume_trigger.folder_path, |
| 76 | + ) |
| 77 | + if ( |
| 78 | + job.state |
| 79 | + and not job.state.lower() |
| 80 | + == UiPathRuntimeStatus.SUCCESSFUL.value.lower() |
| 81 | + ): |
| 82 | + raise UiPathRuntimeError( |
| 83 | + "INVOKED_PROCESS_FAILURE", |
| 84 | + "Invoked process did not finish successfully.", |
| 85 | + _try_convert_to_json_format(str(job.job_error or job.info)), |
| 86 | + ) |
| 87 | + return job.output_arguments |
| 88 | + |
| 89 | + case UiPathResumeTriggerType.API: |
| 90 | + if resume_trigger.api_resume and resume_trigger.api_resume.inbox_id: |
| 91 | + return await _get_api_payload(resume_trigger.api_resume.inbox_id) |
| 92 | + |
| 93 | + case _: |
| 94 | + raise UiPathRuntimeError( |
| 95 | + "UNKNOWN_TRIGGER_TYPE", |
| 96 | + "Unexpected trigger type received", |
| 97 | + f"Trigger type :{type(resume_trigger.trigger_type)} is invalid", |
| 98 | + UiPathErrorCategory.USER, |
| 99 | + ) |
| 100 | + |
| 101 | + raise UiPathRuntimeError( |
| 102 | + "HITL_FEEDBACK_FAILURE", |
| 103 | + "Failed to receive payload from HITL action", |
| 104 | + detail="Failed to receive payload from HITL action", |
| 105 | + category=UiPathErrorCategory.SYSTEM, |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +@dataclass |
| 110 | +class HitlProcessor: |
| 111 | + """Processes events in a Human-(Robot/Agent)-In-The-Loop scenario.""" |
| 112 | + |
| 113 | + value: Any |
| 114 | + |
| 115 | + @cached_property |
| 116 | + def type(self) -> UiPathResumeTriggerType: |
| 117 | + """Returns the type of the interrupt value.""" |
| 118 | + if isinstance(self.value, CreateAction) or isinstance(self.value, WaitAction): |
| 119 | + return UiPathResumeTriggerType.ACTION |
| 120 | + if isinstance(self.value, InvokeProcess) or isinstance(self.value, WaitJob): |
| 121 | + return UiPathResumeTriggerType.JOB |
| 122 | + # default to API trigger |
| 123 | + return UiPathResumeTriggerType.API |
| 124 | + |
| 125 | + async def create_resume_trigger(self) -> Optional[UiPathResumeTrigger]: |
| 126 | + """Returns the resume trigger.""" |
| 127 | + uipath = UiPath() |
| 128 | + try: |
| 129 | + hitl_input = self.value |
| 130 | + resume_trigger = UiPathResumeTrigger( |
| 131 | + trigger_type=self.type, payload=hitl_input.model_dump_json() |
| 132 | + ) |
| 133 | + match self.type: |
| 134 | + case UiPathResumeTriggerType.ACTION: |
| 135 | + resume_trigger.folder_path = hitl_input.app_folder_path |
| 136 | + resume_trigger.folder_key = hitl_input.app_folder_key |
| 137 | + if isinstance(hitl_input, WaitAction): |
| 138 | + resume_trigger.item_key = hitl_input.action.key |
| 139 | + elif isinstance(hitl_input, CreateAction): |
| 140 | + action = await uipath.actions.create_async( |
| 141 | + title=hitl_input.title, |
| 142 | + app_name=hitl_input.app_name if hitl_input.app_name else "", |
| 143 | + app_folder_path=hitl_input.app_folder_path |
| 144 | + if hitl_input.app_folder_path |
| 145 | + else "", |
| 146 | + app_folder_key=hitl_input.app_folder_key |
| 147 | + if hitl_input.app_folder_key |
| 148 | + else "", |
| 149 | + app_key=hitl_input.app_key if hitl_input.app_key else "", |
| 150 | + app_version=hitl_input.app_version |
| 151 | + if hitl_input.app_version |
| 152 | + else 1, |
| 153 | + assignee=hitl_input.assignee if hitl_input.assignee else "", |
| 154 | + data=hitl_input.data, |
| 155 | + ) |
| 156 | + if action: |
| 157 | + resume_trigger.item_key = action.key |
| 158 | + |
| 159 | + case UiPathResumeTriggerType.JOB: |
| 160 | + resume_trigger.folder_path = hitl_input.process_folder_path |
| 161 | + resume_trigger.folder_key = hitl_input.process_folder_key |
| 162 | + if isinstance(hitl_input, WaitJob): |
| 163 | + resume_trigger.item_key = hitl_input.job.key |
| 164 | + elif isinstance(hitl_input, InvokeProcess): |
| 165 | + job = await uipath.processes.invoke_async( |
| 166 | + name=hitl_input.name, |
| 167 | + input_arguments=hitl_input.input_arguments, |
| 168 | + folder_path=hitl_input.process_folder_path, |
| 169 | + folder_key=hitl_input.process_folder_key, |
| 170 | + ) |
| 171 | + if job: |
| 172 | + resume_trigger.item_key = job.key |
| 173 | + |
| 174 | + case UiPathResumeTriggerType.API: |
| 175 | + resume_trigger.api_resume = UiPathApiTrigger( |
| 176 | + inbox_id=str(uuid.uuid4()), request=hitl_input.prefix |
| 177 | + ) |
| 178 | + case _: |
| 179 | + raise UiPathRuntimeError( |
| 180 | + "UNKNOWN_HITL_MODEL", |
| 181 | + "Unexpected model received", |
| 182 | + f"{type(hitl_input)} is not a valid Human(Robot/Agent)-In-The-Loop model", |
| 183 | + UiPathErrorCategory.USER, |
| 184 | + ) |
| 185 | + except Exception as e: |
| 186 | + raise UiPathRuntimeError( |
| 187 | + "HITL_ACTION_CREATION_FAILED", |
| 188 | + "Failed to create HITL action", |
| 189 | + f"{str(e)}", |
| 190 | + UiPathErrorCategory.SYSTEM, |
| 191 | + ) from e |
| 192 | + |
| 193 | + return resume_trigger |
0 commit comments