event.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package event
  2. import (
  3. "strconv"
  4. "time"
  5. )
  6. type SSEEvent struct {
  7. Type string `json:"type"`
  8. Properties map[string]interface{} `json:"properties"`
  9. }
  10. type ParsedEvent struct {
  11. Timestamp string
  12. Port int
  13. Message string
  14. }
  15. func ParseStatus(status map[string]interface{}) string {
  16. if status == nil {
  17. return "未知"
  18. }
  19. t, _ := status["type"].(string)
  20. switch t {
  21. case "idle":
  22. return "空闲"
  23. case "busy":
  24. return "忙碌"
  25. case "retry":
  26. return "重试中"
  27. default:
  28. return t
  29. }
  30. }
  31. func ParseToolState(state map[string]interface{}) string {
  32. if state == nil {
  33. return ""
  34. }
  35. s, _ := state["status"].(string)
  36. title, _ := state["title"].(string)
  37. switch s {
  38. case "running":
  39. if title != "" {
  40. return "运行中: " + title
  41. }
  42. return "运行中"
  43. case "completed":
  44. if title != "" {
  45. return "完成: " + title
  46. }
  47. return "完成"
  48. case "error":
  49. return "错误"
  50. default:
  51. return s
  52. }
  53. }
  54. func FormatEvent(port int, evt *SSEEvent) string {
  55. ts := time.Now().Format("15:04:05")
  56. prefix := "[" + ts + "] [:" + strconv.Itoa(port) + "]"
  57. switch evt.Type {
  58. case "session.status":
  59. if status, ok := evt.Properties["status"].(map[string]interface{}); ok {
  60. return prefix + " 状态: " + ParseStatus(status)
  61. }
  62. case "session.idle":
  63. return prefix + " 状态: 空闲"
  64. case "message.part.updated":
  65. if part, ok := evt.Properties["part"].(map[string]interface{}); ok {
  66. pt, _ := part["type"].(string)
  67. switch pt {
  68. case "tool":
  69. tool, _ := part["tool"].(string)
  70. state := ParseToolState(part["state"].(map[string]interface{}))
  71. return prefix + " 工具: " + tool + " - " + state
  72. case "reasoning":
  73. return prefix + " 思考中..."
  74. }
  75. }
  76. case "permission.updated":
  77. if title, ok := evt.Properties["title"].(string); ok {
  78. return prefix + " 权限请求: " + title
  79. }
  80. case "session.error":
  81. return prefix + " 错误"
  82. }
  83. return ""
  84. }