agent: use ContextVar for tool routing context

This commit is contained in:
jr_blue_551
2026-04-21 13:25:30 +08:00
committed by Xubin Ren
parent 82aa9efc02
commit ff8c28d5a8
4 changed files with 150 additions and 29 deletions
+9 -7
View File
@@ -58,14 +58,14 @@ class CronTool(Tool):
def __init__(self, cron_service: CronService, default_timezone: str = "UTC"):
self._cron = cron_service
self._default_timezone = default_timezone
self._channel = ""
self._chat_id = ""
self._channel: ContextVar[str] = ContextVar("cron_channel", default="")
self._chat_id: ContextVar[str] = ContextVar("cron_chat_id", default="")
self._in_cron_context: ContextVar[bool] = ContextVar("cron_in_context", default=False)
def set_context(self, channel: str, chat_id: str) -> None:
"""Set the current session context for delivery."""
self._channel = channel
self._chat_id = chat_id
self._channel.set(channel)
self._chat_id.set(chat_id)
def set_cron_context(self, active: bool):
"""Mark whether the tool is executing inside a cron job callback."""
@@ -155,7 +155,9 @@ class CronTool(Tool):
"describing what to do when the job triggers "
"(e.g. the reminder text). Retry including message=\"...\"."
)
if not self._channel or not self._chat_id:
channel = self._channel.get()
chat_id = self._chat_id.get()
if not channel or not chat_id:
return "Error: no session context (channel/chat_id)"
if tz and not cron_expr:
return "Error: tz can only be used with cron_expr"
@@ -194,8 +196,8 @@ class CronTool(Tool):
schedule=schedule,
message=message,
deliver=deliver,
channel=self._channel,
to=self._chat_id,
channel=channel,
to=chat_id,
delete_after_run=delete_after,
)
return f"Created job '{job.name}' (id: {job.id})"