forked from trpc-group/trpc-agent-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_command_handler.py
More file actions
181 lines (159 loc) · 6.7 KB
/
Copy path_command_handler.py
File metadata and controls
181 lines (159 loc) · 6.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
from __future__ import annotations
import asyncio
import os
import sys
from dataclasses import dataclass
from dataclasses import field
from typing import Awaitable
from typing import Callable
from typing import TypeAlias
from nanobot.bus.events import InboundMessage
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from trpc_agent_sdk.log import logger
from trpc_agent_sdk.sessions import BaseSessionService
from .._utils import parse_origin
from ..config import ClawConfig
from ..config import DEFAULT_USER_ID
@dataclass
class TrpcClawCommandHandlerParams:
"""Command handler for trpc_claw."""
config: ClawConfig
bus: MessageBus
session_service: BaseSessionService
active_tasks: dict[str, list[asyncio.Task]] = field(default_factory=dict)
background_tasks: dict[str, list[asyncio.Task]] = field(default_factory=dict)
TrpcClawCommandHandlerCallback: TypeAlias = Callable[[InboundMessage, TrpcClawCommandHandlerParams], Awaitable[None]]
class TrpcClawCommandHandler:
"""Command handler for trpc_claw."""
def __init__(self,
params: TrpcClawCommandHandlerParams,
callback: dict[str, TrpcClawCommandHandlerCallback] | None = None):
self.params = params
self.callbacks = {
"/stop": self._handle_stop,
"/new": self._handle_new,
"/help": self._handle_help,
"/restart": self._handle_restart,
"/quit": self._handle_quit,
"/exit": self._handle_quit,
"quit": self._handle_quit,
"exit": self._handle_quit,
}
if callback:
self.callbacks.update(callback)
self.restarting = False
async def handle(self, msg: InboundMessage) -> bool:
"""Handle the command.
Args:
msg: The inbound message.
Returns:
bool: True if the command is handled, False otherwise.
"""
if msg.content.strip().lower() in self.callbacks:
await self.callbacks[msg.content.strip().lower()](msg, self.params)
return True
return False
async def _handle_stop(self, msg: InboundMessage, params: TrpcClawCommandHandlerParams) -> None:
"""Cancel active tasks for the current session key."""
tasks = params.active_tasks.pop(msg.session_key, [])
bg_tasks = params.background_tasks.pop(msg.session_key, [])
cancelled = 0
for t in tasks:
if not t.done():
t.cancel()
cancelled += 1
for t in bg_tasks:
if not t.done():
t.cancel()
cancelled += 1
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
if bg_tasks:
await asyncio.gather(*bg_tasks, return_exceptions=True)
content = f"Stopped {cancelled} task(s)." if cancelled else "No active task to stop."
await params.bus.publish_outbound(OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content=content,
))
async def _handle_new(self, msg: InboundMessage, params: TrpcClawCommandHandlerParams) -> None:
"""Start a new conversation by clearing current session state."""
# Cancel any in-flight work for this session first.
await self._handle_stop(msg, params)
channel, _ = parse_origin(msg)
user_id = msg.sender_id or f"{channel}_{DEFAULT_USER_ID}"
app_name = params.config.runtime.app_name
try:
await params.session_service.delete_session(
app_name=app_name,
user_id=user_id,
session_id=msg.session_key,
)
except Exception:
logger.error("Failed to clear session for /new: %s", msg.session_key)
await params.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content="Failed to start a new session. Please try again.",
))
return
await params.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content="New session started.",
))
async def _handle_help(self, msg: InboundMessage, params: TrpcClawCommandHandlerParams) -> None:
"""Show available runtime commands."""
await params.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content=("OpenClaw commands:\n"
"/new — Start a new conversation\n"
"/stop — Stop active tasks in current session\n"
"/restart — Restart worker process and reload config\n"
"/quit|/exit (or quit|exit) — End current interaction\n"
"/help — Show available commands"),
))
async def _handle_quit(self, msg: InboundMessage, params: TrpcClawCommandHandlerParams) -> None:
"""End current interaction for this channel/session."""
await params.bus.publish_outbound(OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content="Bye.",
))
async def _handle_restart(self, msg: InboundMessage, params: TrpcClawCommandHandlerParams) -> None:
"""Restart worker process (WeCom command only)."""
if self.restarting:
await params.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content="Restart already in progress...",
))
return
self.restarting = True
await params.bus.publish_outbound(
OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content="Restarting worker process and reloading config...",
))
asyncio.create_task(self._restart_process())
async def _restart_process(self, *, delay_s: float = 0.5) -> None:
"""Replace current process to reload config/runtime state."""
await asyncio.sleep(delay_s)
logger.warning("Restarting process to reload config")
try:
argv = [sys.executable, *sys.argv]
os.execv(sys.executable, argv)
except Exception as ex: # pylint: disable=broad-except
logger.error("Failed to restart process: %s", ex)