events.go

  1package server
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"fmt"
  7	"log/slog"
  8
  9	"github.com/charmbracelet/crush/internal/agent/notify"
 10	"github.com/charmbracelet/crush/internal/agent/tools/mcp"
 11	"github.com/charmbracelet/crush/internal/app"
 12	"github.com/charmbracelet/crush/internal/backend"
 13	"github.com/charmbracelet/crush/internal/history"
 14	"github.com/charmbracelet/crush/internal/message"
 15	"github.com/charmbracelet/crush/internal/permission"
 16	"github.com/charmbracelet/crush/internal/proto"
 17	"github.com/charmbracelet/crush/internal/pubsub"
 18	"github.com/charmbracelet/crush/internal/session"
 19	"github.com/charmbracelet/crush/internal/skills"
 20)
 21
 22// wrapEvent converts a raw tea.Msg (a pubsub.Event[T] from the app
 23// event fan-in) into a pubsub.Payload envelope with the correct
 24// PayloadType discriminator and a proto-typed inner payload that has
 25// proper JSON tags. Returns nil if the event type is unrecognized.
 26func wrapEvent(ev any) *pubsub.Payload {
 27	switch e := ev.(type) {
 28	case pubsub.Event[app.LSPEvent]:
 29		return envelope(pubsub.PayloadTypeLSPEvent, pubsub.Event[proto.LSPEvent]{
 30			Type: e.Type,
 31			Payload: proto.LSPEvent{
 32				Type:            proto.LSPEventType(e.Payload.Type),
 33				Name:            e.Payload.Name,
 34				State:           e.Payload.State,
 35				Error:           e.Payload.Error,
 36				DiagnosticCount: e.Payload.DiagnosticCount,
 37			},
 38		})
 39	case pubsub.Event[mcp.Event]:
 40		return envelope(pubsub.PayloadTypeMCPEvent, pubsub.Event[proto.MCPEvent]{
 41			Type: e.Type,
 42			Payload: proto.MCPEvent{
 43				Type:      mcpEventTypeToProto(e.Payload.Type),
 44				Name:      e.Payload.Name,
 45				State:     proto.MCPState(e.Payload.State),
 46				Error:     e.Payload.Error,
 47				ToolCount: e.Payload.Counts.Tools,
 48			},
 49		})
 50	case pubsub.Event[permission.PermissionRequest]:
 51		return envelope(pubsub.PayloadTypePermissionRequest, pubsub.Event[proto.PermissionRequest]{
 52			Type: e.Type,
 53			Payload: proto.PermissionRequest{
 54				ID:          e.Payload.ID,
 55				SessionID:   e.Payload.SessionID,
 56				ToolCallID:  e.Payload.ToolCallID,
 57				ToolName:    e.Payload.ToolName,
 58				Description: e.Payload.Description,
 59				Action:      e.Payload.Action,
 60				Path:        e.Payload.Path,
 61				Params:      e.Payload.Params,
 62			},
 63		})
 64	case pubsub.Event[permission.PermissionNotification]:
 65		return envelope(pubsub.PayloadTypePermissionNotification, pubsub.Event[proto.PermissionNotification]{
 66			Type: e.Type,
 67			Payload: proto.PermissionNotification{
 68				ToolCallID: e.Payload.ToolCallID,
 69				Granted:    e.Payload.Granted,
 70				Denied:     e.Payload.Denied,
 71			},
 72		})
 73	case pubsub.Event[message.Message]:
 74		return envelope(pubsub.PayloadTypeMessage, pubsub.Event[proto.Message]{
 75			Type:    e.Type,
 76			Payload: messageToProto(e.Payload),
 77		})
 78	case pubsub.Event[session.Session]:
 79		return envelope(pubsub.PayloadTypeSession, pubsub.Event[proto.Session]{
 80			Type:    e.Type,
 81			Payload: sessionToProto(e.Payload),
 82		})
 83	case pubsub.Event[history.File]:
 84		return envelope(pubsub.PayloadTypeFile, pubsub.Event[proto.File]{
 85			Type:    e.Type,
 86			Payload: fileToProto(e.Payload),
 87		})
 88	case pubsub.Event[notify.Notification]:
 89		payload := proto.AgentEvent{
 90			SessionID:    e.Payload.SessionID,
 91			SessionTitle: e.Payload.SessionTitle,
 92			Type:         proto.AgentEventType(e.Payload.Type),
 93		}
 94		if e.Payload.Type == notify.TypeAgentError {
 95			payload.Type = proto.AgentEventTypeError
 96			payload.Error = errors.New(e.Payload.Message)
 97		}
 98		return envelope(pubsub.PayloadTypeAgentEvent, pubsub.Event[proto.AgentEvent]{
 99			Type:    e.Type,
100			Payload: payload,
101		})
102	case pubsub.Event[notify.RunComplete]:
103		return envelope(pubsub.PayloadTypeRunComplete, pubsub.Event[proto.RunComplete]{
104			Type: e.Type,
105			Payload: proto.RunComplete{
106				SessionID: e.Payload.SessionID,
107				RunID:     e.Payload.RunID,
108				MessageID: e.Payload.MessageID,
109				Text:      e.Payload.Text,
110				Error:     e.Payload.Error,
111				Cancelled: e.Payload.Cancelled,
112			},
113		})
114	case pubsub.Event[proto.ConfigChanged]:
115		return envelope(pubsub.PayloadTypeConfigChanged, e)
116	case pubsub.Event[skills.Event]:
117		return envelope(pubsub.PayloadTypeSkillsEvent, pubsub.Event[proto.SkillsEvent]{
118			Type:    e.Type,
119			Payload: skillsEventToProto(e.Payload),
120		})
121	default:
122		slog.Warn("Unrecognized event type for SSE wrapping", "type", fmt.Sprintf("%T", ev))
123		return nil
124	}
125}
126
127// envelope marshals the inner event and wraps it in a pubsub.Payload.
128func envelope(payloadType pubsub.PayloadType, inner any) *pubsub.Payload {
129	raw, err := json.Marshal(inner)
130	if err != nil {
131		slog.Error("Failed to marshal event payload", "error", err)
132		return nil
133	}
134	return &pubsub.Payload{
135		Type:    payloadType,
136		Payload: raw,
137	}
138}
139
140func mcpEventTypeToProto(t mcp.EventType) proto.MCPEventType {
141	switch t {
142	case mcp.EventStateChanged:
143		return proto.MCPEventStateChanged
144	case mcp.EventToolsListChanged:
145		return proto.MCPEventToolsListChanged
146	case mcp.EventPromptsListChanged:
147		return proto.MCPEventPromptsListChanged
148	case mcp.EventResourcesListChanged:
149		return proto.MCPEventResourcesListChanged
150	default:
151		return proto.MCPEventStateChanged
152	}
153}
154
155func sessionToProto(s session.Session) proto.Session {
156	return proto.Session{
157		ID:               s.ID,
158		ParentSessionID:  s.ParentSessionID,
159		Title:            s.Title,
160		SummaryMessageID: s.SummaryMessageID,
161		MessageCount:     s.MessageCount,
162		PromptTokens:     s.PromptTokens,
163		CompletionTokens: s.CompletionTokens,
164		Cost:             s.Cost,
165		Todos:            todosToProto(s.Todos),
166		CreatedAt:        s.CreatedAt,
167		UpdatedAt:        s.UpdatedAt,
168	}
169}
170
171// isSessionBusy reports whether the given workspace has an in-flight
172// agent run for sessionID. It tolerates a nil workspace (treating it as
173// "not busy") so REST handlers can pass GetWorkspace's result through
174// unconditionally — the workspace lookup error is already surfaced by
175// the prior ListSessions/GetSession call when relevant.
176func isSessionBusy(ws *backend.Workspace, sessionID string) bool {
177	if ws == nil || ws.App == nil || ws.AgentCoordinator == nil {
178		return false
179	}
180	return ws.AgentCoordinator.IsSessionBusy(sessionID)
181}
182
183// attachedClients returns the number of clients currently viewing
184// sessionID in ws. Hold-only clients (streams == 0) do not contribute.
185// A nil workspace is treated as zero so handlers can pass GetWorkspace's
186// result through without an extra guard.
187func attachedClients(ws *backend.Workspace, sessionID string) int {
188	if ws == nil {
189		return 0
190	}
191	return ws.AttachedClientsForSession(sessionID)
192}
193
194func todosToProto(todos []session.Todo) []proto.Todo {
195	if len(todos) == 0 {
196		return nil
197	}
198	out := make([]proto.Todo, len(todos))
199	for i, t := range todos {
200		out[i] = proto.Todo{
201			Content:    t.Content,
202			Status:     string(t.Status),
203			ActiveForm: t.ActiveForm,
204		}
205	}
206	return out
207}
208
209func fileToProto(f history.File) proto.File {
210	return proto.File{
211		ID:        f.ID,
212		SessionID: f.SessionID,
213		Path:      f.Path,
214		Content:   f.Content,
215		Version:   f.Version,
216		CreatedAt: f.CreatedAt,
217		UpdatedAt: f.UpdatedAt,
218	}
219}
220
221func messageToProto(m message.Message) proto.Message {
222	msg := proto.Message{
223		ID:        m.ID,
224		SessionID: m.SessionID,
225		Role:      proto.MessageRole(m.Role),
226		Model:     m.Model,
227		Provider:  m.Provider,
228		CreatedAt: m.CreatedAt,
229		UpdatedAt: m.UpdatedAt,
230	}
231
232	for _, p := range m.Parts {
233		switch v := p.(type) {
234		case message.TextContent:
235			msg.Parts = append(msg.Parts, proto.TextContent{Text: v.Text})
236		case message.ReasoningContent:
237			msg.Parts = append(msg.Parts, proto.ReasoningContent{
238				Thinking:   v.Thinking,
239				Signature:  v.Signature,
240				StartedAt:  v.StartedAt,
241				FinishedAt: v.FinishedAt,
242			})
243		case message.ToolCall:
244			msg.Parts = append(msg.Parts, proto.ToolCall{
245				ID:       v.ID,
246				Name:     v.Name,
247				Input:    v.Input,
248				Finished: v.Finished,
249			})
250		case message.ToolResult:
251			msg.Parts = append(msg.Parts, proto.ToolResult{
252				ToolCallID: v.ToolCallID,
253				Name:       v.Name,
254				Content:    v.Content,
255				Data:       v.Data,
256				MIMEType:   v.MIMEType,
257				Metadata:   v.Metadata,
258				IsError:    v.IsError,
259			})
260		case message.Finish:
261			msg.Parts = append(msg.Parts, proto.Finish{
262				Reason:  proto.FinishReason(v.Reason),
263				Time:    v.Time,
264				Message: v.Message,
265				Details: v.Details,
266			})
267		case message.ImageURLContent:
268			msg.Parts = append(msg.Parts, proto.ImageURLContent{URL: v.URL, Detail: v.Detail})
269		case message.BinaryContent:
270			msg.Parts = append(msg.Parts, proto.BinaryContent{Path: v.Path, MIMEType: v.MIMEType, Data: v.Data})
271		}
272	}
273
274	return msg
275}
276
277// skillsEventToProto converts a skills.Event into its wire form. Errors
278// are flattened to strings because error does not round-trip over JSON.
279func skillsEventToProto(e skills.Event) proto.SkillsEvent {
280	if len(e.States) == 0 {
281		return proto.SkillsEvent{}
282	}
283	out := proto.SkillsEvent{States: make([]proto.SkillState, len(e.States))}
284	for i, s := range e.States {
285		entry := proto.SkillState{
286			Name:  s.Name,
287			Path:  s.Path,
288			State: proto.SkillDiscoveryState(s.State),
289		}
290		if s.Err != nil {
291			entry.Error = s.Err.Error()
292		}
293		out.States[i] = entry
294	}
295	return out
296}
297
298func messagesToProto(msgs []message.Message) []proto.Message {
299	out := make([]proto.Message, len(msgs))
300	for i, m := range msgs {
301		out[i] = messageToProto(m)
302	}
303	return out
304}