-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathattach.go
More file actions
276 lines (243 loc) · 6.42 KB
/
attach.go
File metadata and controls
276 lines (243 loc) · 6.42 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
package attach
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/coder/agentapi/lib/httpapi"
"github.com/coder/quartz"
"github.com/spf13/cobra"
sse "github.com/tmaxmax/go-sse"
"golang.org/x/term"
"golang.org/x/xerrors"
)
type ChannelWriter struct {
ch chan []byte
}
func (c *ChannelWriter) Write(p []byte) (n int, err error) {
c.ch <- p
return len(p), nil
}
func (c *ChannelWriter) Receive() ([]byte, bool) {
data, ok := <-c.ch
return data, ok
}
type model struct {
screen string
}
func (m model) Init() tea.Cmd {
// Just return `nil`, which means "no I/O right now, please."
return nil
}
type screenMsg struct {
screen string
}
type finishMsg struct{}
//lint:ignore U1000 The Update function is used by the Bubble Tea framework
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case screenMsg:
m.screen = msg.screen
if m.screen != "" && m.screen[len(m.screen)-1] != '\n' {
m.screen += "\n"
}
case tea.KeyMsg:
if msg.String() == "ctrl+c" {
return m, tea.Quit
}
case finishMsg:
return m, tea.Quit
}
return m, nil
}
func (m model) View() string {
return m.screen
}
func ReadScreenOverHTTP(ctx context.Context, url string, ch chan<- httpapi.ScreenUpdateBody) error {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return xerrors.Errorf("failed to do request: %w", err)
}
defer func() {
_ = res.Body.Close()
}()
for ev, err := range sse.Read(res.Body, &sse.ReadConfig{
// 256KB: screen can be big. The default terminal size is 80x1000,
// which can be over 80000 bytes.
MaxEventSize: 256 * 1024,
}) {
if err != nil {
return xerrors.Errorf("failed to read sse: %w", err)
}
var screen httpapi.ScreenUpdateBody
if err := json.Unmarshal([]byte(ev.Data), &screen); err != nil {
return xerrors.Errorf("failed to unmarshal screen: %w", err)
}
ch <- screen
}
return nil
}
func WriteRawInputOverHTTP(ctx context.Context, url string, msg string) error {
messageRequest := httpapi.MessageRequestBody{
Type: httpapi.MessageTypeRaw,
Content: msg,
}
messageRequestBytes, err := json.Marshal(messageRequest)
if err != nil {
return xerrors.Errorf("failed to marshal message request: %w", err)
}
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(messageRequestBytes))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return xerrors.Errorf("failed to do request: %w", err)
}
defer func() {
_ = res.Body.Close()
}()
if res.StatusCode != http.StatusOK {
return xerrors.Errorf("failed to write raw input: %w", errors.New(res.Status))
}
return nil
}
func checkACPMode(remoteURL string) (bool, error) {
resp, err := http.Get(remoteURL + "/status")
if err != nil {
return false, xerrors.Errorf("failed to check server status: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return false, xerrors.Errorf("unexpected %d response from server: %s", resp.StatusCode, resp.Status)
}
var status httpapi.StatusResponse
if err := json.NewDecoder(resp.Body).Decode(&status.Body); err != nil {
return false, xerrors.Errorf("failed to decode server status: %w", err)
}
return status.Body.Transport == httpapi.TransportACP, nil
}
func runAttach(remoteURL string) error {
// Check if server is running in ACP mode (attach not supported)
if isACP, err := checkACPMode(remoteURL); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "WARN: Unable to check server: %s", err.Error())
} else if isACP {
return xerrors.New("attach is not yet supported in ACP mode")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stdin := int(os.Stdin.Fd())
oldState, err := term.MakeRaw(stdin)
if err != nil {
return xerrors.Errorf("failed to make raw: %w", err)
}
defer func() {
_ = term.Restore(stdin, oldState)
}()
stdinWriter := &ChannelWriter{
ch: make(chan []byte, 4096),
}
tee := io.TeeReader(os.Stdin, stdinWriter)
p := tea.NewProgram(model{}, tea.WithInput(tee), tea.WithAltScreen())
screenCh := make(chan httpapi.ScreenUpdateBody, 64)
readScreenErrCh := make(chan error, 1)
go func() {
defer close(readScreenErrCh)
if err := ReadScreenOverHTTP(ctx, remoteURL+"/internal/screen", screenCh); err != nil {
if errors.Is(err, context.Canceled) {
return
}
readScreenErrCh <- xerrors.Errorf("failed to read screen: %w", err)
}
}()
writeRawInputErrCh := make(chan error, 1)
go func() {
defer close(writeRawInputErrCh)
for {
select {
case <-ctx.Done():
return
case buf, ok := <-stdinWriter.ch:
if !ok {
return
}
input := string(buf)
// Don't send Ctrl+C to the agent
if input == "\x03" {
continue
}
if err := WriteRawInputOverHTTP(ctx, remoteURL+"/message", input); err != nil {
writeRawInputErrCh <- xerrors.Errorf("failed to write raw input: %w", err)
return
}
}
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
case screenUpdate, ok := <-screenCh:
if !ok {
return
}
p.Send(screenMsg{
screen: screenUpdate.Screen,
})
}
}
}()
pErrCh := make(chan error, 1)
go func() {
_, err := p.Run()
pErrCh <- err
close(pErrCh)
}()
select {
case err = <-readScreenErrCh:
case err = <-writeRawInputErrCh:
case err = <-pErrCh:
case <-ctx.Done():
err = nil
}
p.Send(finishMsg{})
graceTimer := quartz.NewReal().NewTimer(1 * time.Second)
defer graceTimer.Stop()
select {
case <-pErrCh:
case <-graceTimer.C:
}
return err
}
var remoteUrlArg string
var AttachCmd = &cobra.Command{
Use: "attach",
Short: "Attach to a running agent",
Long: `Attach to a running agent`,
Run: func(cmd *cobra.Command, args []string) {
remoteUrl := remoteUrlArg
if remoteUrl == "" {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(1)
}
if !strings.HasPrefix(remoteUrl, "http") {
remoteUrl = "http://" + remoteUrl
}
remoteUrl = strings.TrimRight(remoteUrl, "/")
if err := runAttach(remoteUrl); err != nil {
fmt.Fprintf(os.Stderr, "Attach failed: %+v\n", err)
os.Exit(1)
}
},
}
func init() {
AttachCmd.Flags().StringVarP(&remoteUrlArg, "url", "u", "localhost:3284", "URL of the agentapi server to attach to. May optionally include a protocol and a path.")
}