blob: 51348022a332b89d0436aea3ba895fd05400062b [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package main
2
3import (
4 "bytes"
5 "context"
6 "flag"
7 "fmt"
8 "io"
9 "log/slog"
10 "math/rand/v2"
11 "net"
12 "net/http"
13 "os"
14 "os/exec"
15 "runtime"
16 "runtime/debug"
17 "strings"
18
19 "github.com/richardlehane/crock32"
20 "sketch.dev/ant"
21 "sketch.dev/dockerimg"
22 "sketch.dev/httprr"
23 "sketch.dev/loop"
24 "sketch.dev/loop/server"
25 "sketch.dev/skabandclient"
26 "sketch.dev/skribe"
27 "sketch.dev/termui"
28)
29
30func main() {
31 err := run()
32 if err != nil {
33 fmt.Fprintf(os.Stderr, "%v: %v\n", os.Args[0], err)
34 os.Exit(1)
35 }
36}
37
38func run() error {
39 addr := flag.String("addr", "localhost:0", "local debug HTTP server address")
40 skabandAddr := flag.String("skaband-addr", "https://sketch.dev", "URL of the skaband server")
41 unsafe := flag.Bool("unsafe", false, "run directly without a docker container")
42 openBrowser := flag.Bool("open", false, "open sketch URL in system browser")
43 httprrFile := flag.String("httprr", "", "if set, record HTTP interactions to file")
Earl Lee2e463fb2025-04-17 11:22:22 -070044 maxIterations := flag.Uint64("max-iterations", 0, "maximum number of iterations the agent should perform per turn, 0 to disable limit")
45 maxWallTime := flag.Duration("max-wall-time", 0, "maximum time the agent should run per turn, 0 to disable limit")
46 maxDollars := flag.Float64("max-dollars", 5.0, "maximum dollars the agent should spend per turn, 0 to disable limit")
47 one := flag.Bool("one", false, "run a single iteration and exit without termui")
Earl Lee2e463fb2025-04-17 11:22:22 -070048 verbose := flag.Bool("verbose", false, "enable verbose output")
49 version := flag.Bool("version", false, "print the version and exit")
Earl Lee2e463fb2025-04-17 11:22:22 -070050 workingDir := flag.String("C", "", "when set, change to this directory before running")
Sean McCulloughae3480f2025-04-23 15:28:20 -070051 sshPort := flag.Int("ssh_port", 0, "the host port number that the container's ssh server will listen on, or a randomly chosen port if this value is 0")
Philip Zeyligerd1402952025-04-23 03:54:37 +000052
53 // Flags geared towards sketch developers or sketch internals:
54 gitUsername := flag.String("git-username", "", "(internal) username for git commits")
55 gitEmail := flag.String("git-email", "", "(internal) email for git commits")
56 sessionID := flag.String("session-id", newSessionID(), "(internal) unique session-id for a sketch process")
57 record := flag.Bool("httprecord", true, "(debugging) Record trace (if httprr is set)")
58 noCleanup := flag.Bool("nocleanup", false, "(debugging) do not clean up docker containers on exit")
59 containerLogDest := flag.String("save-container-logs", "", "(debugging) host path to save container logs to on exit")
Philip Zeyliger18532b22025-04-23 21:11:46 +000060 outsideHostname := flag.String("outside-hostname", "", "(internal) hostname on the outside system")
61 outsideOS := flag.String("outside-os", "", "(internal) OS on the outside system")
62 outsideWorkingDir := flag.String("outside-working-dir", "", "(internal) working dir on the outside system")
Philip Zeyligerd1402952025-04-23 03:54:37 +000063 sketchBinaryLinux := flag.String("sketch-binary-linux", "", "(development) path to a pre-built sketch binary for linux")
64
Earl Lee2e463fb2025-04-17 11:22:22 -070065 flag.Parse()
66
67 if *version {
68 bi, ok := debug.ReadBuildInfo()
69 if ok {
70 fmt.Printf("%s@%v\n", bi.Path, bi.Main.Version)
71 }
72 return nil
73 }
74
75 firstMessage := flag.Args()
76
77 // Add a global "session_id" to all logs using this context.
78 // A "session" is a single full run of the agent.
79 ctx := skribe.ContextWithAttr(context.Background(), slog.String("session_id", *sessionID))
80
81 var slogHandler slog.Handler
82 var err error
83 var logFile *os.File
Philip Zeyliger5e227dd2025-04-21 15:55:29 -070084 if !*one && !*verbose {
Earl Lee2e463fb2025-04-17 11:22:22 -070085 // Log to a file
86 logFile, err = os.CreateTemp("", "sketch-cli-log-*")
87 if err != nil {
88 return fmt.Errorf("cannot create log file: %v", err)
89 }
David Crawshawfaa39be2025-04-25 08:06:38 -070090 if *unsafe {
91 fmt.Printf("structured logs: %v\n", logFile.Name())
92 }
Earl Lee2e463fb2025-04-17 11:22:22 -070093 defer logFile.Close()
94 slogHandler = slog.NewJSONHandler(logFile, &slog.HandlerOptions{Level: slog.LevelDebug})
95 slogHandler = skribe.AttrsWrap(slogHandler)
96 } else {
97 // Log straight to stdout, no task_id
98 // TODO: verbosity controls?
99 slogHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
100 // TODO: we skipped "AttrsWrap" here because it adds a bunch of line noise. do we want it anyway?
101 }
102 slog.SetDefault(slog.New(slogHandler))
103
104 if *workingDir != "" {
105 if err := os.Chdir(*workingDir); err != nil {
106 return fmt.Errorf("sketch: cannot change directory to %q: %v", *workingDir, err)
107 }
108 }
109
110 if *gitUsername == "" {
111 *gitUsername = defaultGitUsername()
112 }
113 if *gitEmail == "" {
114 *gitEmail = defaultGitEmail()
115 }
116
117 inDocker := false
118 if _, err := os.Stat("/.dockerenv"); err == nil {
119 inDocker = true
120 }
121
122 if !inDocker {
Philip Zeyliger8a89e1c2025-04-21 15:27:13 -0700123 msgs, err := hostReqsCheck(*unsafe)
Earl Lee2e463fb2025-04-17 11:22:22 -0700124 if *verbose {
125 fmt.Println("Host requirement checks:")
126 for _, m := range msgs {
127 fmt.Println(m)
128 }
129 }
130 if err != nil {
131 return err
132 }
133 }
134
135 if *one && len(firstMessage) == 0 {
136 return fmt.Errorf("-one flag requires a message to send to the agent")
137 }
138
139 var pubKey, antURL, apiKey string
140 if *skabandAddr == "" {
141 apiKey = os.Getenv("ANTHROPIC_API_KEY")
142 if apiKey == "" {
143 return fmt.Errorf("ANTHROPIC_API_KEY environment variable is not set")
144 }
145 } else {
146 if inDocker {
147 apiKey = os.Getenv("ANTHROPIC_API_KEY")
148 pubKey = os.Getenv("SKETCH_PUB_KEY")
149 antURL, err = skabandclient.LocalhostToDockerInternal(os.Getenv("ANT_URL"))
150 if err != nil {
151 return err
152 }
153 } else {
154 privKey, err := skabandclient.LoadOrCreatePrivateKey(skabandclient.DefaultKeyPath())
155 if err != nil {
156 return err
157 }
158 pubKey, antURL, apiKey, err = skabandclient.Login(os.Stdout, privKey, *skabandAddr, *sessionID)
159 if err != nil {
160 return err
161 }
162 }
163 }
164
165 if !*unsafe {
166 cwd, err := os.Getwd()
167 if err != nil {
168 return fmt.Errorf("sketch: cannot determine current working directory: %v", err)
169 }
170 // TODO: this is a bit of a mess.
171 // The "stdout" and "stderr" used here are "just" for verbose logs from LaunchContainer.
172 // LaunchContainer has to attach the termui, and does that directly to os.Stdout/os.Stderr
173 // regardless of what is attached here.
174 // This is probably wrong. Instead of having a big "if verbose" switch here, the verbosity
175 // switches should be inside LaunchContainer and os.Stdout/os.Stderr should be passed in
176 // here (with the parameters being kept for future testing).
177 var stdout, stderr io.Writer
178 var outbuf, errbuf *bytes.Buffer
179 if *verbose {
180 stdout, stderr = os.Stdout, os.Stderr
181 } else {
182 outbuf, errbuf = &bytes.Buffer{}, &bytes.Buffer{}
183 stdout, stderr = outbuf, errbuf
184 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700185
Earl Lee2e463fb2025-04-17 11:22:22 -0700186 config := dockerimg.ContainerConfig{
187 SessionID: *sessionID,
188 LocalAddr: *addr,
189 SkabandAddr: *skabandAddr,
190 AntURL: antURL,
191 AntAPIKey: apiKey,
192 Path: cwd,
193 GitUsername: *gitUsername,
194 GitEmail: *gitEmail,
195 OpenBrowser: *openBrowser,
196 NoCleanup: *noCleanup,
197 ContainerLogDest: *containerLogDest,
198 SketchBinaryLinux: *sketchBinaryLinux,
199 SketchPubKey: pubKey,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700200 SSHPort: *sshPort,
Earl Lee2e463fb2025-04-17 11:22:22 -0700201 ForceRebuild: false,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000202 OutsideHostname: getHostname(),
203 OutsideOS: runtime.GOOS,
204 OutsideWorkingDir: cwd,
Earl Lee2e463fb2025-04-17 11:22:22 -0700205 }
206 if err := dockerimg.LaunchContainer(ctx, stdout, stderr, config); err != nil {
207 if *verbose {
208 fmt.Fprintf(os.Stderr, "dockerimg.LaunchContainer failed: %v\ndockerimg.LaunchContainer stderr:\n%s\ndockerimg.LaunchContainer stdout:\n%s\n", err, errbuf.String(), outbuf.String())
209 }
210 return err
211 }
212 return nil
213 }
214
215 var client *http.Client
216 if *httprrFile != "" {
217 var err error
218 var rr *httprr.RecordReplay
219 if *record {
220 rr, err = httprr.OpenForRecording(*httprrFile, http.DefaultTransport)
221 } else {
222 rr, err = httprr.Open(*httprrFile, http.DefaultTransport)
223 }
224 if err != nil {
225 return fmt.Errorf("httprr: %v", err)
226 }
227 // Scrub API keys from requests for security
228 rr.ScrubReq(func(req *http.Request) error {
229 req.Header.Del("x-api-key")
230 req.Header.Del("anthropic-api-key")
231 return nil
232 })
233 client = rr.Client()
234 }
235 wd, err := os.Getwd()
236 if err != nil {
237 return err
238 }
239
240 agentConfig := loop.AgentConfig{
Philip Zeyliger18532b22025-04-23 21:11:46 +0000241 Context: ctx,
242 AntURL: antURL,
243 APIKey: apiKey,
244 HTTPC: client,
245 Budget: ant.Budget{MaxResponses: *maxIterations, MaxWallTime: *maxWallTime, MaxDollars: *maxDollars},
246 GitUsername: *gitUsername,
247 GitEmail: *gitEmail,
248 SessionID: *sessionID,
249 ClientGOOS: runtime.GOOS,
250 ClientGOARCH: runtime.GOARCH,
251 UseAnthropicEdit: os.Getenv("SKETCH_ANTHROPIC_EDIT") == "1",
252 OutsideHostname: *outsideHostname,
253 OutsideOS: *outsideOS,
254 OutsideWorkingDir: *outsideWorkingDir,
Earl Lee2e463fb2025-04-17 11:22:22 -0700255 }
256 agent := loop.NewAgent(agentConfig)
257
258 srv, err := server.New(agent, logFile)
259 if err != nil {
260 return err
261 }
262
263 if !inDocker {
264 ini := loop.AgentInit{
265 WorkingDir: wd,
266 }
267 if err = agent.Init(ini); err != nil {
268 return fmt.Errorf("failed to initialize agent: %v", err)
269 }
270 }
271
272 // Start the agent
273 go agent.Loop(ctx)
274
275 // Start the local HTTP server.
276 ln, err := net.Listen("tcp", *addr)
277 if err != nil {
278 return fmt.Errorf("cannot create debug server listener: %v", err)
279 }
280 go (&http.Server{Handler: srv}).Serve(ln)
281 var ps1URL string
282 if *skabandAddr != "" {
283 ps1URL = fmt.Sprintf("%s/s/%s", *skabandAddr, *sessionID)
284 } else if !inDocker {
285 // Do not tell users about the port inside the container, let the
286 // process running on the host report this.
287 ps1URL = fmt.Sprintf("http://%s", ln.Addr())
288 }
289
290 if len(firstMessage) > 0 {
291 agent.UserMessage(ctx, strings.Join(firstMessage, " "))
292 }
293
294 if inDocker {
295 <-agent.Ready()
296 if ps1URL == "" {
297 ps1URL = agent.URL()
298 }
299 }
300
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700301 // Open the web UI URL in the system browser if requested
Earl Lee2e463fb2025-04-17 11:22:22 -0700302 if *openBrowser {
303 dockerimg.OpenBrowser(ctx, ps1URL)
304 }
305
306 // Create the termui instance
307 s := termui.New(agent, ps1URL)
308 defer func() {
309 r := recover()
310 if err := s.RestoreOldState(); err != nil {
311 fmt.Fprintf(os.Stderr, "couldn't restore old terminal state: %s\n", err)
312 }
313 if r != nil {
314 panic(r)
315 }
316 }()
317
318 // Start skaband connection loop if needed
319 if *skabandAddr != "" {
320 connectFn := func(connected bool) {
David Crawshaw7b436622025-04-24 17:49:01 +0000321 if *verbose {
322 if connected {
323 s.AppendSystemMessage("skaband connected")
324 } else {
325 s.AppendSystemMessage("skaband disconnected")
326 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 }
328 }
329 go skabandclient.DialAndServeLoop(ctx, *skabandAddr, *sessionID, pubKey, srv, connectFn)
330 }
331
332 if *one {
333 for {
334 m := agent.WaitForMessage(ctx)
335 if m.Content != "" {
336 fmt.Printf("💬 %s %s: %s\n", m.Timestamp.Format("15:04:05"), m.Type, m.Content)
337 }
338 if m.EndOfTurn && m.ParentConversationID == nil {
339 fmt.Printf("Total cost: $%0.2f\n", agent.TotalUsage().TotalCostUSD)
340 return nil
341 }
342 }
343 }
344
345 if err := s.Run(ctx); err != nil {
346 return err
347 }
348
349 return nil
350}
351
352// newSessionID generates a new 10-byte random Session ID.
353func newSessionID() string {
354 u1, u2 := rand.Uint64(), rand.Uint64N(1<<16)
355 s := crock32.Encode(u1) + crock32.Encode(uint64(u2))
356 if len(s) < 16 {
357 s += strings.Repeat("0", 16-len(s))
358 }
359 return s[0:4] + "-" + s[4:8] + "-" + s[8:12] + "-" + s[12:16]
360}
361
Philip Zeyligerd1402952025-04-23 03:54:37 +0000362func getHostname() string {
363 hostname, err := os.Hostname()
364 if err != nil {
365 return "unknown"
366 }
367 return hostname
368}
369
Earl Lee2e463fb2025-04-17 11:22:22 -0700370func defaultGitUsername() string {
371 out, err := exec.Command("git", "config", "user.name").CombinedOutput()
372 if err != nil {
373 return "Sketch🕴️" // TODO: what should this be?
374 }
375 return strings.TrimSpace(string(out))
376}
377
378func defaultGitEmail() string {
379 out, err := exec.Command("git", "config", "user.email").CombinedOutput()
380 if err != nil {
381 return "skallywag@sketch.dev" // TODO: what should this be?
382 }
383 return strings.TrimSpace(string(out))
384}