1package client
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "log/slog"
12 "net/http"
13 "net/url"
14 "time"
15
16 "github.com/charmbracelet/crush/internal/config"
17 "github.com/charmbracelet/crush/internal/message"
18 "github.com/charmbracelet/crush/internal/proto"
19 "github.com/charmbracelet/crush/internal/pubsub"
20 "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
21)
22
23// ListWorkspaces retrieves all workspaces from the server.
24func (c *Client) ListWorkspaces(ctx context.Context) ([]proto.Workspace, error) {
25 rsp, err := c.get(ctx, "/workspaces", nil, nil)
26 if err != nil {
27 return nil, fmt.Errorf("failed to list workspaces: %w", err)
28 }
29 defer rsp.Body.Close()
30 if rsp.StatusCode != http.StatusOK {
31 return nil, fmt.Errorf("failed to list workspaces: status code %d", rsp.StatusCode)
32 }
33 var workspaces []proto.Workspace
34 if err := json.NewDecoder(rsp.Body).Decode(&workspaces); err != nil {
35 return nil, fmt.Errorf("failed to decode workspaces: %w", err)
36 }
37 return workspaces, nil
38}
39
40// CreateWorkspace creates a new workspace on the server.
41func (c *Client) CreateWorkspace(ctx context.Context, ws proto.Workspace) (*proto.Workspace, error) {
42 rsp, err := c.post(ctx, "/workspaces", nil, jsonBody(ws), http.Header{"Content-Type": []string{"application/json"}})
43 if err != nil {
44 return nil, fmt.Errorf("failed to create workspace: %w", err)
45 }
46 defer rsp.Body.Close()
47 if rsp.StatusCode != http.StatusOK {
48 return nil, fmt.Errorf("failed to create workspace: status code %d", rsp.StatusCode)
49 }
50 var created proto.Workspace
51 if err := json.NewDecoder(rsp.Body).Decode(&created); err != nil {
52 return nil, fmt.Errorf("failed to decode workspace: %w", err)
53 }
54 return &created, nil
55}
56
57// GetWorkspace retrieves a workspace from the server.
58func (c *Client) GetWorkspace(ctx context.Context, id string) (*proto.Workspace, error) {
59 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s", id), nil, nil)
60 if err != nil {
61 return nil, fmt.Errorf("failed to get workspace: %w", err)
62 }
63 defer rsp.Body.Close()
64 if rsp.StatusCode != http.StatusOK {
65 return nil, fmt.Errorf("failed to get workspace: status code %d", rsp.StatusCode)
66 }
67 var ws proto.Workspace
68 if err := json.NewDecoder(rsp.Body).Decode(&ws); err != nil {
69 return nil, fmt.Errorf("failed to decode workspace: %w", err)
70 }
71 return &ws, nil
72}
73
74// DeleteWorkspace deletes a workspace on the server.
75func (c *Client) DeleteWorkspace(ctx context.Context, id string) error {
76 rsp, err := c.delete(ctx, fmt.Sprintf("/workspaces/%s", id), nil, nil)
77 if err != nil {
78 return fmt.Errorf("failed to delete workspace: %w", err)
79 }
80 defer rsp.Body.Close()
81 if rsp.StatusCode != http.StatusOK {
82 return fmt.Errorf("failed to delete workspace: status code %d", rsp.StatusCode)
83 }
84 return nil
85}
86
87// SubscribeEvents subscribes to server-sent events for a workspace.
88func (c *Client) SubscribeEvents(ctx context.Context, id string) (<-chan any, error) {
89 events := make(chan any, 100)
90 //nolint:bodyclose
91 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/events", id), nil, http.Header{
92 "Accept": []string{"text/event-stream"},
93 "Cache-Control": []string{"no-cache"},
94 "Connection": []string{"keep-alive"},
95 })
96 if err != nil {
97 return nil, fmt.Errorf("failed to subscribe to events: %w", err)
98 }
99
100 if rsp.StatusCode != http.StatusOK {
101 rsp.Body.Close()
102 return nil, fmt.Errorf("failed to subscribe to events: status code %d", rsp.StatusCode)
103 }
104
105 go func() {
106 defer rsp.Body.Close()
107
108 scr := bufio.NewReader(rsp.Body)
109 for {
110 line, err := scr.ReadBytes('\n')
111 if errors.Is(err, io.EOF) {
112 break
113 }
114 if err != nil {
115 slog.Error("Reading from events stream", "error", err)
116 time.Sleep(time.Second * 2)
117 continue
118 }
119 line = bytes.TrimSpace(line)
120 if len(line) == 0 {
121 continue
122 }
123
124 data, ok := bytes.CutPrefix(line, []byte("data:"))
125 if !ok {
126 slog.Warn("Invalid event format", "line", string(line))
127 continue
128 }
129
130 data = bytes.TrimSpace(data)
131
132 var p pubsub.Payload
133 if err := json.Unmarshal(data, &p); err != nil {
134 slog.Error("Unmarshaling event envelope", "error", err)
135 continue
136 }
137
138 switch p.Type {
139 case pubsub.PayloadTypeLSPEvent:
140 var e pubsub.Event[proto.LSPEvent]
141 _ = json.Unmarshal(p.Payload, &e)
142 sendEvent(ctx, events, e)
143 case pubsub.PayloadTypeMCPEvent:
144 var e pubsub.Event[proto.MCPEvent]
145 _ = json.Unmarshal(p.Payload, &e)
146 sendEvent(ctx, events, e)
147 case pubsub.PayloadTypePermissionRequest:
148 var e pubsub.Event[proto.PermissionRequest]
149 _ = json.Unmarshal(p.Payload, &e)
150 sendEvent(ctx, events, e)
151 case pubsub.PayloadTypePermissionNotification:
152 var e pubsub.Event[proto.PermissionNotification]
153 _ = json.Unmarshal(p.Payload, &e)
154 sendEvent(ctx, events, e)
155 case pubsub.PayloadTypeMessage:
156 var e pubsub.Event[proto.Message]
157 _ = json.Unmarshal(p.Payload, &e)
158 sendEvent(ctx, events, e)
159 case pubsub.PayloadTypeSession:
160 var e pubsub.Event[proto.Session]
161 _ = json.Unmarshal(p.Payload, &e)
162 sendEvent(ctx, events, e)
163 case pubsub.PayloadTypeFile:
164 var e pubsub.Event[proto.File]
165 _ = json.Unmarshal(p.Payload, &e)
166 sendEvent(ctx, events, e)
167 case pubsub.PayloadTypeAgentEvent:
168 var e pubsub.Event[proto.AgentEvent]
169 _ = json.Unmarshal(p.Payload, &e)
170 sendEvent(ctx, events, e)
171 default:
172 slog.Warn("Unknown event type", "type", p.Type)
173 continue
174 }
175 }
176 }()
177
178 return events, nil
179}
180
181func sendEvent(ctx context.Context, evc chan any, ev any) {
182 select {
183 case evc <- ev:
184 case <-ctx.Done():
185 close(evc)
186 return
187 }
188}
189
190// GetLSPDiagnostics retrieves LSP diagnostics for a specific LSP client.
191func (c *Client) GetLSPDiagnostics(ctx context.Context, id string, lspName string) (map[protocol.DocumentURI][]protocol.Diagnostic, error) {
192 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/lsps/%s/diagnostics", id, lspName), nil, nil)
193 if err != nil {
194 return nil, fmt.Errorf("failed to get LSP diagnostics: %w", err)
195 }
196 defer rsp.Body.Close()
197 if rsp.StatusCode != http.StatusOK {
198 return nil, fmt.Errorf("failed to get LSP diagnostics: status code %d", rsp.StatusCode)
199 }
200 var diagnostics map[protocol.DocumentURI][]protocol.Diagnostic
201 if err := json.NewDecoder(rsp.Body).Decode(&diagnostics); err != nil {
202 return nil, fmt.Errorf("failed to decode LSP diagnostics: %w", err)
203 }
204 return diagnostics, nil
205}
206
207// GetLSPs retrieves the LSP client states for a workspace.
208func (c *Client) GetLSPs(ctx context.Context, id string) (map[string]proto.LSPClientInfo, error) {
209 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/lsps", id), nil, nil)
210 if err != nil {
211 return nil, fmt.Errorf("failed to get LSPs: %w", err)
212 }
213 defer rsp.Body.Close()
214 if rsp.StatusCode != http.StatusOK {
215 return nil, fmt.Errorf("failed to get LSPs: status code %d", rsp.StatusCode)
216 }
217 var lsps map[string]proto.LSPClientInfo
218 if err := json.NewDecoder(rsp.Body).Decode(&lsps); err != nil {
219 return nil, fmt.Errorf("failed to decode LSPs: %w", err)
220 }
221 return lsps, nil
222}
223
224// MCPGetStates retrieves the MCP client states for a workspace.
225func (c *Client) MCPGetStates(ctx context.Context, id string) (map[string]proto.MCPClientInfo, error) {
226 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/mcp/states", id), nil, nil)
227 if err != nil {
228 return nil, fmt.Errorf("failed to get MCP states: %w", err)
229 }
230 defer rsp.Body.Close()
231 if rsp.StatusCode != http.StatusOK {
232 return nil, fmt.Errorf("failed to get MCP states: status code %d", rsp.StatusCode)
233 }
234 var states map[string]proto.MCPClientInfo
235 if err := json.NewDecoder(rsp.Body).Decode(&states); err != nil {
236 return nil, fmt.Errorf("failed to decode MCP states: %w", err)
237 }
238 return states, nil
239}
240
241// MCPRefreshPrompts refreshes prompts for a named MCP client.
242func (c *Client) MCPRefreshPrompts(ctx context.Context, id, name string) error {
243 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/mcp/refresh-prompts", id), nil,
244 jsonBody(struct {
245 Name string `json:"name"`
246 }{Name: name}),
247 http.Header{"Content-Type": []string{"application/json"}})
248 if err != nil {
249 return fmt.Errorf("failed to refresh MCP prompts: %w", err)
250 }
251 defer rsp.Body.Close()
252 if rsp.StatusCode != http.StatusOK {
253 return fmt.Errorf("failed to refresh MCP prompts: status code %d", rsp.StatusCode)
254 }
255 return nil
256}
257
258// MCPRefreshResources refreshes resources for a named MCP client.
259func (c *Client) MCPRefreshResources(ctx context.Context, id, name string) error {
260 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/mcp/refresh-resources", id), nil,
261 jsonBody(struct {
262 Name string `json:"name"`
263 }{Name: name}),
264 http.Header{"Content-Type": []string{"application/json"}})
265 if err != nil {
266 return fmt.Errorf("failed to refresh MCP resources: %w", err)
267 }
268 defer rsp.Body.Close()
269 if rsp.StatusCode != http.StatusOK {
270 return fmt.Errorf("failed to refresh MCP resources: status code %d", rsp.StatusCode)
271 }
272 return nil
273}
274
275// GetAgentSessionQueuedPrompts retrieves the number of queued prompts for a
276// session.
277func (c *Client) GetAgentSessionQueuedPrompts(ctx context.Context, id string, sessionID string) (int, error) {
278 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s/prompts/queued", id, sessionID), nil, nil)
279 if err != nil {
280 return 0, fmt.Errorf("failed to get session agent queued prompts: %w", err)
281 }
282 defer rsp.Body.Close()
283 if rsp.StatusCode != http.StatusOK {
284 return 0, fmt.Errorf("failed to get session agent queued prompts: status code %d", rsp.StatusCode)
285 }
286 var count int
287 if err := json.NewDecoder(rsp.Body).Decode(&count); err != nil {
288 return 0, fmt.Errorf("failed to decode session agent queued prompts: %w", err)
289 }
290 return count, nil
291}
292
293// ClearAgentSessionQueuedPrompts clears the queued prompts for a session.
294func (c *Client) ClearAgentSessionQueuedPrompts(ctx context.Context, id string, sessionID string) error {
295 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s/prompts/clear", id, sessionID), nil, nil, nil)
296 if err != nil {
297 return fmt.Errorf("failed to clear session agent queued prompts: %w", err)
298 }
299 defer rsp.Body.Close()
300 if rsp.StatusCode != http.StatusOK {
301 return fmt.Errorf("failed to clear session agent queued prompts: status code %d", rsp.StatusCode)
302 }
303 return nil
304}
305
306// GetAgentInfo retrieves the agent status for a workspace.
307func (c *Client) GetAgentInfo(ctx context.Context, id string) (*proto.AgentInfo, error) {
308 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/agent", id), nil, nil)
309 if err != nil {
310 return nil, fmt.Errorf("failed to get agent status: %w", err)
311 }
312 defer rsp.Body.Close()
313 if rsp.StatusCode != http.StatusOK {
314 return nil, fmt.Errorf("failed to get agent status: status code %d", rsp.StatusCode)
315 }
316 var info proto.AgentInfo
317 if err := json.NewDecoder(rsp.Body).Decode(&info); err != nil {
318 return nil, fmt.Errorf("failed to decode agent status: %w", err)
319 }
320 return &info, nil
321}
322
323// UpdateAgent triggers an agent model update on the server.
324func (c *Client) UpdateAgent(ctx context.Context, id string) error {
325 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent/update", id), nil, nil, nil)
326 if err != nil {
327 return fmt.Errorf("failed to update agent: %w", err)
328 }
329 defer rsp.Body.Close()
330 if rsp.StatusCode != http.StatusOK {
331 return fmt.Errorf("failed to update agent: status code %d", rsp.StatusCode)
332 }
333 return nil
334}
335
336// SendMessage sends a message to the agent for a workspace.
337func (c *Client) SendMessage(ctx context.Context, id string, sessionID, prompt string, attachments ...message.Attachment) error {
338 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent", id), nil, jsonBody(proto.AgentMessage{
339 SessionID: sessionID,
340 Prompt: prompt,
341 Attachments: proto.AttachmentsFromMessage(attachments),
342 }), http.Header{"Content-Type": []string{"application/json"}})
343 if err != nil {
344 return fmt.Errorf("failed to send message to agent: %w", err)
345 }
346 defer rsp.Body.Close()
347 if rsp.StatusCode != http.StatusOK {
348 return fmt.Errorf("failed to send message to agent: status code %d", rsp.StatusCode)
349 }
350 return nil
351}
352
353// GetAgentSessionInfo retrieves the agent session info for a workspace.
354func (c *Client) GetAgentSessionInfo(ctx context.Context, id string, sessionID string) (*proto.AgentSession, error) {
355 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s", id, sessionID), nil, nil)
356 if err != nil {
357 return nil, fmt.Errorf("failed to get session agent info: %w", err)
358 }
359 defer rsp.Body.Close()
360 if rsp.StatusCode != http.StatusOK {
361 return nil, fmt.Errorf("failed to get session agent info: status code %d", rsp.StatusCode)
362 }
363 var info proto.AgentSession
364 if err := json.NewDecoder(rsp.Body).Decode(&info); err != nil {
365 return nil, fmt.Errorf("failed to decode session agent info: %w", err)
366 }
367 return &info, nil
368}
369
370// AgentSummarizeSession requests a session summarization.
371func (c *Client) AgentSummarizeSession(ctx context.Context, id string, sessionID string) error {
372 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s/summarize", id, sessionID), nil, nil, nil)
373 if err != nil {
374 return fmt.Errorf("failed to summarize session: %w", err)
375 }
376 defer rsp.Body.Close()
377 if rsp.StatusCode != http.StatusOK {
378 return fmt.Errorf("failed to summarize session: status code %d", rsp.StatusCode)
379 }
380 return nil
381}
382
383// InitiateAgentProcessing triggers agent initialization on the server.
384func (c *Client) InitiateAgentProcessing(ctx context.Context, id string) error {
385 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent/init", id), nil, nil, nil)
386 if err != nil {
387 return fmt.Errorf("failed to initiate session agent processing: %w", err)
388 }
389 defer rsp.Body.Close()
390 if rsp.StatusCode != http.StatusOK {
391 return fmt.Errorf("failed to initiate session agent processing: status code %d", rsp.StatusCode)
392 }
393 return nil
394}
395
396// ListMessages retrieves all messages for a session as proto types.
397func (c *Client) ListMessages(ctx context.Context, id string, sessionID string) ([]proto.Message, error) {
398 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s/messages", id, sessionID), nil, nil)
399 if err != nil {
400 return nil, fmt.Errorf("failed to get messages: %w", err)
401 }
402 defer rsp.Body.Close()
403 if rsp.StatusCode != http.StatusOK {
404 return nil, fmt.Errorf("failed to get messages: status code %d", rsp.StatusCode)
405 }
406 var msgs []proto.Message
407 if err := json.NewDecoder(rsp.Body).Decode(&msgs); err != nil && !errors.Is(err, io.EOF) {
408 return nil, fmt.Errorf("failed to decode messages: %w", err)
409 }
410 return msgs, nil
411}
412
413// GetSession retrieves a specific session as a proto type.
414func (c *Client) GetSession(ctx context.Context, id string, sessionID string) (*proto.Session, error) {
415 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s", id, sessionID), nil, nil)
416 if err != nil {
417 return nil, fmt.Errorf("failed to get session: %w", err)
418 }
419 defer rsp.Body.Close()
420 if rsp.StatusCode != http.StatusOK {
421 return nil, fmt.Errorf("failed to get session: status code %d", rsp.StatusCode)
422 }
423 var sess proto.Session
424 if err := json.NewDecoder(rsp.Body).Decode(&sess); err != nil {
425 return nil, fmt.Errorf("failed to decode session: %w", err)
426 }
427 return &sess, nil
428}
429
430// ListSessionHistoryFiles retrieves history files for a session as proto types.
431func (c *Client) ListSessionHistoryFiles(ctx context.Context, id string, sessionID string) ([]proto.File, error) {
432 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s/history", id, sessionID), nil, nil)
433 if err != nil {
434 return nil, fmt.Errorf("failed to get session history files: %w", err)
435 }
436 defer rsp.Body.Close()
437 if rsp.StatusCode != http.StatusOK {
438 return nil, fmt.Errorf("failed to get session history files: status code %d", rsp.StatusCode)
439 }
440 var files []proto.File
441 if err := json.NewDecoder(rsp.Body).Decode(&files); err != nil {
442 return nil, fmt.Errorf("failed to decode session history files: %w", err)
443 }
444 return files, nil
445}
446
447// CreateSession creates a new session in a workspace as a proto type.
448func (c *Client) CreateSession(ctx context.Context, id string, title string) (*proto.Session, error) {
449 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/sessions", id), nil, jsonBody(proto.Session{Title: title}), http.Header{"Content-Type": []string{"application/json"}})
450 if err != nil {
451 return nil, fmt.Errorf("failed to create session: %w", err)
452 }
453 defer rsp.Body.Close()
454 if rsp.StatusCode != http.StatusOK {
455 return nil, fmt.Errorf("failed to create session: status code %d", rsp.StatusCode)
456 }
457 var sess proto.Session
458 if err := json.NewDecoder(rsp.Body).Decode(&sess); err != nil {
459 return nil, fmt.Errorf("failed to decode session: %w", err)
460 }
461 return &sess, nil
462}
463
464// ListSessions lists all sessions in a workspace as proto types.
465func (c *Client) ListSessions(ctx context.Context, id string) ([]proto.Session, error) {
466 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions", id), nil, nil)
467 if err != nil {
468 return nil, fmt.Errorf("failed to get sessions: %w", err)
469 }
470 defer rsp.Body.Close()
471 if rsp.StatusCode != http.StatusOK {
472 return nil, fmt.Errorf("failed to get sessions: status code %d", rsp.StatusCode)
473 }
474 var sessions []proto.Session
475 if err := json.NewDecoder(rsp.Body).Decode(&sessions); err != nil {
476 return nil, fmt.Errorf("failed to decode sessions: %w", err)
477 }
478 return sessions, nil
479}
480
481// GrantPermission grants a permission on a workspace.
482func (c *Client) GrantPermission(ctx context.Context, id string, req proto.PermissionGrant) error {
483 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/permissions/grant", id), nil, jsonBody(req), http.Header{"Content-Type": []string{"application/json"}})
484 if err != nil {
485 return fmt.Errorf("failed to grant permission: %w", err)
486 }
487 defer rsp.Body.Close()
488 if rsp.StatusCode != http.StatusOK {
489 return fmt.Errorf("failed to grant permission: status code %d", rsp.StatusCode)
490 }
491 return nil
492}
493
494// SetPermissionsSkipRequests sets the skip-requests flag for a workspace.
495func (c *Client) SetPermissionsSkipRequests(ctx context.Context, id string, skip bool) error {
496 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/permissions/skip", id), nil, jsonBody(proto.PermissionSkipRequest{Skip: skip}), http.Header{"Content-Type": []string{"application/json"}})
497 if err != nil {
498 return fmt.Errorf("failed to set permissions skip requests: %w", err)
499 }
500 defer rsp.Body.Close()
501 if rsp.StatusCode != http.StatusOK {
502 return fmt.Errorf("failed to set permissions skip requests: status code %d", rsp.StatusCode)
503 }
504 return nil
505}
506
507// GetPermissionsSkipRequests retrieves the skip-requests flag for a workspace.
508func (c *Client) GetPermissionsSkipRequests(ctx context.Context, id string) (bool, error) {
509 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/permissions/skip", id), nil, nil)
510 if err != nil {
511 return false, fmt.Errorf("failed to get permissions skip requests: %w", err)
512 }
513 defer rsp.Body.Close()
514 if rsp.StatusCode != http.StatusOK {
515 return false, fmt.Errorf("failed to get permissions skip requests: status code %d", rsp.StatusCode)
516 }
517 var skip proto.PermissionSkipRequest
518 if err := json.NewDecoder(rsp.Body).Decode(&skip); err != nil {
519 return false, fmt.Errorf("failed to decode permissions skip requests: %w", err)
520 }
521 return skip.Skip, nil
522}
523
524// GetConfig retrieves the workspace-specific configuration.
525func (c *Client) GetConfig(ctx context.Context, id string) (*config.Config, error) {
526 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/config", id), nil, nil)
527 if err != nil {
528 return nil, fmt.Errorf("failed to get config: %w", err)
529 }
530 defer rsp.Body.Close()
531 if rsp.StatusCode != http.StatusOK {
532 return nil, fmt.Errorf("failed to get config: status code %d", rsp.StatusCode)
533 }
534 var cfg config.Config
535 if err := json.NewDecoder(rsp.Body).Decode(&cfg); err != nil {
536 return nil, fmt.Errorf("failed to decode config: %w", err)
537 }
538 return &cfg, nil
539}
540
541func jsonBody(v any) *bytes.Buffer {
542 b := new(bytes.Buffer)
543 m, _ := json.Marshal(v)
544 b.Write(m)
545 return b
546}
547
548// SaveSession updates a session in a workspace, returning a proto type.
549func (c *Client) SaveSession(ctx context.Context, id string, sess proto.Session) (*proto.Session, error) {
550 rsp, err := c.put(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s", id, sess.ID), nil, jsonBody(sess), http.Header{"Content-Type": []string{"application/json"}})
551 if err != nil {
552 return nil, fmt.Errorf("failed to save session: %w", err)
553 }
554 defer rsp.Body.Close()
555 if rsp.StatusCode != http.StatusOK {
556 return nil, fmt.Errorf("failed to save session: status code %d", rsp.StatusCode)
557 }
558 var saved proto.Session
559 if err := json.NewDecoder(rsp.Body).Decode(&saved); err != nil {
560 return nil, fmt.Errorf("failed to decode session: %w", err)
561 }
562 return &saved, nil
563}
564
565// DeleteSession deletes a session from a workspace.
566func (c *Client) DeleteSession(ctx context.Context, id string, sessionID string) error {
567 rsp, err := c.delete(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s", id, sessionID), nil, nil)
568 if err != nil {
569 return fmt.Errorf("failed to delete session: %w", err)
570 }
571 defer rsp.Body.Close()
572 if rsp.StatusCode != http.StatusOK {
573 return fmt.Errorf("failed to delete session: status code %d", rsp.StatusCode)
574 }
575 return nil
576}
577
578// ListUserMessages retrieves user-role messages for a session as proto types.
579func (c *Client) ListUserMessages(ctx context.Context, id string, sessionID string) ([]proto.Message, error) {
580 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s/messages/user", id, sessionID), nil, nil)
581 if err != nil {
582 return nil, fmt.Errorf("failed to get user messages: %w", err)
583 }
584 defer rsp.Body.Close()
585 if rsp.StatusCode != http.StatusOK {
586 return nil, fmt.Errorf("failed to get user messages: status code %d", rsp.StatusCode)
587 }
588 var msgs []proto.Message
589 if err := json.NewDecoder(rsp.Body).Decode(&msgs); err != nil && !errors.Is(err, io.EOF) {
590 return nil, fmt.Errorf("failed to decode user messages: %w", err)
591 }
592 return msgs, nil
593}
594
595// ListAllUserMessages retrieves all user-role messages across sessions as proto types.
596func (c *Client) ListAllUserMessages(ctx context.Context, id string) ([]proto.Message, error) {
597 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/messages/user", id), nil, nil)
598 if err != nil {
599 return nil, fmt.Errorf("failed to get all user messages: %w", err)
600 }
601 defer rsp.Body.Close()
602 if rsp.StatusCode != http.StatusOK {
603 return nil, fmt.Errorf("failed to get all user messages: status code %d", rsp.StatusCode)
604 }
605 var msgs []proto.Message
606 if err := json.NewDecoder(rsp.Body).Decode(&msgs); err != nil && !errors.Is(err, io.EOF) {
607 return nil, fmt.Errorf("failed to decode all user messages: %w", err)
608 }
609 return msgs, nil
610}
611
612// CancelAgentSession cancels an ongoing agent operation for a session.
613func (c *Client) CancelAgentSession(ctx context.Context, id string, sessionID string) error {
614 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s/cancel", id, sessionID), nil, nil, nil)
615 if err != nil {
616 return fmt.Errorf("failed to cancel agent session: %w", err)
617 }
618 defer rsp.Body.Close()
619 if rsp.StatusCode != http.StatusOK {
620 return fmt.Errorf("failed to cancel agent session: status code %d", rsp.StatusCode)
621 }
622 return nil
623}
624
625// GetAgentSessionQueuedPromptsList retrieves the list of queued prompt
626// strings for a session.
627func (c *Client) GetAgentSessionQueuedPromptsList(ctx context.Context, id string, sessionID string) ([]string, error) {
628 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/agent/sessions/%s/prompts/list", id, sessionID), nil, nil)
629 if err != nil {
630 return nil, fmt.Errorf("failed to get queued prompts list: %w", err)
631 }
632 defer rsp.Body.Close()
633 if rsp.StatusCode != http.StatusOK {
634 return nil, fmt.Errorf("failed to get queued prompts list: status code %d", rsp.StatusCode)
635 }
636 var prompts []string
637 if err := json.NewDecoder(rsp.Body).Decode(&prompts); err != nil {
638 return nil, fmt.Errorf("failed to decode queued prompts list: %w", err)
639 }
640 return prompts, nil
641}
642
643// GetDefaultSmallModel retrieves the default small model for a provider.
644func (c *Client) GetDefaultSmallModel(ctx context.Context, id string, providerID string) (*config.SelectedModel, error) {
645 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/agent/default-small-model", id), url.Values{"provider_id": []string{providerID}}, nil)
646 if err != nil {
647 return nil, fmt.Errorf("failed to get default small model: %w", err)
648 }
649 defer rsp.Body.Close()
650 if rsp.StatusCode != http.StatusOK {
651 return nil, fmt.Errorf("failed to get default small model: status code %d", rsp.StatusCode)
652 }
653 var model config.SelectedModel
654 if err := json.NewDecoder(rsp.Body).Decode(&model); err != nil {
655 return nil, fmt.Errorf("failed to decode default small model: %w", err)
656 }
657 return &model, nil
658}
659
660// FileTrackerRecordRead records a file read for a session.
661func (c *Client) FileTrackerRecordRead(ctx context.Context, id string, sessionID, path string) error {
662 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/filetracker/read", id), nil, jsonBody(struct {
663 SessionID string `json:"session_id"`
664 Path string `json:"path"`
665 }{SessionID: sessionID, Path: path}), http.Header{"Content-Type": []string{"application/json"}})
666 if err != nil {
667 return fmt.Errorf("failed to record file read: %w", err)
668 }
669 defer rsp.Body.Close()
670 if rsp.StatusCode != http.StatusOK {
671 return fmt.Errorf("failed to record file read: status code %d", rsp.StatusCode)
672 }
673 return nil
674}
675
676// FileTrackerLastReadTime returns the last read time for a file in a
677// session.
678func (c *Client) FileTrackerLastReadTime(ctx context.Context, id string, sessionID, path string) (time.Time, error) {
679 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/filetracker/lastread", id), url.Values{
680 "session_id": []string{sessionID},
681 "path": []string{path},
682 }, nil)
683 if err != nil {
684 return time.Time{}, fmt.Errorf("failed to get last read time: %w", err)
685 }
686 defer rsp.Body.Close()
687 if rsp.StatusCode != http.StatusOK {
688 return time.Time{}, fmt.Errorf("failed to get last read time: status code %d", rsp.StatusCode)
689 }
690 var t time.Time
691 if err := json.NewDecoder(rsp.Body).Decode(&t); err != nil {
692 return time.Time{}, fmt.Errorf("failed to decode last read time: %w", err)
693 }
694 return t, nil
695}
696
697// FileTrackerListReadFiles returns the list of read files for a session.
698func (c *Client) FileTrackerListReadFiles(ctx context.Context, id string, sessionID string) ([]string, error) {
699 rsp, err := c.get(ctx, fmt.Sprintf("/workspaces/%s/sessions/%s/filetracker/files", id, sessionID), nil, nil)
700 if err != nil {
701 return nil, fmt.Errorf("failed to get read files: %w", err)
702 }
703 defer rsp.Body.Close()
704 if rsp.StatusCode != http.StatusOK {
705 return nil, fmt.Errorf("failed to get read files: status code %d", rsp.StatusCode)
706 }
707 var files []string
708 if err := json.NewDecoder(rsp.Body).Decode(&files); err != nil {
709 return nil, fmt.Errorf("failed to decode read files: %w", err)
710 }
711 return files, nil
712}
713
714// LSPStart starts an LSP server for a path.
715func (c *Client) LSPStart(ctx context.Context, id string, path string) error {
716 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/lsps/start", id), nil, jsonBody(struct {
717 Path string `json:"path"`
718 }{Path: path}), http.Header{"Content-Type": []string{"application/json"}})
719 if err != nil {
720 return fmt.Errorf("failed to start LSP: %w", err)
721 }
722 defer rsp.Body.Close()
723 if rsp.StatusCode != http.StatusOK {
724 return fmt.Errorf("failed to start LSP: status code %d", rsp.StatusCode)
725 }
726 return nil
727}
728
729// LSPStopAll stops all LSP servers for a workspace.
730func (c *Client) LSPStopAll(ctx context.Context, id string) error {
731 rsp, err := c.post(ctx, fmt.Sprintf("/workspaces/%s/lsps/stop", id), nil, nil, nil)
732 if err != nil {
733 return fmt.Errorf("failed to stop LSPs: %w", err)
734 }
735 defer rsp.Body.Close()
736 if rsp.StatusCode != http.StatusOK {
737 return fmt.Errorf("failed to stop LSPs: status code %d", rsp.StatusCode)
738 }
739 return nil
740}