|
| 1 | +package attach |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "net/http" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + tea "github.com/charmbracelet/bubbletea" |
| 16 | + "github.com/coder/agentapi/lib/httpapi" |
| 17 | + "github.com/spf13/cobra" |
| 18 | + sse "github.com/tmaxmax/go-sse" |
| 19 | + "golang.org/x/term" |
| 20 | + "golang.org/x/xerrors" |
| 21 | +) |
| 22 | + |
| 23 | +type ChannelWriter struct { |
| 24 | + ch chan []byte |
| 25 | +} |
| 26 | + |
| 27 | +func (c *ChannelWriter) Write(p []byte) (n int, err error) { |
| 28 | + c.ch <- p |
| 29 | + return len(p), nil |
| 30 | +} |
| 31 | + |
| 32 | +func (c *ChannelWriter) Receive() ([]byte, bool) { |
| 33 | + data, ok := <-c.ch |
| 34 | + return data, ok |
| 35 | +} |
| 36 | + |
| 37 | +type model struct { |
| 38 | + screen string |
| 39 | +} |
| 40 | + |
| 41 | +func (m model) Init() tea.Cmd { |
| 42 | + // Just return `nil`, which means "no I/O right now, please." |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +type screenMsg struct { |
| 47 | + screen string |
| 48 | +} |
| 49 | + |
| 50 | +type finishMsg struct{} |
| 51 | + |
| 52 | +//lint:ignore U1000 The Update function is used by the Bubble Tea framework |
| 53 | +func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { |
| 54 | + switch msg := msg.(type) { |
| 55 | + case screenMsg: |
| 56 | + m.screen = msg.screen |
| 57 | + if m.screen != "" && m.screen[len(m.screen)-1] != '\n' { |
| 58 | + m.screen += "\n" |
| 59 | + } |
| 60 | + case tea.KeyMsg: |
| 61 | + if msg.String() == "ctrl+c" { |
| 62 | + return m, tea.Quit |
| 63 | + } |
| 64 | + case finishMsg: |
| 65 | + return m, tea.Quit |
| 66 | + } |
| 67 | + |
| 68 | + return m, nil |
| 69 | +} |
| 70 | + |
| 71 | +func (m model) View() string { |
| 72 | + return m.screen |
| 73 | +} |
| 74 | + |
| 75 | +func ReadScreenOverHTTP(ctx context.Context, url string, ch chan<- httpapi.ScreenUpdateBody) error { |
| 76 | + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 77 | + req.Header.Set("Content-Type", "application/json") |
| 78 | + |
| 79 | + res, err := http.DefaultClient.Do(req) |
| 80 | + if err != nil { |
| 81 | + return xerrors.Errorf("failed to do request: %w", err) |
| 82 | + } |
| 83 | + defer res.Body.Close() |
| 84 | + |
| 85 | + for ev, err := range sse.Read(res.Body, &sse.ReadConfig{ |
| 86 | + // 256KB: screen can be big. The default terminal size is 80x1000, |
| 87 | + // which can be over 80000 bytes. |
| 88 | + MaxEventSize: 256 * 1024, |
| 89 | + }) { |
| 90 | + if err != nil { |
| 91 | + return xerrors.Errorf("failed to read sse: %w", err) |
| 92 | + } |
| 93 | + var screen httpapi.ScreenUpdateBody |
| 94 | + if err := json.Unmarshal([]byte(ev.Data), &screen); err != nil { |
| 95 | + return xerrors.Errorf("failed to unmarshal screen: %w", err) |
| 96 | + } |
| 97 | + ch <- screen |
| 98 | + } |
| 99 | + return nil |
| 100 | +} |
| 101 | + |
| 102 | +func WriteRawInputOverHTTP(ctx context.Context, url string, msg string) error { |
| 103 | + messageRequest := httpapi.MessageRequestBody{ |
| 104 | + Type: httpapi.MessageTypeRaw, |
| 105 | + Content: msg, |
| 106 | + } |
| 107 | + messageRequestBytes, err := json.Marshal(messageRequest) |
| 108 | + if err != nil { |
| 109 | + return xerrors.Errorf("failed to marshal message request: %w", err) |
| 110 | + } |
| 111 | + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(messageRequestBytes)) |
| 112 | + req.Header.Set("Content-Type", "application/json") |
| 113 | + |
| 114 | + res, err := http.DefaultClient.Do(req) |
| 115 | + if err != nil { |
| 116 | + return xerrors.Errorf("failed to do request: %w", err) |
| 117 | + } |
| 118 | + defer res.Body.Close() |
| 119 | + if res.StatusCode != http.StatusOK { |
| 120 | + return xerrors.Errorf("failed to write raw input: %w", errors.New(res.Status)) |
| 121 | + } |
| 122 | + |
| 123 | + return nil |
| 124 | +} |
| 125 | + |
| 126 | +func runAttach(remoteUrl string) error { |
| 127 | + ctx, cancel := context.WithCancel(context.Background()) |
| 128 | + defer cancel() |
| 129 | + stdin := int(os.Stdin.Fd()) |
| 130 | + |
| 131 | + oldState, err := term.MakeRaw(stdin) |
| 132 | + if err != nil { |
| 133 | + return xerrors.Errorf("failed to make raw: %w", err) |
| 134 | + } |
| 135 | + defer term.Restore(stdin, oldState) |
| 136 | + |
| 137 | + stdinWriter := &ChannelWriter{ |
| 138 | + ch: make(chan []byte, 4096), |
| 139 | + } |
| 140 | + tee := io.TeeReader(os.Stdin, stdinWriter) |
| 141 | + p := tea.NewProgram(model{}, tea.WithInput(tee), tea.WithAltScreen()) |
| 142 | + screenCh := make(chan httpapi.ScreenUpdateBody, 64) |
| 143 | + |
| 144 | + readScreenErrCh := make(chan error, 1) |
| 145 | + go func() { |
| 146 | + defer close(readScreenErrCh) |
| 147 | + if err := ReadScreenOverHTTP(ctx, remoteUrl+"/internal/screen", screenCh); err != nil { |
| 148 | + if errors.Is(err, context.Canceled) { |
| 149 | + return |
| 150 | + } |
| 151 | + readScreenErrCh <- xerrors.Errorf("failed to read screen: %w", err) |
| 152 | + } |
| 153 | + }() |
| 154 | + writeRawInputErrCh := make(chan error, 1) |
| 155 | + go func() { |
| 156 | + defer close(writeRawInputErrCh) |
| 157 | + for { |
| 158 | + select { |
| 159 | + case <-ctx.Done(): |
| 160 | + return |
| 161 | + case buf, ok := <-stdinWriter.ch: |
| 162 | + if !ok { |
| 163 | + return |
| 164 | + } |
| 165 | + input := string(buf) |
| 166 | + // Don't send Ctrl+C to the agent |
| 167 | + if input == "\x03" { |
| 168 | + continue |
| 169 | + } |
| 170 | + if err := WriteRawInputOverHTTP(ctx, remoteUrl+"/message", input); err != nil { |
| 171 | + writeRawInputErrCh <- xerrors.Errorf("failed to write raw input: %w", err) |
| 172 | + return |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | + }() |
| 177 | + go func() { |
| 178 | + for { |
| 179 | + select { |
| 180 | + case <-ctx.Done(): |
| 181 | + return |
| 182 | + case screenUpdate, ok := <-screenCh: |
| 183 | + if !ok { |
| 184 | + return |
| 185 | + } |
| 186 | + p.Send(screenMsg{ |
| 187 | + screen: screenUpdate.Screen, |
| 188 | + }) |
| 189 | + } |
| 190 | + } |
| 191 | + }() |
| 192 | + pErrCh := make(chan error, 1) |
| 193 | + go func() { |
| 194 | + _, err := p.Run() |
| 195 | + pErrCh <- err |
| 196 | + close(pErrCh) |
| 197 | + }() |
| 198 | + |
| 199 | + select { |
| 200 | + case err = <-readScreenErrCh: |
| 201 | + case err = <-writeRawInputErrCh: |
| 202 | + case err = <-pErrCh: |
| 203 | + case <-ctx.Done(): |
| 204 | + err = nil |
| 205 | + } |
| 206 | + |
| 207 | + p.Send(finishMsg{}) |
| 208 | + select { |
| 209 | + case <-pErrCh: |
| 210 | + case <-time.After(1 * time.Second): |
| 211 | + } |
| 212 | + |
| 213 | + return err |
| 214 | +} |
| 215 | + |
| 216 | +var remoteUrlArg string |
| 217 | + |
| 218 | +var AttachCmd = &cobra.Command{ |
| 219 | + Use: "attach", |
| 220 | + Short: "Attach to a running agent", |
| 221 | + Long: `Attach to a running agent`, |
| 222 | + Run: func(cmd *cobra.Command, args []string) { |
| 223 | + remoteUrl := remoteUrlArg |
| 224 | + if remoteUrl == "" { |
| 225 | + fmt.Fprintln(os.Stderr, "URL is required") |
| 226 | + os.Exit(1) |
| 227 | + } |
| 228 | + if !strings.HasPrefix(remoteUrl, "http") { |
| 229 | + remoteUrl = "http://" + remoteUrl |
| 230 | + } |
| 231 | + remoteUrl = strings.TrimRight(remoteUrl, "/") |
| 232 | + if err := runAttach(remoteUrl); err != nil { |
| 233 | + fmt.Fprintf(os.Stderr, "Attach failed: %+v\n", err) |
| 234 | + os.Exit(1) |
| 235 | + } |
| 236 | + }, |
| 237 | +} |
| 238 | + |
| 239 | +func init() { |
| 240 | + AttachCmd.Flags().StringVarP(&remoteUrlArg, "url", "u", "localhost:3284", "URL of the agentapi server to attach to. May optionally include a protocol and a path.") |
| 241 | +} |
0 commit comments