| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "sync/atomic" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/gorilla/websocket" |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | func AgentSocket(ctx context.Context, configPath string, target AgentTarget, path string, input io.ReadCloser, output io.Writer) (returned error) { |
| 21 | if !strings.HasPrefix(path, "/api/") || strings.ContainsAny(path, "\r\n\\") || strings.Contains(path, "#") || strings.Contains(path, "://") { |
| 22 | return &AgentError{Code: "invalid_input", Message: "Use a relative /api/ WebSocket path", NextAction: "routes"} |
| 23 | } |
| 24 | c, err := agentConnectTarget(ctx, configPath, target) |
| 25 | if err != nil { |
| 26 | return err |
| 27 | } |
| 28 | defer c.close() |
| 29 | if target.Scope == "desktop" { |
| 30 | return &AgentError{Code: "invalid_input", Message: "Use local or selected scope for a workload WebSocket", NextAction: "client.context"} |
| 31 | } |
| 32 | if target.Scope == "client" && target.Connection == "" { |
| 33 | return &AgentError{Code: "invalid_input", Message: "Client sockets require an explicit connection generation", NextAction: "client.context"} |
| 34 | } |
| 35 | connection := "local" |
| 36 | if target.Connection != "" { |
| 37 | connection = target.Connection |
| 38 | } |
| 39 | req, _ := http.NewRequest("GET", c.origin, nil) |
| 40 | headers := http.Header{"Origin": []string{c.origin}, connectionHeader: []string{connection}} |
| 41 | for _, cookie := range c.client.Jar.Cookies(req.URL) { |
| 42 | headers.Add("Cookie", cookie.String()) |
| 43 | } |
| 44 | dialer := websocket.Dialer{Proxy: nil, HandshakeTimeout: 15 * time.Second} |
| 45 | ws, response, err := dialer.DialContext(ctx, "ws"+strings.TrimPrefix(c.origin, "http")+path, headers) |
| 46 | if err != nil { |
| 47 | if response != nil { |
| 48 | return agentHTTPError(response.StatusCode) |
| 49 | } |
| 50 | return &AgentError{Code: "connection_failed", Message: "WebSocket connection failed", NextAction: "status"} |
| 51 | } |
| 52 | defer ws.Close() |
| 53 | ws.SetReadLimit(32 << 20) |
| 54 | stop := context.AfterFunc(ctx, func() { ws.Close() }) |
| 55 | defer stop() |
| 56 | type frame struct { |
| 57 | Type string `json:"type"` |
| 58 | Data json.RawMessage `json:"data"` |
| 59 | } |
| 60 | var mutex sync.Mutex |
| 61 | emit := func(value any) error { |
| 62 | mutex.Lock() |
| 63 | defer mutex.Unlock() |
| 64 | return json.NewEncoder(output).Encode(value) |
| 65 | } |
| 66 | if err := emit(map[string]any{"protocol": AgentProtocol, "status": "connected"}); err != nil { |
| 67 | return err |
| 68 | } |
| 69 | inputDone := make(chan error, 1) |
| 70 | var closing, inputFailed atomic.Bool |
| 71 | defer func() { |
| 72 | closing.Store(true) |
| 73 | input.Close() |
| 74 | <-inputDone |
| 75 | if inputFailed.Load() { |
| 76 | returned = &AgentError{Code: "invalid_input", Message: "Invalid NDJSON WebSocket input; the failed input was not executed", NextAction: "capabilities"} |
| 77 | } |
| 78 | }() |
| 79 | go func() { |
| 80 | decoder := json.NewDecoder(input) |
| 81 | for { |
| 82 | var value frame |
| 83 | if err := decoder.Decode(&value); err != nil { |
| 84 | if !errors.Is(err, io.EOF) && !closing.Load() { |
| 85 | inputFailed.Store(true) |
| 86 | ws.Close() |
| 87 | } |
| 88 | inputDone <- err |
| 89 | return |
| 90 | } |
| 91 | var body []byte |
| 92 | kind := websocket.TextMessage |
| 93 | switch value.Type { |
| 94 | case "text": |
| 95 | var text string |
| 96 | if json.Unmarshal(value.Data, &text) != nil { |
| 97 | inputFailed.Store(true) |
| 98 | inputDone <- io.ErrUnexpectedEOF |
| 99 | ws.Close() |
| 100 | return |
| 101 | } |
| 102 | body = []byte(text) |
| 103 | case "binary": |
| 104 | kind = websocket.BinaryMessage |
| 105 | if json.Unmarshal(value.Data, &body) != nil { |
| 106 | inputFailed.Store(true) |
| 107 | inputDone <- io.ErrUnexpectedEOF |
| 108 | ws.Close() |
| 109 | return |
| 110 | } |
| 111 | default: |
| 112 | inputFailed.Store(true) |
| 113 | inputDone <- io.ErrUnexpectedEOF |
| 114 | ws.Close() |
| 115 | return |
| 116 | } |
| 117 | ws.SetWriteDeadline(time.Now().Add(30 * time.Second)) |
| 118 | if err := ws.WriteMessage(kind, body); err != nil { |
| 119 | inputDone <- err |
| 120 | ws.Close() |
| 121 | return |
| 122 | } |
| 123 | } |
| 124 | }() |
| 125 | for { |
| 126 | kind, body, err := ws.ReadMessage() |
| 127 | if err != nil { |
| 128 | if ctx.Err() != nil { |
| 129 | return nil |
| 130 | } |
| 131 | if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) { |
| 132 | return nil |
| 133 | } |
| 134 | return &AgentError{Code: "connection_closed", Message: "WebSocket closed; inspect the original session before reconnecting", NextAction: "status"} |
| 135 | } |
| 136 | var value any |
| 137 | switch kind { |
| 138 | case websocket.TextMessage: |
| 139 | value = map[string]any{"type": "text", "data": string(body)} |
| 140 | case websocket.BinaryMessage: |
| 141 | value = map[string]any{"type": "binary", "data": body} |
| 142 | default: |
| 143 | continue |
| 144 | } |
| 145 | if err := emit(value); err != nil { |
| 146 | return err |
| 147 | } |
| 148 | } |
| 149 | } |