-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathecho.go
More file actions
210 lines (177 loc) · 4.76 KB
/
echo.go
File metadata and controls
210 lines (177 loc) · 4.76 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
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
"regexp"
"strings"
"time"
"github.com/acarl005/stripansi"
st "github.com/coder/agentapi/lib/screentracker"
)
type ScriptEntry struct {
ExpectMessage string `json:"expectMessage"`
ThinkDurationMS int64 `json:"thinkDurationMS"`
ResponseMessage string `json:"responseMessage"`
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: echo <script.json>")
os.Exit(1)
}
runEchoAgent(os.Args[1])
}
func loadScript(scriptPath string) ([]ScriptEntry, error) {
data, err := os.ReadFile(scriptPath)
if err != nil {
return nil, fmt.Errorf("failed to read script file: %w", err)
}
var script []ScriptEntry
if err := json.Unmarshal(data, &script); err != nil {
return nil, fmt.Errorf("failed to parse script JSON: %w", err)
}
return script, nil
}
func runEchoAgent(scriptPath string) {
script, err := loadScript(scriptPath)
if err != nil {
fmt.Printf("Error loading script: %v\n", err)
os.Exit(1)
}
if len(script) == 0 {
fmt.Println("Script is empty")
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
go func() {
for {
select {
case <-sigCh:
cancel()
fmt.Println("Exiting...")
os.Exit(0)
case <-ctx.Done():
return
}
}
}()
var messages []st.ConversationMessage
redrawTerminal(messages, false)
scriptIndex := 0
scanner := bufio.NewScanner(os.Stdin)
for scriptIndex < len(script) {
entry := script[scriptIndex]
expectedMsg := strings.TrimSpace(entry.ExpectMessage)
// Handle initial/follow-up messages (empty ExpectMessage)
if expectedMsg == "" {
// Show thinking state if there's a delay
if entry.ThinkDurationMS > 0 {
redrawTerminal(messages, true)
spinnerCtx, spinnerCancel := context.WithCancel(ctx)
go runSpinner(spinnerCtx)
time.Sleep(time.Duration(entry.ThinkDurationMS) * time.Millisecond)
if spinnerCancel != nil {
spinnerCancel()
}
}
messages = append(messages, st.ConversationMessage{
Role: st.ConversationRoleAgent,
Message: entry.ResponseMessage,
Time: time.Now(),
})
redrawTerminal(messages, false)
scriptIndex++
continue
}
// Wait for user input for non-initial messages
if !scanner.Scan() {
break
}
input := scanner.Text()
input = cleanTerminalInput(input)
if input == "" {
continue
}
if input != expectedMsg {
fmt.Printf("Error: Expected message '%s' but received '%s'\n", expectedMsg, input)
os.Exit(1)
}
messages = append(messages, st.ConversationMessage{
Role: st.ConversationRoleUser,
Message: entry.ExpectMessage,
Time: time.Now(),
})
redrawTerminal(messages, false)
// Show thinking state if there's a delay
if entry.ThinkDurationMS > 0 {
redrawTerminal(messages, true)
spinnerCtx, spinnerCancel := context.WithCancel(ctx)
go runSpinner(spinnerCtx)
time.Sleep(time.Duration(entry.ThinkDurationMS) * time.Millisecond)
spinnerCancel()
}
messages = append(messages, st.ConversationMessage{
Role: st.ConversationRoleAgent,
Message: entry.ResponseMessage,
Time: time.Now(),
})
redrawTerminal(messages, false)
scriptIndex++
}
// Now just do nothing.
<-make(chan struct{})
}
func redrawTerminal(messages []st.ConversationMessage, thinking bool) {
fmt.Print("\033[2J\033[H") // Clear screen and move cursor to home
// Show conversation history
for _, msg := range messages {
if msg.Role == st.ConversationRoleUser {
fmt.Printf("> %s\n", msg.Message)
} else {
fmt.Printf("%s\n", msg.Message)
}
}
if thinking {
fmt.Print("Thinking... ")
} else {
fmt.Print("> ")
}
}
func cleanTerminalInput(input string) string {
// Strip ANSI escape sequences
input = stripansi.Strip(input)
// Remove bracketed paste mode sequences (^[[200~ and ^[[201~)
bracketedPasteRe := regexp.MustCompile(`\x1b\[\d+~`)
input = bracketedPasteRe.ReplaceAllString(input, "")
// Remove backspace sequences (character followed by ^H)
backspaceRe := regexp.MustCompile(`.\x08`)
input = backspaceRe.ReplaceAllString(input, "")
// Remove other common control characters
input = strings.ReplaceAll(input, "\x08", "") // backspace
input = strings.ReplaceAll(input, "\x7f", "") // delete
input = strings.ReplaceAll(input, "\x1b", "") // escape (if any remain)
return strings.TrimSpace(input)
}
func runSpinner(ctx context.Context) {
spinnerChars := []string{"|", "/", "-", "\\"}
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
i := 0
for {
select {
case <-ticker.C:
fmt.Printf("\rThinking %s", spinnerChars[i%len(spinnerChars)])
i++
case <-ctx.Done():
// Clear spinner on cancellation
fmt.Print("\r" + strings.Repeat(" ", 20) + "\r")
return
}
}
}