Coverage for aipyapp/plugins/p_style_agent.py: 0%

1#!/usr/bin/env python

2# -*- coding: utf-8 -*-

3

4 from typing import Any, Dict

5 from datetime import datetime

6

7 from aipyapp import Event

8 from aipyapp.display import RichDisplayPlugin

9

10 class DisplayAgent(RichDisplayPlugin):

11 """Agent模式显示插件 - 捕获所有输出用于API返回"""

12 name = "agent"

13 version = "1.0.0"

14 description = "Agent display style"

15 author = "AiPy Team"

16

17 def __init__(self, console, quiet: bool = True):

18 super().__init__(console, quiet)

19 # 捕获的输出数据

20 self.captured_data = {

21 'messages': [],

22 'results': [],

23 'errors': [],

24 'status': 'running',

25 'start_time': datetime.now().isoformat(),

26 'end_time': None,

27 'metadata': {}

28 }

29

30 def _add_message(self, message_type: str, content: Any, timestamp: str = None):

31 """添加消息到捕获数据"""

32 if timestamp is None:

33 timestamp = datetime.now().isoformat()

34

35 self.captured_data['messages'].append({

36 'type': message_type,

37 'content': content,

38 'timestamp': timestamp

39 })

40

41 def get_captured_data(self) -> Dict:

42 """获取捕获的数据"""

43 return self.captured_data.copy()

44

45 def clear_captured_data(self):

46 """清空捕获的数据"""

47 self.captured_data = {

48 'messages': [],

49 'results': [],

50 'errors': [],

51 'status': 'running',

52 'start_time': datetime.now().isoformat(),

53 'end_time': None,

54 'metadata': {}

55 }

56

57 # 重写父类方法，捕获输出而不显示

58 def print(self, message: str, style: str = None):

59 """捕获打印消息"""

60 self._add_message('print', {'message': message, 'style': style})

61

62 def input(self, prompt: str) -> str:

63 """Agent模式不支持交互输入"""

64 self._add_message('input_request', {'prompt': prompt})

65 return ''

66

67 def confirm(self, prompt, default="n", auto=None):

68 """Agent模式自动确认"""

69 self._add_message('confirm', {'prompt': prompt, 'default': default, 'auto_response': auto})

70 return auto if auto is not None else (default == "y")

71

72 # 事件处理方法

73 def on_task_start(self, event: Event):

74 """任务开始"""

75 instruction = event.data.get('instruction', 'Unknown instruction')

76 self._add_message('task_start', {

77 'instruction': instruction,

78 'task_id': event.data.get('task_id', None)

79 })

80 self.captured_data['status'] = 'running'

81 self.captured_data['metadata']['instruction'] = instruction

82

83 def on_response_complete(self, event: Event):

84 """LLM响应完成"""

85 llm = event.data.get('llm', 'unknown')

86 msg = event.data.get('msg')

87 message_content = msg.content if (msg and hasattr(msg, 'content')) else str(msg) if msg else 'No response'

88

89 self._add_message('llm_response', {

90 'llm': llm,

91 'message': message_content

92 })

93

94 def on_exec_result(self, event: Event):

95 """代码执行结果"""

96 block = event.data.get('block')

97 result = event.data.get('result', {})

98

99 result_data = {

100 'block_name': block.name if (block and hasattr(block, 'name')) else 'unknown',

101 'language': block.lang if (block and hasattr(block, 'lang')) else 'unknown',

102 'result': result

103 }

104 self._add_message('exec_result', result_data)

105 self.captured_data['results'].append(result_data)

106

107 def on_task_end(self, event: Event):

108 """任务结束"""

109 self.captured_data['status'] = 'completed'

110 self.captured_data['end_time'] = datetime.now().isoformat()

111 self._add_message('task_end', {

112 'path': event.data.get('path', None)

113 })

114

115 def on_exception(self, event: Event):

116 """异常处理"""

117 error_data = {

118 'message': event.data.get('msg', 'Unknown error'),

119 'exception': str(event.data.get('exception')) if event.data.get('exception') else None

120 }

121 self._add_message('error', error_data)

122 self.captured_data['errors'].append(error_data)

123 self.captured_data['status'] = 'error'

124

125 def on_stream(self, event: Event):

126 """流式响应"""

127 self._add_message('stream', {

128 'llm': event.data.get('llm', 'unknown'),

129 'lines': event.data.get('lines', []),

130 'reason': event.data.get('reason', False)

131 })

132

133 def on_parse_reply(self, event: Event):

134 """解析回复"""

135 self._add_message('parse_reply', {

136 'result': event.data.get('result', {})

137 })

138

139 def on_mcp_result(self, event: Event):

140 """MCP工具调用结果"""

141 block = event.data.get('block')

142 self._add_message('mcp_result', {

143 'block': str(block) if block else None,

144 'result': event.data.get('result', None)

145 })

146

147 def on_upload_result(self, event: Event):

148 """云端上传结果"""

149 self._add_message('upload_result', {

150 'status_code': event.data.get('status_code', None),

151 'url': event.data.get('url', None)

152 })

153

154 def on_query_start(self, event: Event):

155 """查询开始"""

156 self._add_message('query_start', {

157 'timestamp': datetime.now().isoformat()

158 })

159

160 def on_round_start(self, event: Event):

161 """回合开始"""

162 self._add_message('round_start', {

163 'instruction': event.data.get('instruction', 'Unknown'),

164 'user_prompt': str(event.data.get('user_prompt', ''))

165 })

166

167 def on_round_end(self, event: Event):

168 """回合结束"""

169 self._add_message('round_end', {

170 'summary': event.data.get('summary', {}),

171 'response': str(event.data.get('response', ''))

172 })

173

174 def on_exec(self, event: Event):

175 """代码执行开始"""

176 block = event.data.get('block')

177 self._add_message('exec_start', {

178 'block_name': block.name if (block and hasattr(block, 'name')) else 'unknown',

179 'language': block.lang if (block and hasattr(block, 'lang')) else 'unknown',

180 'code': block.code if (block and hasattr(block, 'code')) else 'No code'

181 })

182

183 def on_edit_start(self, event: Event):

184 """代码编辑开始"""

185 instruction = event.data.get('instruction', {})

186 self._add_message('edit_start', {

187 'block_name': instruction.get('name', 'unknown'),

188 'old_str': instruction.get('old', ''),

189 'new_str': instruction.get('new', ''),

190 'replace_all': instruction.get('replace_all', False)

191 })

192

193 def on_edit_result(self, event: Event):

194 """代码编辑结果"""

195 result = event.data.get('result', {})

196 self._add_message('edit_result', {

197 'success': result.get('success', False),

198 'message': result.get('message', ''),

199 'block_name': result.get('block_name', 'unknown'),

200 'new_version': result.get('new_version'),

201 'old_str': result.get('old_str', ''),

202 'new_str': result.get('new_str', ''),

203 'replace_all': result.get('replace_all', False)

204 })

205

206 def on_mcp_call(self, event: Event):

207 """MCP工具调用"""

208 block = event.data.get('block', {})

209 self._add_message('mcp_call', {

210 'content': block.get('content') if isinstance(block, dict) else str(block),

211 'language': block.get('language') if isinstance(block, dict) else 'json'

212 })