-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathevents.go
More file actions
294 lines (249 loc) · 7.61 KB
/
events.go
File metadata and controls
294 lines (249 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package httpapi
import (
"fmt"
"strings"
"sync"
"time"
"github.com/coder/quartz"
mf "github.com/coder/agentapi/lib/msgfmt"
st "github.com/coder/agentapi/lib/screentracker"
"github.com/coder/agentapi/lib/util"
"github.com/danielgtaylor/huma/v2"
)
type EventType string
const (
EventTypeMessageUpdate EventType = "message_update"
EventTypeStatusChange EventType = "status_change"
EventTypeScreenUpdate EventType = "screen_update"
EventTypeError EventType = "agent_error"
)
type AgentStatus string
const (
AgentStatusRunning AgentStatus = "running"
AgentStatusStable AgentStatus = "stable"
)
var AgentStatusValues = []AgentStatus{
AgentStatusStable,
AgentStatusRunning,
}
func (a AgentStatus) Schema(r huma.Registry) *huma.Schema {
return util.OpenAPISchema(r, "AgentStatus", AgentStatusValues)
}
type MessageUpdateBody struct {
Id int `json:"id" doc:"Unique identifier for the message. This identifier also represents the order of the message in the conversation history."`
Role st.ConversationRole `json:"role" doc:"Role of the message author"`
Message string `json:"message" doc:"Message content. The message is formatted as it appears in the agent's terminal session, meaning that, by default, it consists of lines of text with 80 characters per line."`
Time time.Time `json:"time" doc:"Timestamp of the message"`
}
type StatusChangeBody struct {
Status AgentStatus `json:"status" doc:"Agent status"`
AgentType mf.AgentType `json:"agent_type" doc:"Type of the agent being used by the server."`
}
type ScreenUpdateBody struct {
Screen string `json:"screen"`
}
type ErrorBody struct {
Message string `json:"message" doc:"Error message"`
Level st.ErrorLevel `json:"level" doc:"Error level"`
Time time.Time `json:"time" doc:"Timestamp when the error occurred"`
}
type Event struct {
Type EventType
Payload any
}
type EventEmitter struct {
mu sync.Mutex
messages []st.ConversationMessage
status AgentStatus
agentType mf.AgentType
chans map[int]chan Event
chanIdx int
subscriptionBufSize uint
screen string
errors []ErrorBody
clock quartz.Clock
}
func convertStatus(status st.ConversationStatus) AgentStatus {
switch status {
case st.ConversationStatusInitializing:
return AgentStatusRunning
case st.ConversationStatusStable:
return AgentStatusStable
case st.ConversationStatusChanging:
return AgentStatusRunning
default:
panic(fmt.Sprintf("unknown conversation status: %s", status))
}
}
const defaultSubscriptionBufSize uint = 1024
// maxStoredErrors caps the number of errors retained for late subscribers.
const maxStoredErrors = 100
type EventEmitterOption func(*EventEmitter)
func WithSubscriptionBufSize(size uint) EventEmitterOption {
return func(e *EventEmitter) {
if size == 0 {
e.subscriptionBufSize = defaultSubscriptionBufSize
} else {
e.subscriptionBufSize = size
}
}
}
func WithAgentType(agentType mf.AgentType) EventEmitterOption {
return func(e *EventEmitter) {
e.agentType = agentType
}
}
func WithClock(clock quartz.Clock) EventEmitterOption {
return func(e *EventEmitter) {
e.clock = clock
}
}
func NewEventEmitter(opts ...EventEmitterOption) *EventEmitter {
e := &EventEmitter{
messages: make([]st.ConversationMessage, 0),
status: AgentStatusRunning,
chans: make(map[int]chan Event),
subscriptionBufSize: defaultSubscriptionBufSize,
}
for _, opt := range opts {
opt(e)
}
if e.clock == nil {
e.clock = quartz.NewReal()
}
return e
}
// Assumes the caller holds the lock.
func (e *EventEmitter) notifyChannels(eventType EventType, payload any) {
chanIds := make([]int, 0, len(e.chans))
for chanId := range e.chans {
chanIds = append(chanIds, chanId)
}
for _, chanId := range chanIds {
ch := e.chans[chanId]
event := Event{
Type: eventType,
Payload: payload,
}
select {
case ch <- event:
default:
// If the channel is full, close it.
// Listeners must actively drain the channel.
e.unsubscribeInner(chanId)
}
}
}
// EmitMessages assumes that only the last message can change or new messages can be added.
// If a new message is injected between existing messages (identified by Id), the behavior is undefined.
func (e *EventEmitter) EmitMessages(newMessages []st.ConversationMessage) {
e.mu.Lock()
defer e.mu.Unlock()
maxLength := max(len(e.messages), len(newMessages))
for i := range maxLength {
var oldMsg st.ConversationMessage
var newMsg st.ConversationMessage
if i < len(e.messages) {
oldMsg = e.messages[i]
}
if i < len(newMessages) {
newMsg = newMessages[i]
}
if oldMsg != newMsg {
if i >= len(newMessages) {
continue
}
e.notifyChannels(EventTypeMessageUpdate, MessageUpdateBody{
Id: newMessages[i].Id,
Role: newMessages[i].Role,
Message: newMessages[i].Message,
Time: newMessages[i].Time,
})
}
}
e.messages = newMessages
}
func (e *EventEmitter) EmitStatus(newStatus st.ConversationStatus) {
e.mu.Lock()
defer e.mu.Unlock()
newAgentStatus := convertStatus(newStatus)
if e.status == newAgentStatus {
return
}
e.notifyChannels(EventTypeStatusChange, StatusChangeBody{Status: newAgentStatus, AgentType: e.agentType})
e.status = newAgentStatus
}
func (e *EventEmitter) EmitScreen(newScreen string) {
e.mu.Lock()
defer e.mu.Unlock()
if e.screen == newScreen {
return
}
e.notifyChannels(EventTypeScreenUpdate, ScreenUpdateBody{Screen: strings.TrimRight(newScreen, mf.WhiteSpaceChars)})
e.screen = newScreen
}
func (e *EventEmitter) EmitError(message string, level st.ErrorLevel) {
e.mu.Lock()
defer e.mu.Unlock()
errorBody := ErrorBody{
Message: message,
Level: level,
Time: e.clock.Now(),
}
// Store the error so new subscribers can receive recent errors.
e.errors = append(e.errors, errorBody)
if len(e.errors) > maxStoredErrors {
e.errors = e.errors[len(e.errors)-maxStoredErrors:]
}
e.notifyChannels(EventTypeError, errorBody)
}
// Assumes the caller holds the lock.
func (e *EventEmitter) currentStateAsEvents() []Event {
events := make([]Event, 0, len(e.messages)+2)
for _, msg := range e.messages {
events = append(events, Event{
Type: EventTypeMessageUpdate,
Payload: MessageUpdateBody{Id: msg.Id, Role: msg.Role, Message: msg.Message, Time: msg.Time},
})
}
events = append(events, Event{
Type: EventTypeStatusChange,
Payload: StatusChangeBody{Status: e.status, AgentType: e.agentType},
})
events = append(events, Event{
Type: EventTypeScreenUpdate,
Payload: ScreenUpdateBody{Screen: strings.TrimRight(e.screen, mf.WhiteSpaceChars)},
})
// Include all error events
for _, err := range e.errors {
events = append(events, Event{
Type: EventTypeError,
Payload: err,
})
}
return events
}
// Subscribe returns:
// - a subscription ID that can be used to unsubscribe.
// - a channel for receiving events.
// - a list of events that allow to recreate the state of the conversation right before the subscription was created.
func (e *EventEmitter) Subscribe() (int, <-chan Event, []Event) {
e.mu.Lock()
defer e.mu.Unlock()
stateEvents := e.currentStateAsEvents()
// Once a channel becomes full, it will be closed.
ch := make(chan Event, e.subscriptionBufSize)
e.chans[e.chanIdx] = ch
e.chanIdx++
return e.chanIdx - 1, ch, stateEvents
}
// Assumes the caller holds the lock.
func (e *EventEmitter) unsubscribeInner(chanId int) {
close(e.chans[chanId])
delete(e.chans, chanId)
}
func (e *EventEmitter) Unsubscribe(chanId int) {
e.mu.Lock()
defer e.mu.Unlock()
e.unsubscribeInner(chanId)
}