| 1 | import asyncio |
| 2 | from datetime import timedelta |
| 3 | from helpers.tool import Tool, Response |
| 4 | from helpers.print_style import PrintStyle |
| 5 | from helpers.wait import managed_wait |
| 6 | from helpers.localization import Localization |
| 7 | |
| 8 | class WaitTool(Tool): |
| 9 | |
| 10 | async def execute(self, **kwargs) -> Response: |
| 11 | await self.agent.handle_intervention() |
| 12 | |
| 13 | seconds = self.args.get("seconds", 0) |
| 14 | minutes = self.args.get("minutes", 0) |
| 15 | hours = self.args.get("hours", 0) |
| 16 | days = self.args.get("days", 0) |
| 17 | until_timestamp_str = self.args.get("until") |
| 18 | |
| 19 | is_duration_wait = not bool(until_timestamp_str) |
| 20 | |
| 21 | now = Localization.get().now() |
| 22 | target_time = None |
| 23 | |
| 24 | if until_timestamp_str: |
| 25 | try: |
| 26 | target_time = Localization.get().localtime_str_to_utc_dt(until_timestamp_str) |
| 27 | if not target_time: |
| 28 | raise ValueError(f"Invalid timestamp format: {until_timestamp_str}") |
| 29 | except ValueError as e: |
| 30 | return Response( |
| 31 | message=str(e), |
| 32 | break_loop=False, |
| 33 | ) |
| 34 | else: |
| 35 | wait_duration = timedelta( |
| 36 | days=int(days), |
| 37 | hours=int(hours), |
| 38 | minutes=int(minutes), |
| 39 | seconds=int(seconds), |
| 40 | ) |
| 41 | if wait_duration.total_seconds() <= 0: |
| 42 | return Response( |
| 43 | message="Wait duration must be positive.", |
| 44 | break_loop=False, |
| 45 | ) |
| 46 | target_time = now + wait_duration |
| 47 | |
| 48 | if target_time <= now: |
| 49 | return Response( |
| 50 | message=f"Target time {Localization.get().serialize_datetime(target_time)} is in the past.", |
| 51 | break_loop=False, |
| 52 | ) |
| 53 | |
| 54 | PrintStyle.info(f"Waiting until {Localization.get().serialize_datetime(target_time)}...") |
| 55 | |
| 56 | target_time = await managed_wait( |
| 57 | agent=self.agent, |
| 58 | target_time=target_time, |
| 59 | is_duration_wait=is_duration_wait, |
| 60 | log=self.log, |
| 61 | get_heading_callback=self.get_heading |
| 62 | ) |
| 63 | |
| 64 | if self.log: |
| 65 | self.log.update(heading=self.get_heading("Done", done=True)) |
| 66 | |
| 67 | message = self.agent.read_prompt( |
| 68 | "fw.wait_complete.md", |
| 69 | target_time=Localization.get().serialize_datetime(target_time) |
| 70 | ) |
| 71 | |
| 72 | return Response( |
| 73 | message=message, |
| 74 | break_loop=False, |
| 75 | ) |
| 76 | |
| 77 | def get_log_object(self): |
| 78 | return self.agent.context.log.log( |
| 79 | type="progress", |
| 80 | heading=self.get_heading(), |
| 81 | content="", |
| 82 | kvps=self.args, |
| 83 | ) |
| 84 | |
| 85 | def get_heading(self, text: str = "", done: bool = False): |
| 86 | done_icon = " icon://done_all" if done else "" |
| 87 | if not text: |
| 88 | text = f"Waiting..." |
| 89 | return f"icon://timer Wait: {text}{done_icon}" |