event.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. case "pending":
  28. return "修改中"
  29. default:
  30. return t
  31. }
  32. }
  33. func ParseToolState(state map[string]interface{}) string {
  34. if state == nil {
  35. return ""
  36. }
  37. s, _ := state["status"].(string)
  38. title, _ := state["title"].(string)
  39. switch s {
  40. case "pending":
  41. return "等待中"
  42. case "running":
  43. if title != "" {
  44. return "运行中: " + title
  45. }
  46. return "运行中"
  47. case "completed":
  48. if title != "" {
  49. return "工具执行完成: " + title
  50. }
  51. return "工具执行完成"
  52. case "error":
  53. return "错误"
  54. default:
  55. return s
  56. }
  57. }
  58. func FormatEvent(port int, evt *SSEEvent) string {
  59. ts := time.Now().Format("15:04:05")
  60. prefix := "[" + ts + "] [:" + strconv.Itoa(port) + "]"
  61. switch evt.Type {
  62. case "session.status":
  63. if status, ok := evt.Properties["status"].(map[string]interface{}); ok {
  64. return prefix + " 状态: " + ParseStatus(status)
  65. }
  66. case "session.idle":
  67. return prefix + " 状态: 空闲"
  68. case "message.part.updated":
  69. if part, ok := evt.Properties["part"].(map[string]interface{}); ok {
  70. pt, _ := part["type"].(string)
  71. switch pt {
  72. case "tool":
  73. tool, _ := part["tool"].(string)
  74. state := ParseToolState(part["state"].(map[string]interface{}))
  75. return prefix + " 工具: " + tool + " - " + state
  76. case "reasoning":
  77. return prefix + " 思考中..."
  78. }
  79. }
  80. case "permission.updated":
  81. if title, ok := evt.Properties["title"].(string); ok {
  82. return prefix + " 权限请求: " + title
  83. }
  84. case "session.error":
  85. return prefix + " 错误"
  86. }
  87. return ""
  88. }