agent.go

 1package proto
 2
 3import (
 4	"encoding/json"
 5	"errors"
 6)
 7
 8// AgentEventType represents the type of agent event.
 9type AgentEventType string
10
11const (
12	AgentEventTypeError     AgentEventType = "error"
13	AgentEventTypeResponse  AgentEventType = "response"
14	AgentEventTypeSummarize AgentEventType = "summarize"
15)
16
17// MarshalText implements the [encoding.TextMarshaler] interface.
18func (t AgentEventType) MarshalText() ([]byte, error) {
19	return []byte(t), nil
20}
21
22// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
23func (t *AgentEventType) UnmarshalText(text []byte) error {
24	*t = AgentEventType(text)
25	return nil
26}
27
28// AgentEvent represents an event emitted by the agent.
29type AgentEvent struct {
30	Type    AgentEventType `json:"type"`
31	Message Message        `json:"message"`
32	Error   error          `json:"error,omitempty"`
33
34	// RunID echoes the caller-supplied AgentMessage.RunID for the run
35	// that produced this event. It lets observers (notably
36	// `crush run`) attribute an error event to a specific request
37	// instead of to any in-flight run on the session. Empty when no
38	// caller set one.
39	RunID string `json:"run_id,omitempty"`
40
41	// When summarizing.
42	SessionID    string `json:"session_id,omitempty"`
43	SessionTitle string `json:"session_title,omitempty"`
44	Progress     string `json:"progress,omitempty"`
45	Done         bool   `json:"done,omitempty"`
46}
47
48// MarshalJSON implements the [json.Marshaler] interface.
49func (e AgentEvent) MarshalJSON() ([]byte, error) {
50	type Alias AgentEvent
51	return json.Marshal(&struct {
52		Error string `json:"error,omitempty"`
53		Alias
54	}{
55		Error: func() string {
56			if e.Error != nil {
57				return e.Error.Error()
58			}
59			return ""
60		}(),
61		Alias: Alias(e),
62	})
63}
64
65// UnmarshalJSON implements the [json.Unmarshaler] interface.
66func (e *AgentEvent) UnmarshalJSON(data []byte) error {
67	type Alias AgentEvent
68	aux := &struct {
69		Error string `json:"error,omitempty"`
70		Alias
71	}{
72		Alias: Alias(*e),
73	}
74	if err := json.Unmarshal(data, &aux); err != nil {
75		return err
76	}
77	*e = AgentEvent(aux.Alias)
78	if aux.Error != "" {
79		e.Error = errors.New(aux.Error)
80	}
81	return nil
82}