-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathserver.go
More file actions
332 lines (294 loc) · 9.73 KB
/
Copy pathserver.go
File metadata and controls
332 lines (294 loc) · 9.73 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package httpapi
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/url"
"sync"
"time"
"github.com/coder/agentapi/lib/logctx"
mf "github.com/coder/agentapi/lib/msgfmt"
st "github.com/coder/agentapi/lib/screentracker"
"github.com/coder/agentapi/lib/termexec"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/sse"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"golang.org/x/xerrors"
)
// Server represents the HTTP server
type Server struct {
router chi.Router
api huma.API
port int
srv *http.Server
mu sync.RWMutex
logger *slog.Logger
conversation *st.Conversation
agentio *termexec.Process
agentType mf.AgentType
emitter *EventEmitter
chatBasePath string
}
func (s *Server) GetOpenAPI() string {
jsonBytes, err := s.api.OpenAPI().MarshalJSON()
if err != nil {
return ""
}
// unmarshal the json and pretty print it
var jsonObj any
if err := json.Unmarshal(jsonBytes, &jsonObj); err != nil {
return ""
}
prettyJSON, err := json.MarshalIndent(jsonObj, "", " ")
if err != nil {
return ""
}
return string(prettyJSON)
}
// That's about 40 frames per second. It's slightly less
// because the action of taking a snapshot takes time too.
const snapshotInterval = 25 * time.Millisecond
// NewServer creates a new server instance
func NewServer(ctx context.Context, agentType mf.AgentType, process *termexec.Process, port int, chatBasePath string) *Server {
router := chi.NewMux()
corsMiddleware := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
router.Use(corsMiddleware.Handler)
humaConfig := huma.DefaultConfig("AgentAPI", "0.3.0")
humaConfig.Info.Description = "HTTP API for Claude Code, Goose, and Aider.\n\nhttps://github.com/coder/agentapi"
api := humachi.New(router, humaConfig)
formatMessage := func(message string, userInput string) string {
return mf.FormatAgentMessage(agentType, message, userInput)
}
conversation := st.NewConversation(ctx, st.ConversationConfig{
AgentIO: process,
GetTime: func() time.Time {
return time.Now()
},
SnapshotInterval: snapshotInterval,
ScreenStabilityLength: 2 * time.Second,
FormatMessage: formatMessage,
})
emitter := NewEventEmitter(1024)
s := &Server{
router: router,
api: api,
port: port,
conversation: conversation,
logger: logctx.From(ctx),
agentio: process,
agentType: agentType,
emitter: emitter,
chatBasePath: chatBasePath,
}
// Register API routes
s.registerRoutes()
return s
}
// Handler returns the underlying chi.Router for testing purposes.
func (s *Server) Handler() http.Handler {
return s.router
}
func (s *Server) StartSnapshotLoop(ctx context.Context) {
s.conversation.StartSnapshotLoop(ctx)
go func() {
for {
s.emitter.UpdateStatusAndEmitChanges(s.conversation.Status())
s.emitter.UpdateMessagesAndEmitChanges(s.conversation.Messages())
s.emitter.UpdateScreenAndEmitChanges(s.conversation.Screen())
time.Sleep(snapshotInterval)
}
}()
}
// registerRoutes sets up all API endpoints
func (s *Server) registerRoutes() {
// GET /status endpoint
huma.Get(s.api, "/status", s.getStatus, func(o *huma.Operation) {
o.Description = "Returns the current status of the agent."
})
// GET /messages endpoint
huma.Get(s.api, "/messages", s.getMessages, func(o *huma.Operation) {
o.Description = "Returns a list of messages representing the conversation history with the agent."
})
// POST /message endpoint
huma.Post(s.api, "/message", s.createMessage, func(o *huma.Operation) {
o.Description = "Send a message to the agent. For messages of type 'user', the agent's status must be 'stable' for the operation to complete successfully. Otherwise, this endpoint will return an error."
})
// GET /events endpoint
sse.Register(s.api, huma.Operation{
OperationID: "subscribeEvents",
Method: http.MethodGet,
Path: "/events",
Summary: "Subscribe to events",
Description: "The events are sent as Server-Sent Events (SSE). Initially, the endpoint returns a list of events needed to reconstruct the current state of the conversation and the agent's status. After that, it only returns events that have occurred since the last event was sent.\n\nNote: When an agent is running, the last message in the conversation history is updated frequently, and the endpoint sends a new message update event each time.",
}, map[string]any{
// Mapping of event type name to Go struct for that event.
"message_update": MessageUpdateBody{},
"status_change": StatusChangeBody{},
}, s.subscribeEvents)
sse.Register(s.api, huma.Operation{
OperationID: "subscribeScreen",
Method: http.MethodGet,
Path: "/internal/screen",
Summary: "Subscribe to screen",
Hidden: true,
}, map[string]any{
"screen": ScreenUpdateBody{},
}, s.subscribeScreen)
s.router.Handle("/", http.HandlerFunc(s.redirectToChat))
// Serve static files for the chat interface under /chat
s.registerStaticFileRoutes()
}
// getStatus handles GET /status
func (s *Server) getStatus(ctx context.Context, input *struct{}) (*StatusResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
status := s.conversation.Status()
agentStatus := convertStatus(status)
resp := &StatusResponse{}
resp.Body.Status = agentStatus
return resp, nil
}
// getMessages handles GET /messages
func (s *Server) getMessages(ctx context.Context, input *struct{}) (*MessagesResponse, error) {
s.mu.RLock()
defer s.mu.RUnlock()
resp := &MessagesResponse{}
resp.Body.Messages = make([]Message, len(s.conversation.Messages()))
for i, msg := range s.conversation.Messages() {
resp.Body.Messages[i] = Message{
Id: msg.Id,
Role: msg.Role,
Content: msg.Message,
Time: msg.Time,
}
}
return resp, nil
}
// createMessage handles POST /message
func (s *Server) createMessage(ctx context.Context, input *MessageRequest) (*MessageResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
switch input.Body.Type {
case MessageTypeUser:
if err := s.conversation.SendMessage(FormatMessage(s.agentType, input.Body.Content)...); err != nil {
return nil, xerrors.Errorf("failed to send message: %w", err)
}
case MessageTypeRaw:
if _, err := s.agentio.Write([]byte(input.Body.Content)); err != nil {
return nil, xerrors.Errorf("failed to send message: %w", err)
}
}
resp := &MessageResponse{}
resp.Body.Ok = true
return resp, nil
}
// subscribeEvents is an SSE endpoint that sends events to the client
func (s *Server) subscribeEvents(ctx context.Context, input *struct{}, send sse.Sender) {
subscriberId, ch, stateEvents := s.emitter.Subscribe()
defer s.emitter.Unsubscribe(subscriberId)
s.logger.Info("New subscriber", "subscriberId", subscriberId)
for _, event := range stateEvents {
if event.Type == EventTypeScreenUpdate {
continue
}
if err := send.Data(event.Payload); err != nil {
s.logger.Error("Failed to send event", "subscriberId", subscriberId, "error", err)
return
}
}
for {
select {
case event, ok := <-ch:
if !ok {
s.logger.Info("Channel closed", "subscriberId", subscriberId)
return
}
if event.Type == EventTypeScreenUpdate {
continue
}
if err := send.Data(event.Payload); err != nil {
s.logger.Error("Failed to send event", "subscriberId", subscriberId, "error", err)
return
}
case <-ctx.Done():
s.logger.Info("Context done", "subscriberId", subscriberId)
return
}
}
}
func (s *Server) subscribeScreen(ctx context.Context, input *struct{}, send sse.Sender) {
subscriberId, ch, stateEvents := s.emitter.Subscribe()
defer s.emitter.Unsubscribe(subscriberId)
s.logger.Info("New screen subscriber", "subscriberId", subscriberId)
for _, event := range stateEvents {
if event.Type != EventTypeScreenUpdate {
continue
}
if err := send.Data(event.Payload); err != nil {
s.logger.Error("Failed to send screen event", "subscriberId", subscriberId, "error", err)
return
}
}
for {
select {
case event, ok := <-ch:
if !ok {
s.logger.Info("Screen channel closed", "subscriberId", subscriberId)
return
}
if event.Type != EventTypeScreenUpdate {
continue
}
if err := send.Data(event.Payload); err != nil {
s.logger.Error("Failed to send screen event", "subscriberId", subscriberId, "error", err)
return
}
case <-ctx.Done():
s.logger.Info("Screen context done", "subscriberId", subscriberId)
return
}
}
}
// Start starts the HTTP server
func (s *Server) Start() error {
addr := fmt.Sprintf(":%d", s.port)
s.srv = &http.Server{
Addr: addr,
Handler: s.router,
}
return s.srv.ListenAndServe()
}
// Stop gracefully stops the HTTP server
func (s *Server) Stop(ctx context.Context) error {
if s.srv != nil {
return s.srv.Shutdown(ctx)
}
return nil
}
// registerStaticFileRoutes sets up routes for serving static files
func (s *Server) registerStaticFileRoutes() {
chatHandler := FileServerWithIndexFallback(s.chatBasePath)
// Mount the file server at /chat
s.router.Handle("/chat", http.StripPrefix("/chat", chatHandler))
s.router.Handle("/chat/*", http.StripPrefix("/chat", chatHandler))
}
func (s *Server) redirectToChat(w http.ResponseWriter, r *http.Request) {
rdir, err := url.JoinPath(s.chatBasePath, "embed")
if err != nil {
s.logger.Error("Failed to construct redirect URL", "error", err)
http.Error(w, "Failed to redirect", http.StatusInternalServerError)
return
}
http.Redirect(w, r, rdir, http.StatusTemporaryRedirect)
}