11# Copyright (c) ModelScope Contributors. All rights reserved.
2- from typing import List
2+ from typing import TYPE_CHECKING , List , Optional
33
44from ms_agent .agent .runtime import Runtime
55from ms_agent .callbacks import Callback
66from ms_agent .llm .utils import Message
77from ms_agent .utils import get_logger
88from omegaconf import DictConfig
99
10+ if TYPE_CHECKING :
11+ from ms_agent .command .router import CommandRouter
12+
1013logger = get_logger ()
1114
1215
1316class InputCallback (Callback ):
14- """Waiting for human inputs."""
17+ """Waiting for human inputs. Supports slash command interception. """
1518
16- def __init__ (self , config : DictConfig ):
19+ def __init__ (
20+ self ,
21+ config : DictConfig ,
22+ command_router : Optional ['CommandRouter' ] = None ,
23+ ):
1724 super ().__init__ (config )
25+ if command_router is None :
26+ command_router = self ._build_default_router ()
27+ self ._command_router = command_router
28+
29+ @staticmethod
30+ def _build_default_router () -> 'CommandRouter' :
31+ from ms_agent .command import CommandRouter , register_builtin_commands
32+
33+ router = CommandRouter ()
34+ register_builtin_commands (router )
35+ return router
1836
1937 async def after_tool_call (self , runtime : Runtime , messages : List [Message ]):
2038 if messages [- 1 ].tool_calls or messages [- 1 ].role in ('tool' , 'user' ):
@@ -27,6 +45,47 @@ async def after_tool_call(self, runtime: Runtime, messages: List[Message]):
2745
2846 if not query :
2947 runtime .should_stop = True
30- else :
48+ return
49+
50+ if self ._command_router :
51+ handled = await self ._try_command (query , runtime , messages )
52+ if handled :
53+ return
54+
55+ runtime .should_stop = False
56+ messages .append (Message (role = 'user' , content = query ))
57+
58+ async def _try_command (
59+ self ,
60+ query : str ,
61+ runtime : Runtime ,
62+ messages : List [Message ],
63+ ) -> bool :
64+ """Try to dispatch as slash command. Returns True if handled."""
65+ from ms_agent .command .router import CommandRouter
66+ from ms_agent .command .types import CommandContext , CommandResultType
67+
68+ if not CommandRouter .is_command (query ):
69+ return False
70+
71+ cmd_name , args = CommandRouter .parse_input (query )
72+ ctx = CommandContext (
73+ raw_input = query ,
74+ command_name = cmd_name ,
75+ args = args ,
76+ source = 'cli' ,
77+ runtime = runtime ,
78+ extra = {'router' : self ._command_router },
79+ )
80+ result = await self ._command_router .dispatch (ctx )
81+ if result is None :
82+ return False
83+
84+ if result .type == CommandResultType .QUIT :
85+ runtime .should_stop = True
86+ elif result .type == CommandResultType .MESSAGE :
87+ print (result .content )
88+ elif result .type == CommandResultType .SUBMIT_PROMPT :
89+ messages .append (Message (role = 'user' , content = result .content ))
3190 runtime .should_stop = False
32- messages . append ( Message ( role = 'user' , content = query ))
91+ return True
0 commit comments