kweaver-dolphin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. DolphinLanguageSDK/__init__.py +58 -0
  2. dolphin/__init__.py +62 -0
  3. dolphin/cli/__init__.py +20 -0
  4. dolphin/cli/args/__init__.py +9 -0
  5. dolphin/cli/args/parser.py +567 -0
  6. dolphin/cli/builtin_agents/__init__.py +22 -0
  7. dolphin/cli/commands/__init__.py +4 -0
  8. dolphin/cli/interrupt/__init__.py +8 -0
  9. dolphin/cli/interrupt/handler.py +205 -0
  10. dolphin/cli/interrupt/keyboard.py +82 -0
  11. dolphin/cli/main.py +49 -0
  12. dolphin/cli/multimodal/__init__.py +34 -0
  13. dolphin/cli/multimodal/clipboard.py +327 -0
  14. dolphin/cli/multimodal/handler.py +249 -0
  15. dolphin/cli/multimodal/image_processor.py +214 -0
  16. dolphin/cli/multimodal/input_parser.py +149 -0
  17. dolphin/cli/runner/__init__.py +8 -0
  18. dolphin/cli/runner/runner.py +989 -0
  19. dolphin/cli/ui/__init__.py +10 -0
  20. dolphin/cli/ui/console.py +2795 -0
  21. dolphin/cli/ui/input.py +340 -0
  22. dolphin/cli/ui/layout.py +425 -0
  23. dolphin/cli/ui/stream_renderer.py +302 -0
  24. dolphin/cli/utils/__init__.py +8 -0
  25. dolphin/cli/utils/helpers.py +135 -0
  26. dolphin/cli/utils/version.py +49 -0
  27. dolphin/core/__init__.py +107 -0
  28. dolphin/core/agent/__init__.py +10 -0
  29. dolphin/core/agent/agent_state.py +69 -0
  30. dolphin/core/agent/base_agent.py +970 -0
  31. dolphin/core/code_block/__init__.py +0 -0
  32. dolphin/core/code_block/agent_init_block.py +0 -0
  33. dolphin/core/code_block/assign_block.py +98 -0
  34. dolphin/core/code_block/basic_code_block.py +1865 -0
  35. dolphin/core/code_block/explore_block.py +1327 -0
  36. dolphin/core/code_block/explore_block_v2.py +712 -0
  37. dolphin/core/code_block/explore_strategy.py +672 -0
  38. dolphin/core/code_block/judge_block.py +220 -0
  39. dolphin/core/code_block/prompt_block.py +32 -0
  40. dolphin/core/code_block/skill_call_deduplicator.py +291 -0
  41. dolphin/core/code_block/tool_block.py +129 -0
  42. dolphin/core/common/__init__.py +17 -0
  43. dolphin/core/common/constants.py +176 -0
  44. dolphin/core/common/enums.py +1173 -0
  45. dolphin/core/common/exceptions.py +133 -0
  46. dolphin/core/common/multimodal.py +539 -0
  47. dolphin/core/common/object_type.py +165 -0
  48. dolphin/core/common/output_format.py +432 -0
  49. dolphin/core/common/types.py +36 -0
  50. dolphin/core/config/__init__.py +16 -0
  51. dolphin/core/config/global_config.py +1289 -0
  52. dolphin/core/config/ontology_config.py +133 -0
  53. dolphin/core/context/__init__.py +12 -0
  54. dolphin/core/context/context.py +1580 -0
  55. dolphin/core/context/context_manager.py +161 -0
  56. dolphin/core/context/var_output.py +82 -0
  57. dolphin/core/context/variable_pool.py +356 -0
  58. dolphin/core/context_engineer/__init__.py +41 -0
  59. dolphin/core/context_engineer/config/__init__.py +5 -0
  60. dolphin/core/context_engineer/config/settings.py +402 -0
  61. dolphin/core/context_engineer/core/__init__.py +7 -0
  62. dolphin/core/context_engineer/core/budget_manager.py +327 -0
  63. dolphin/core/context_engineer/core/context_assembler.py +583 -0
  64. dolphin/core/context_engineer/core/context_manager.py +637 -0
  65. dolphin/core/context_engineer/core/tokenizer_service.py +260 -0
  66. dolphin/core/context_engineer/example/incremental_example.py +267 -0
  67. dolphin/core/context_engineer/example/traditional_example.py +334 -0
  68. dolphin/core/context_engineer/services/__init__.py +5 -0
  69. dolphin/core/context_engineer/services/compressor.py +399 -0
  70. dolphin/core/context_engineer/utils/__init__.py +6 -0
  71. dolphin/core/context_engineer/utils/context_utils.py +441 -0
  72. dolphin/core/context_engineer/utils/message_formatter.py +270 -0
  73. dolphin/core/context_engineer/utils/token_utils.py +139 -0
  74. dolphin/core/coroutine/__init__.py +15 -0
  75. dolphin/core/coroutine/context_snapshot.py +154 -0
  76. dolphin/core/coroutine/context_snapshot_profile.py +922 -0
  77. dolphin/core/coroutine/context_snapshot_store.py +268 -0
  78. dolphin/core/coroutine/execution_frame.py +145 -0
  79. dolphin/core/coroutine/execution_state_registry.py +161 -0
  80. dolphin/core/coroutine/resume_handle.py +101 -0
  81. dolphin/core/coroutine/step_result.py +101 -0
  82. dolphin/core/executor/__init__.py +18 -0
  83. dolphin/core/executor/debug_controller.py +630 -0
  84. dolphin/core/executor/dolphin_executor.py +1063 -0
  85. dolphin/core/executor/executor.py +624 -0
  86. dolphin/core/flags/__init__.py +27 -0
  87. dolphin/core/flags/definitions.py +49 -0
  88. dolphin/core/flags/manager.py +113 -0
  89. dolphin/core/hook/__init__.py +95 -0
  90. dolphin/core/hook/expression_evaluator.py +499 -0
  91. dolphin/core/hook/hook_dispatcher.py +380 -0
  92. dolphin/core/hook/hook_types.py +248 -0
  93. dolphin/core/hook/isolated_variable_pool.py +284 -0
  94. dolphin/core/interfaces.py +53 -0
  95. dolphin/core/llm/__init__.py +0 -0
  96. dolphin/core/llm/llm.py +495 -0
  97. dolphin/core/llm/llm_call.py +100 -0
  98. dolphin/core/llm/llm_client.py +1285 -0
  99. dolphin/core/llm/message_sanitizer.py +120 -0
  100. dolphin/core/logging/__init__.py +20 -0
  101. dolphin/core/logging/logger.py +526 -0
  102. dolphin/core/message/__init__.py +8 -0
  103. dolphin/core/message/compressor.py +749 -0
  104. dolphin/core/parser/__init__.py +8 -0
  105. dolphin/core/parser/parser.py +405 -0
  106. dolphin/core/runtime/__init__.py +10 -0
  107. dolphin/core/runtime/runtime_graph.py +926 -0
  108. dolphin/core/runtime/runtime_instance.py +446 -0
  109. dolphin/core/skill/__init__.py +14 -0
  110. dolphin/core/skill/context_retention.py +157 -0
  111. dolphin/core/skill/skill_function.py +686 -0
  112. dolphin/core/skill/skill_matcher.py +282 -0
  113. dolphin/core/skill/skillkit.py +700 -0
  114. dolphin/core/skill/skillset.py +72 -0
  115. dolphin/core/trajectory/__init__.py +10 -0
  116. dolphin/core/trajectory/recorder.py +189 -0
  117. dolphin/core/trajectory/trajectory.py +522 -0
  118. dolphin/core/utils/__init__.py +9 -0
  119. dolphin/core/utils/cache_kv.py +212 -0
  120. dolphin/core/utils/tools.py +340 -0
  121. dolphin/lib/__init__.py +93 -0
  122. dolphin/lib/debug/__init__.py +8 -0
  123. dolphin/lib/debug/visualizer.py +409 -0
  124. dolphin/lib/memory/__init__.py +28 -0
  125. dolphin/lib/memory/async_processor.py +220 -0
  126. dolphin/lib/memory/llm_calls.py +195 -0
  127. dolphin/lib/memory/manager.py +78 -0
  128. dolphin/lib/memory/sandbox.py +46 -0
  129. dolphin/lib/memory/storage.py +245 -0
  130. dolphin/lib/memory/utils.py +51 -0
  131. dolphin/lib/ontology/__init__.py +12 -0
  132. dolphin/lib/ontology/basic/__init__.py +0 -0
  133. dolphin/lib/ontology/basic/base.py +102 -0
  134. dolphin/lib/ontology/basic/concept.py +130 -0
  135. dolphin/lib/ontology/basic/object.py +11 -0
  136. dolphin/lib/ontology/basic/relation.py +63 -0
  137. dolphin/lib/ontology/datasource/__init__.py +27 -0
  138. dolphin/lib/ontology/datasource/datasource.py +66 -0
  139. dolphin/lib/ontology/datasource/oracle_datasource.py +338 -0
  140. dolphin/lib/ontology/datasource/sql.py +845 -0
  141. dolphin/lib/ontology/mapping.py +177 -0
  142. dolphin/lib/ontology/ontology.py +733 -0
  143. dolphin/lib/ontology/ontology_context.py +16 -0
  144. dolphin/lib/ontology/ontology_manager.py +107 -0
  145. dolphin/lib/skill_results/__init__.py +31 -0
  146. dolphin/lib/skill_results/cache_backend.py +559 -0
  147. dolphin/lib/skill_results/result_processor.py +181 -0
  148. dolphin/lib/skill_results/result_reference.py +179 -0
  149. dolphin/lib/skill_results/skillkit_hook.py +324 -0
  150. dolphin/lib/skill_results/strategies.py +328 -0
  151. dolphin/lib/skill_results/strategy_registry.py +150 -0
  152. dolphin/lib/skillkits/__init__.py +44 -0
  153. dolphin/lib/skillkits/agent_skillkit.py +155 -0
  154. dolphin/lib/skillkits/cognitive_skillkit.py +82 -0
  155. dolphin/lib/skillkits/env_skillkit.py +250 -0
  156. dolphin/lib/skillkits/mcp_adapter.py +616 -0
  157. dolphin/lib/skillkits/mcp_skillkit.py +771 -0
  158. dolphin/lib/skillkits/memory_skillkit.py +650 -0
  159. dolphin/lib/skillkits/noop_skillkit.py +31 -0
  160. dolphin/lib/skillkits/ontology_skillkit.py +89 -0
  161. dolphin/lib/skillkits/plan_act_skillkit.py +452 -0
  162. dolphin/lib/skillkits/resource/__init__.py +52 -0
  163. dolphin/lib/skillkits/resource/models/__init__.py +6 -0
  164. dolphin/lib/skillkits/resource/models/skill_config.py +109 -0
  165. dolphin/lib/skillkits/resource/models/skill_meta.py +127 -0
  166. dolphin/lib/skillkits/resource/resource_skillkit.py +393 -0
  167. dolphin/lib/skillkits/resource/skill_cache.py +215 -0
  168. dolphin/lib/skillkits/resource/skill_loader.py +395 -0
  169. dolphin/lib/skillkits/resource/skill_validator.py +406 -0
  170. dolphin/lib/skillkits/resource_skillkit.py +11 -0
  171. dolphin/lib/skillkits/search_skillkit.py +163 -0
  172. dolphin/lib/skillkits/sql_skillkit.py +274 -0
  173. dolphin/lib/skillkits/system_skillkit.py +509 -0
  174. dolphin/lib/skillkits/vm_skillkit.py +65 -0
  175. dolphin/lib/utils/__init__.py +9 -0
  176. dolphin/lib/utils/data_process.py +207 -0
  177. dolphin/lib/utils/handle_progress.py +178 -0
  178. dolphin/lib/utils/security.py +139 -0
  179. dolphin/lib/utils/text_retrieval.py +462 -0
  180. dolphin/lib/vm/__init__.py +11 -0
  181. dolphin/lib/vm/env_executor.py +895 -0
  182. dolphin/lib/vm/python_session_manager.py +453 -0
  183. dolphin/lib/vm/vm.py +610 -0
  184. dolphin/sdk/__init__.py +60 -0
  185. dolphin/sdk/agent/__init__.py +12 -0
  186. dolphin/sdk/agent/agent_factory.py +236 -0
  187. dolphin/sdk/agent/dolphin_agent.py +1106 -0
  188. dolphin/sdk/api/__init__.py +4 -0
  189. dolphin/sdk/runtime/__init__.py +8 -0
  190. dolphin/sdk/runtime/env.py +363 -0
  191. dolphin/sdk/skill/__init__.py +10 -0
  192. dolphin/sdk/skill/global_skills.py +706 -0
  193. dolphin/sdk/skill/traditional_toolkit.py +260 -0
  194. kweaver_dolphin-0.1.0.dist-info/METADATA +521 -0
  195. kweaver_dolphin-0.1.0.dist-info/RECORD +199 -0
  196. kweaver_dolphin-0.1.0.dist-info/WHEEL +5 -0
  197. kweaver_dolphin-0.1.0.dist-info/entry_points.txt +27 -0
  198. kweaver_dolphin-0.1.0.dist-info/licenses/LICENSE.txt +201 -0
  199. kweaver_dolphin-0.1.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,630 @@
1
+ import json
2
+ from enum import Enum
3
+ from typing import Optional, Dict, Any, List
4
+ from dataclasses import dataclass
5
+
6
+ from dolphin.core.context.context import Context
7
+ from dolphin.core.logging.logger import console
8
+ from dolphin.core.common.exceptions import DebuggerQuitException
9
+ from dolphin.lib.debug.visualizer import TraceVisualizer
10
+
11
+
12
+
13
+ class DebugCommand(Enum):
14
+ """Debug command enumeration"""
15
+
16
+ STEP = "step" # Step execution (pause for each block)
17
+ NEXT = "next" # Step execution (current implementation is equivalent to step)
18
+ CONTINUE = "continue" # Continue executing until the next breakpoint
19
+ RUN = "run" # Run to completion (ignore all breakpoints)
20
+ UNTIL = "until" # Run to a specified block
21
+ VARS = "vars" # View variables
22
+ VAR = "var" # View specific variables
23
+ PROGRESS = "progress" # Check execution progress
24
+ BREAK = "break" # Set breakpoint
25
+ DELETE = "delete" # Delete breakpoint
26
+ LIST = "list" # Display breakpoint list
27
+ QUIT = "quit" # Exit debugging
28
+ HELP = "help" # Help
29
+
30
+
31
+ class RunMode(Enum):
32
+ """Execution mode enumeration"""
33
+
34
+ STEP = "step" # Step-by-step mode: each block is paused
35
+ CONTINUE = "continue" # Continue mode: run to the next breakpoint
36
+ RUN = "run" # Running mode: run to completion, ignore all breakpoints
37
+ UNTIL = "until" # Run to specified position
38
+
39
+
40
+ @dataclass
41
+ class DebugBreakpoint:
42
+ """Debug Breakpoint"""
43
+
44
+ block_index: int
45
+ condition: Optional[str] = None
46
+ enabled: bool = True
47
+
48
+
49
+ class DebugController:
50
+ """Debug Controller - Provides debugging functionality similar to gdb/pdb"""
51
+
52
+ def __init__(
53
+ self,
54
+ context: Context,
55
+ break_on_start: bool = False,
56
+ break_at: Optional[List[int]] = None,
57
+ ):
58
+ self.context = context
59
+ self.breakpoints: Dict[int, DebugBreakpoint] = {}
60
+ self.waiting_for_input = False
61
+ self.run_mode = RunMode.STEP # Default single-step mode
62
+ self.until_block: Optional[int] = None # until command target block
63
+
64
+ # Set initial breakpoints
65
+ if break_on_start:
66
+ self.set_breakpoint(0)
67
+ console("🔴 已在程序开始处(block #0)设置断点")
68
+
69
+ if break_at:
70
+ for block_index in break_at:
71
+ self.set_breakpoint(block_index)
72
+ console(f"🔴 已在 block #{block_index} 设置断点")
73
+
74
+ def enable_step_mode(self):
75
+ """Enable debug mode (maintain backward compatibility)"""
76
+ console("🐛 调试模式已启用")
77
+ console("💡 输入 'help' 查看可用命令")
78
+ console("💡 程序将在第一个 block 暂停")
79
+
80
+ def should_pause_at_block(self, block_index: int) -> bool:
81
+ """Check whether to pause at the specified block (similar to gdb/pdb breakpoint logic)"""
82
+ # RUN mode: run to completion, ignore all breakpoints
83
+ if self.run_mode == RunMode.RUN:
84
+ return False
85
+
86
+ # UNTIL mode: Run until specified block
87
+ if self.run_mode == RunMode.UNTIL:
88
+ if self.until_block is not None and block_index >= self.until_block:
89
+ # Arrive at the target position, switch back to single-step mode
90
+ self.run_mode = RunMode.STEP
91
+ self.until_block = None
92
+ return True
93
+ # Check whether a breakpoint has been hit (should still stop at breakpoints even in until mode)
94
+ if block_index in self.breakpoints and self.breakpoints[block_index].enabled:
95
+ console(f"🔴 遇到断点 #{block_index}")
96
+ self.run_mode = RunMode.STEP # Switch back to single-step mode
97
+ return True
98
+ return False
99
+
100
+ # STEP mode: each block pauses
101
+ if self.run_mode == RunMode.STEP:
102
+ return True
103
+
104
+ # CONTINUE mode: pause only at breakpoints
105
+ if self.run_mode == RunMode.CONTINUE:
106
+ if block_index in self.breakpoints:
107
+ breakpoint = self.breakpoints[block_index]
108
+ if breakpoint.enabled:
109
+ console(f"🔴 遇到断点 #{block_index}")
110
+ self.run_mode = RunMode.STEP # Switch back to single-step mode after encountering a breakpoint
111
+ return True
112
+ return False
113
+
114
+ return False
115
+
116
+ async def pause_and_wait_for_input(
117
+ self, block_index: int, current_block: Any = None
118
+ ) -> bool:
119
+ """Pause execution and wait for user input (similar to the debug prompt in gdb/pdb)"""
120
+ self.waiting_for_input = True
121
+
122
+ console(f"\n🎯 暂停在 block #{block_index}")
123
+ if current_block:
124
+ console(f"📋 当前 block 类型: {type(current_block).__name__}")
125
+
126
+ while self.waiting_for_input:
127
+ try:
128
+ from dolphin.cli.ui.input import prompt_debug_command
129
+ user_input = await prompt_debug_command("Debug > ", allow_execution_control=True)
130
+
131
+ if not user_input:
132
+ # Empty input: repeat the previous command (similar to gdb)
133
+ # Here it is simplified, defaulting to step
134
+ user_input = "step"
135
+
136
+ # Parse command
137
+ parts = user_input.split()
138
+ command = parts[0].lower()
139
+ args = parts[1:] if len(parts) > 1 else []
140
+
141
+ continue_execution = await self.handle_debug_command(
142
+ command, args, block_index
143
+ )
144
+ if continue_execution is not None:
145
+ return continue_execution
146
+
147
+ except (EOFError, KeyboardInterrupt):
148
+ console("\n🛑 中断调试,退出程序")
149
+ return False
150
+
151
+ return True
152
+
153
+ async def handle_debug_command(
154
+ self, command: str, args: List[str], current_block_index: int
155
+ ) -> Optional[bool]:
156
+ """Handle debug commands (similar to gdb/pdb)
157
+
158
+ Returns:
159
+ True - Continue execution
160
+ False - Exit debugging
161
+ None - Continue waiting for input
162
+ """
163
+ try:
164
+ # ========== Execute Control Commands ==========
165
+ if command in ["step", "s", "n", "next"]:
166
+ # Step execution: Enter step mode and execute the next block
167
+ self.run_mode = RunMode.STEP
168
+ self.waiting_for_input = False
169
+ console("➡️ 单步执行")
170
+ return True
171
+
172
+ elif command in ["continue", "c", "cont"]:
173
+ # Continue: Run until the next breakpoint
174
+ self.run_mode = RunMode.CONTINUE
175
+ self.waiting_for_input = False
176
+ console("▶️ 继续执行到下一个断点")
177
+ return True
178
+
179
+ elif command in ["run", "r"]:
180
+ # Run to completion: ignore all breakpoints
181
+ self.run_mode = RunMode.RUN
182
+ self.waiting_for_input = False
183
+ console("🚀 运行到结束(忽略所有断点)")
184
+ return True
185
+
186
+ elif command in ["until", "u"]:
187
+ # Run to the specified block
188
+ if args:
189
+ try:
190
+ target_block = int(args[0])
191
+ if target_block <= current_block_index:
192
+ console(f"❌ 目标 block #{target_block} 必须大于当前位置 #{current_block_index}")
193
+ else:
194
+ self.run_mode = RunMode.UNTIL
195
+ self.until_block = target_block
196
+ self.waiting_for_input = False
197
+ console(f"⏭️ 运行到 block #{target_block}")
198
+ return True
199
+ except ValueError:
200
+ console("❌ block 索引必须是数字")
201
+ else:
202
+ console("❌ 请指定目标 block: until <block_index>")
203
+
204
+ elif command in ["quit", "q", "exit"]:
205
+ # Exit debugging
206
+ console("🛑 退出调试模式")
207
+ from dolphin.core.common.exceptions import DebuggerQuitException
208
+ raise DebuggerQuitException()
209
+
210
+ # ========== Breakpoint Management Commands ==========
211
+ elif command in ["break", "b"]:
212
+ if args:
213
+ try:
214
+ block_index = int(args[0])
215
+ self.set_breakpoint(block_index)
216
+ except ValueError:
217
+ console("❌ 断点位置必须是数字")
218
+ else:
219
+ self.show_breakpoints()
220
+
221
+ elif command in ["delete", "d", "del"]:
222
+ if args:
223
+ try:
224
+ block_index = int(args[0])
225
+ self.delete_breakpoint(block_index)
226
+ except ValueError:
227
+ console("❌ 断点位置必须是数字")
228
+ else:
229
+ console("❌ 请指定要删除的断点: delete <block_index>")
230
+
231
+ elif command in ["list", "l"]:
232
+ self.show_breakpoints()
233
+
234
+ # ========== Variable Viewing Commands ==========
235
+ elif command in ["vars", "v"]:
236
+ self.show_all_variables()
237
+
238
+ elif command == "var":
239
+ if args:
240
+ self.show_variable(args[0])
241
+ else:
242
+ console("❌ 请指定变量名: var <variable_name>")
243
+
244
+ elif command in ["progress"]:
245
+ self.show_execution_frames()
246
+
247
+ # ========== Runtime Graph and Trajectory ==========
248
+ # 'graph' command removed as it's included in 'trace'
249
+
250
+ elif command in ["trace", "t"]:
251
+ mode = "brief"
252
+ if args and args[0].lower() == "full":
253
+ mode = "full"
254
+
255
+ try:
256
+ # Unified Rich visualization (replaces legacy print_profile)
257
+ trace_data = self.context.get_execution_trace(title="Debug Execution Trace")
258
+ visualizer = TraceVisualizer(mode=mode)
259
+ visualizer.display_trace(trace_data)
260
+ except Exception as e:
261
+ console(f"❌ 生成执行轨迹时出错: {e}")
262
+
263
+ # ========== ContextSnapshot Analysis Command ==========
264
+ elif command in ["snapshot", "sn"]:
265
+ format_type = args[0] if args else "markdown"
266
+ self.show_snapshot_analysis(format_type)
267
+
268
+ # ========== Help Command ==========
269
+ elif command in ["help", "h", "?"]:
270
+ self.show_help()
271
+
272
+ else:
273
+ console(f"❌ 未知命令: {command}")
274
+ console("💡 输入 'help' 查看可用命令")
275
+
276
+ except DebuggerQuitException:
277
+ # Re-raise the quit exception so it can be caught by the main loop
278
+ raise
279
+ except Exception as e:
280
+ console(f"❌ 执行命令时出错: {e}")
281
+ import traceback
282
+ traceback.print_exc()
283
+
284
+ return None # Wait for input continuously
285
+
286
+ def show_all_variables(self):
287
+ """Display all variables"""
288
+ console("\n📊 当前变量状态:")
289
+ console("=" * 50)
290
+
291
+ try:
292
+ all_vars = self.context.get_all_variables_values()
293
+ if not all_vars:
294
+ console("📭 暂无变量")
295
+ return
296
+
297
+ for var_name, var_value in all_vars.items():
298
+ if var_name is None:
299
+ continue
300
+ if var_name.startswith("_"): # Skip internal variables
301
+ continue
302
+
303
+ if isinstance(var_value, (dict, list)):
304
+ formatted_json = json.dumps(var_value, ensure_ascii=False, indent=2)
305
+ try:
306
+ from rich.console import Console as RichConsole
307
+ from rich.syntax import Syntax
308
+ RichConsole().print(f"📝 {var_name}:")
309
+ RichConsole().print(Syntax(formatted_json, "json", theme="monokai", background_color="default"))
310
+ except ImportError:
311
+ console(f"📝 {var_name}: {formatted_json}")
312
+ else:
313
+ value_str = self.format_value(var_value)
314
+ console(f"📝 {var_name}: {value_str}")
315
+
316
+ except Exception as e:
317
+ console(f"❌ Get变量时出错: {e}")
318
+
319
+ def show_variable(self, var_name: str):
320
+ """Display a specific variable"""
321
+ console(f"\n🔍 变量 '{var_name}':")
322
+ console("-" * 30)
323
+
324
+ try:
325
+ var_value = self.context.get_var_path_value(var_name)
326
+ if var_value is not None:
327
+ if isinstance(var_value, (dict, list)):
328
+ formatted_json = json.dumps(var_value, ensure_ascii=False, indent=2)
329
+ try:
330
+ from rich.console import Console as RichConsole
331
+ from rich.syntax import Syntax
332
+ RichConsole().print(Syntax(formatted_json, "json", theme="monokai", background_color="default"))
333
+ except ImportError:
334
+ console(formatted_json)
335
+ else:
336
+ value_str = self.format_value(var_value, detailed=True)
337
+ console(f"📝 {var_name}: {value_str}")
338
+ else:
339
+ console(f"❌ 变量 '{var_name}' 不存在")
340
+
341
+ except Exception as e:
342
+ console(f"❌ Get变量 '{var_name}' 时出错: {e}")
343
+
344
+ def format_value(self, value: Any, detailed: bool = False) -> str:
345
+ """Format variable value display"""
346
+ if value is None:
347
+ return "None"
348
+ elif isinstance(value, str):
349
+ if detailed:
350
+ return f'"{value}"'
351
+ return f'"{value[:100]}{"..." if len(value) > 100 else ""}"'
352
+ elif isinstance(value, (list, dict)):
353
+ if detailed:
354
+ return json.dumps(value, ensure_ascii=False, indent=2)
355
+ return f"{type(value).__name__}(长度: {len(value)})"
356
+ else:
357
+ return str(value)
358
+
359
+ def show_execution_frames(self):
360
+ """Display execution progress information"""
361
+ try:
362
+ # Here, coroutine execution progress/phase information can be obtained.
363
+ runtime_graph = self.context.get_runtime_graph()
364
+ if hasattr(runtime_graph, "get_all_stages"):
365
+ stages = runtime_graph.get_all_stages()
366
+
367
+ # Visualize using TraceVisualizer
368
+ visualizer = TraceVisualizer()
369
+ visualizer.display_progress(stages)
370
+ else:
371
+ console("📭 暂无执行进度信息")
372
+
373
+ except Exception as e:
374
+ console(f"❌ Get执行进度时出错: {e}")
375
+
376
+ def set_breakpoint(self, block_index: int):
377
+ """Set breakpoint"""
378
+ self.breakpoints[block_index] = DebugBreakpoint(block_index)
379
+ console(f"🔴 在 block #{block_index} 设置断点")
380
+
381
+ def delete_breakpoint(self, block_index: int):
382
+ """Delete breakpoint"""
383
+ if block_index in self.breakpoints:
384
+ del self.breakpoints[block_index]
385
+ console(f"✅ 已删除 block #{block_index} 的断点")
386
+ else:
387
+ console(f"❌ block #{block_index} 没有断点")
388
+
389
+ def show_breakpoints(self):
390
+ """Display all breakpoints"""
391
+ console("\n🔴 断点列表:")
392
+ console("-" * 30)
393
+
394
+ if not self.breakpoints:
395
+ console("📭 暂无断点")
396
+ return
397
+
398
+ for block_index, bp in self.breakpoints.items():
399
+ status = "✅ 启用" if bp.enabled else "❌ 禁用"
400
+ console(f" Block #{block_index}: {status}")
401
+
402
+ def show_snapshot_summary(self):
403
+ """Display ContextSnapshot statistics summary"""
404
+ console("\n📸 ContextSnapshot 统计摘要:")
405
+ console("=" * 60)
406
+
407
+ try:
408
+ # Create snapshot and get JSON profile
409
+ snapshot = self.context.export_runtime_state(frame_id="debug_snapshot")
410
+ profile_data = snapshot.profile(format='json')
411
+
412
+ # Display key statistics
413
+ console(f"📊 消息数量: {profile_data['message_count']}")
414
+ console(f"📊 变量数量: {profile_data['variable_count']}")
415
+ console(f"📊 原始大小: {profile_data['original_size_bytes'] / 1000:.2f} KB")
416
+ console(f"📊 压缩大小: {profile_data['compressed_size_bytes'] / 1000:.2f} KB")
417
+ console(f"📊 压缩率: {profile_data['compression_ratio']:.1%}")
418
+ console(f"📊 节省空间: {profile_data['space_saved_ratio']:.1%}")
419
+ console(f"📊 预估内存: {profile_data['estimated_memory_mb']:.3f} MB")
420
+
421
+ # Show optimization suggestions
422
+ if profile_data.get('optimization_suggestions'):
423
+ console("\n💡 优化建议:")
424
+ for suggestion in profile_data['optimization_suggestions']:
425
+ console(f" • {suggestion}")
426
+
427
+ console("")
428
+ console("💡 输入 'snapshot' 或 'snapshot json' 查看详细分析报告")
429
+
430
+ except Exception as e:
431
+ console(f"❌ 生成快照摘要时出错: {e}")
432
+ import traceback
433
+ traceback.print_exc()
434
+
435
+ def show_snapshot_analysis(self, format_type: str = "markdown"):
436
+ """Display the complete ContextSnapshot analysis report"""
437
+ try:
438
+ # Create Snapshot
439
+ snapshot = self.context.export_runtime_state(frame_id="debug_snapshot")
440
+
441
+ if format_type.lower() == "json":
442
+ console("\n📋 ContextSnapshot Analysis (JSON):")
443
+ console("=" * 60)
444
+ analysis_data = snapshot.profile(format='json')
445
+ import json
446
+ json_str = json.dumps(analysis_data, ensure_ascii=False, indent=2)
447
+ try:
448
+ from rich.console import Console as RichConsole
449
+ from rich.syntax import Syntax
450
+ RichConsole().print(Syntax(json_str, "json", theme="monokai", background_color="default"))
451
+ except ImportError:
452
+ console(json_str)
453
+ else:
454
+ analysis_md = snapshot.profile(
455
+ format='markdown',
456
+ title="Debug Snapshot Analysis"
457
+ )
458
+ try:
459
+ from dolphin.cli.ui.console import get_console_ui
460
+ # Use CLI's markdown rendering if available
461
+ from rich.console import Console as RichConsole
462
+ from rich.markdown import Markdown
463
+ from rich.panel import Panel
464
+ rich_console = RichConsole()
465
+ md = Markdown(analysis_md)
466
+ panel_obj = Panel(
467
+ md,
468
+ title="Debug Snapshot Analysis",
469
+ border_style="blue",
470
+ padding=(1, 2)
471
+ )
472
+ rich_console.print(panel_obj)
473
+ except ImportError:
474
+ console(analysis_md)
475
+
476
+ console("=" * 60)
477
+
478
+ except Exception as e:
479
+ console(f"❌ 生成快照分析时出错: {e}")
480
+ import traceback
481
+ traceback.print_exc()
482
+
483
+ # Backward compatibility: retain old method names
484
+ def show_snapshot_profile(self, format_type: str = "markdown"):
485
+ """[Deprecated] Please use show_snapshot_analysis() instead"""
486
+ console("💡 提示: show_snapshot_profile() 已废弃,使用 show_snapshot_analysis() 代替")
487
+ return self.show_snapshot_analysis(format_type)
488
+
489
+ def show_help(self):
490
+ """Display help information (similar to gdb/pdb)"""
491
+ console("\n🆘 调试命令帮助 (类似 gdb/pdb):")
492
+ console("=" * 70)
493
+ console("\n📌 执行控制 (仅断点暂停时有效):")
494
+ console(" step, s, n, next - 单步执行下一个 block")
495
+ console(" continue, c, cont - 继续执行直到下一个断点")
496
+ console(" run, r - 运行到结束(忽略所有断点)")
497
+ console(" until, u <n> - 运行到 block #n")
498
+ console(" quit, q, exit - 退出调试模式")
499
+ console("\n📍 断点管理:")
500
+ console(" break, b <n> - 在 block #n 设置断点")
501
+ console(" break, b - 显示所有断点")
502
+ console(" delete, d, del <n> - 删除 block #n 的断点")
503
+ console(" list, l - 显示所有断点")
504
+ console("\n🔍 变量查看:")
505
+ console(" vars, v - 显示所有变量")
506
+ console(" var <name> - 显示特定变量")
507
+ console(" progress - 显示执行进度信息")
508
+ console(" trace, t [mode] - 显示执行轨迹 (mode: brief/full, 默认为 brief)")
509
+ console("\n📊 快照分析:")
510
+ console(" snapshot, sn - 显示 ContextSnapshot 分析 (Markdown)")
511
+ console(" snapshot json - 显示 JSON 格式的 ContextSnapshot 分析")
512
+ console("\n💡 帮助:")
513
+ console(" help, h, ? - 显示此帮助")
514
+ console("\n💡 提示: 直接按回车重复上一条命令(默认为 step)")
515
+ console("\n🔥 实时调试快捷方式 (对话中可用):")
516
+ console(" /debug - 进入实时调试交互模式")
517
+ console(" /debug <cmd> - 执行单个调试命令(如 /debug vars)")
518
+ console(" /trace [mode] - 快速查看执行轨迹 (brief/full)")
519
+ console(" /snapshot - 快速查看快照分析")
520
+ console(" /vars - 快速查看所有变量")
521
+ console(" /var <name> - 快速查看特定变量")
522
+ console("=" * 70)
523
+
524
+ async def enter_live_debug(self, initial_command: str = None) -> None:
525
+ """Enter real-time debugging mode (during conversation)
526
+
527
+ Difference from post_mortem_loop:
528
+ - Real-time debugging: called during execution, can view current state
529
+ - Post-mortem: called after program ends, read-only analysis
530
+
531
+ Args:
532
+ initial_command: initial command to execute (e.g., "trace", "vars", etc.)
533
+ """
534
+ console("\n🔎 实时调试模式:查看当前执行状态")
535
+
536
+ if initial_command:
537
+ # Execute the initial command directly
538
+ parts = initial_command.split()
539
+ command = parts[0].lower()
540
+ args = parts[1:] if len(parts) > 1 else []
541
+
542
+ try:
543
+ await self.handle_debug_command(command, args, current_block_index=-1)
544
+ except DebuggerQuitException:
545
+ return
546
+ except Exception as e:
547
+ console(f"❌ 执行命令时出错: {e}")
548
+ else:
549
+ # Enter the interactive debugging loop
550
+ console("可用命令: vars, var <name>, trace, snapshot [json], help, quit")
551
+ console("💡 输入 'quit' 或 'q' 返回对话")
552
+
553
+ while True:
554
+ try:
555
+ from dolphin.cli.ui.input import prompt_debug_command
556
+ user_input = await prompt_debug_command("Debug (live) > ", allow_execution_control=False)
557
+ except (EOFError, KeyboardInterrupt):
558
+ console("\n↩️ 返回对话模式")
559
+ break
560
+
561
+ if not user_input:
562
+ continue
563
+
564
+ parts = user_input.split()
565
+ command = parts[0].lower()
566
+ args = parts[1:] if len(parts) > 1 else []
567
+
568
+ if command in ["quit", "q", "exit"]:
569
+ console("↩️ 返回对话模式")
570
+ break
571
+
572
+ # In real-time debugging, execution control commands are invalid (because not in breakpoint pause state)
573
+ if command in ["step", "s", "n", "next", "continue", "c", "cont", "run", "r", "until", "u"]:
574
+ console("⚠️ 执行控制命令仅在断点暂停时有效;当前为实时查看模式。")
575
+ continue
576
+
577
+ try:
578
+ await self.handle_debug_command(command, args, current_block_index=-1)
579
+ except DebuggerQuitException:
580
+ break
581
+ except Exception as e:
582
+ console(f"❌ 执行命令时出错: {e}")
583
+
584
+ async def post_mortem_loop(self):
585
+ """A read-only interactive debugging loop (post-mortem) after program termination."""
586
+ console("\n🔎 Post-Mortem 模式:程序已结束,仅支持查看命令。")
587
+ console("可用命令: vars, var <name>, progress, trace, snapshot [json], help, quit")
588
+
589
+ while True:
590
+ try:
591
+ from dolphin.cli.ui.input import prompt_debug_command
592
+ user_input = await prompt_debug_command("Debug (post-mortem) > ", allow_execution_control=False)
593
+ except (EOFError, KeyboardInterrupt):
594
+ console("\n🛑 退出 Post-Mortem 模式")
595
+ break
596
+
597
+ if not user_input:
598
+ # Do not execute control flow commands repeatedly when the input is empty, keep waiting
599
+ continue
600
+
601
+ parts = user_input.split()
602
+ command = parts[0].lower()
603
+ args = parts[1:] if len(parts) > 1 else []
604
+
605
+ # In post-mortem, executing control class commands is invalid
606
+ if command in [
607
+ "step",
608
+ "s",
609
+ "n",
610
+ "next",
611
+ "continue",
612
+ "c",
613
+ "cont",
614
+ "run",
615
+ "r",
616
+ "until",
617
+ "u",
618
+ ]:
619
+ console("⚠️ 程序已结束,无法继续执行;仅支持查看类命令。")
620
+ continue
621
+
622
+ if command in ["quit", "q", "exit"]:
623
+ console("🧹 退出 Post-Mortem 模式")
624
+ break
625
+
626
+ # Reuse debug command handling (ignore return value)
627
+ try:
628
+ await self.handle_debug_command(command, args, current_block_index=999999)
629
+ except Exception as e:
630
+ console(f"❌ Post-Mortem 命令执行出错: {e}")