blob: 23654ab73dc08914b66167b9ffa4dbbaa3e256e9 [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")
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -070042 openBrowser := flag.Bool("open", true, "open sketch URL in system browser")
Earl Lee2e463fb2025-04-17 11:22:22 -070043 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")
Pokey Rule0dcebe12025-04-28 14:51:04 +010047 oneShot := flag.Bool("one-shot", false, "exit after the first turn without termui")
48 prompt := flag.String("prompt", "", "prompt to send to sketch")
Earl Lee2e463fb2025-04-17 11:22:22 -070049 verbose := flag.Bool("verbose", false, "enable verbose output")
50 version := flag.Bool("version", false, "print the version and exit")
Earl Lee2e463fb2025-04-17 11:22:22 -070051 workingDir := flag.String("C", "", "when set, change to this directory before running")
Sean McCulloughae3480f2025-04-23 15:28:20 -070052 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 Zeyliger176a5102025-04-24 20:32:37 -070053 forceRebuild := flag.Bool("force-rebuild-container", false, "rebuild Docker container")
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000054 initialCommit := flag.String("initial-commit", "HEAD", "the git commit reference to use as starting point (incompatible with -unsafe)")
Philip Zeyligerd1402952025-04-23 03:54:37 +000055
56 // Flags geared towards sketch developers or sketch internals:
57 gitUsername := flag.String("git-username", "", "(internal) username for git commits")
58 gitEmail := flag.String("git-email", "", "(internal) email for git commits")
59 sessionID := flag.String("session-id", newSessionID(), "(internal) unique session-id for a sketch process")
60 record := flag.Bool("httprecord", true, "(debugging) Record trace (if httprr is set)")
61 noCleanup := flag.Bool("nocleanup", false, "(debugging) do not clean up docker containers on exit")
62 containerLogDest := flag.String("save-container-logs", "", "(debugging) host path to save container logs to on exit")
Philip Zeyliger18532b22025-04-23 21:11:46 +000063 outsideHostname := flag.String("outside-hostname", "", "(internal) hostname on the outside system")
64 outsideOS := flag.String("outside-os", "", "(internal) OS on the outside system")
65 outsideWorkingDir := flag.String("outside-working-dir", "", "(internal) working dir on the outside system")
Philip Zeyligerd1402952025-04-23 03:54:37 +000066 sketchBinaryLinux := flag.String("sketch-binary-linux", "", "(development) path to a pre-built sketch binary for linux")
67
Earl Lee2e463fb2025-04-17 11:22:22 -070068 flag.Parse()
69
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000070 if *unsafe && *initialCommit != "HEAD" {
71 return fmt.Errorf("cannot use -initial-commit with -unsafe, they are incompatible")
72 }
73
Earl Lee2e463fb2025-04-17 11:22:22 -070074 if *version {
75 bi, ok := debug.ReadBuildInfo()
76 if ok {
77 fmt.Printf("%s@%v\n", bi.Path, bi.Main.Version)
78 }
79 return nil
80 }
81
Earl Lee2e463fb2025-04-17 11:22:22 -070082 // Add a global "session_id" to all logs using this context.
83 // A "session" is a single full run of the agent.
84 ctx := skribe.ContextWithAttr(context.Background(), slog.String("session_id", *sessionID))
85
86 var slogHandler slog.Handler
87 var err error
88 var logFile *os.File
Pokey Rule0dcebe12025-04-28 14:51:04 +010089 if !*oneShot && !*verbose {
Earl Lee2e463fb2025-04-17 11:22:22 -070090 // Log to a file
91 logFile, err = os.CreateTemp("", "sketch-cli-log-*")
92 if err != nil {
93 return fmt.Errorf("cannot create log file: %v", err)
94 }
David Crawshawfaa39be2025-04-25 08:06:38 -070095 if *unsafe {
96 fmt.Printf("structured logs: %v\n", logFile.Name())
97 }
Earl Lee2e463fb2025-04-17 11:22:22 -070098 defer logFile.Close()
99 slogHandler = slog.NewJSONHandler(logFile, &slog.HandlerOptions{Level: slog.LevelDebug})
100 slogHandler = skribe.AttrsWrap(slogHandler)
101 } else {
102 // Log straight to stdout, no task_id
103 // TODO: verbosity controls?
104 slogHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
105 // TODO: we skipped "AttrsWrap" here because it adds a bunch of line noise. do we want it anyway?
106 }
107 slog.SetDefault(slog.New(slogHandler))
108
109 if *workingDir != "" {
110 if err := os.Chdir(*workingDir); err != nil {
111 return fmt.Errorf("sketch: cannot change directory to %q: %v", *workingDir, err)
112 }
113 }
114
115 if *gitUsername == "" {
116 *gitUsername = defaultGitUsername()
117 }
118 if *gitEmail == "" {
119 *gitEmail = defaultGitEmail()
120 }
121
122 inDocker := false
123 if _, err := os.Stat("/.dockerenv"); err == nil {
124 inDocker = true
125 }
Philip Zeyliger5fdd0242025-04-25 19:31:58 -0700126 inInsideSketch := inDocker && *outsideHostname != ""
Earl Lee2e463fb2025-04-17 11:22:22 -0700127
128 if !inDocker {
Philip Zeyliger8a89e1c2025-04-21 15:27:13 -0700129 msgs, err := hostReqsCheck(*unsafe)
Earl Lee2e463fb2025-04-17 11:22:22 -0700130 if *verbose {
131 fmt.Println("Host requirement checks:")
132 for _, m := range msgs {
133 fmt.Println(m)
134 }
135 }
136 if err != nil {
137 return err
138 }
139 }
140
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 var pubKey, antURL, apiKey string
142 if *skabandAddr == "" {
143 apiKey = os.Getenv("ANTHROPIC_API_KEY")
144 if apiKey == "" {
145 return fmt.Errorf("ANTHROPIC_API_KEY environment variable is not set")
146 }
147 } else {
148 if inDocker {
149 apiKey = os.Getenv("ANTHROPIC_API_KEY")
150 pubKey = os.Getenv("SKETCH_PUB_KEY")
151 antURL, err = skabandclient.LocalhostToDockerInternal(os.Getenv("ANT_URL"))
152 if err != nil {
153 return err
154 }
155 } else {
156 privKey, err := skabandclient.LoadOrCreatePrivateKey(skabandclient.DefaultKeyPath())
157 if err != nil {
158 return err
159 }
160 pubKey, antURL, apiKey, err = skabandclient.Login(os.Stdout, privKey, *skabandAddr, *sessionID)
161 if err != nil {
162 return err
163 }
164 }
165 }
166
167 if !*unsafe {
168 cwd, err := os.Getwd()
169 if err != nil {
170 return fmt.Errorf("sketch: cannot determine current working directory: %v", err)
171 }
172 // TODO: this is a bit of a mess.
173 // The "stdout" and "stderr" used here are "just" for verbose logs from LaunchContainer.
174 // LaunchContainer has to attach the termui, and does that directly to os.Stdout/os.Stderr
175 // regardless of what is attached here.
176 // This is probably wrong. Instead of having a big "if verbose" switch here, the verbosity
177 // switches should be inside LaunchContainer and os.Stdout/os.Stderr should be passed in
178 // here (with the parameters being kept for future testing).
179 var stdout, stderr io.Writer
180 var outbuf, errbuf *bytes.Buffer
181 if *verbose {
182 stdout, stderr = os.Stdout, os.Stderr
183 } else {
184 outbuf, errbuf = &bytes.Buffer{}, &bytes.Buffer{}
185 stdout, stderr = outbuf, errbuf
186 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700187
Earl Lee2e463fb2025-04-17 11:22:22 -0700188 config := dockerimg.ContainerConfig{
189 SessionID: *sessionID,
190 LocalAddr: *addr,
191 SkabandAddr: *skabandAddr,
192 AntURL: antURL,
193 AntAPIKey: apiKey,
194 Path: cwd,
195 GitUsername: *gitUsername,
196 GitEmail: *gitEmail,
197 OpenBrowser: *openBrowser,
198 NoCleanup: *noCleanup,
199 ContainerLogDest: *containerLogDest,
200 SketchBinaryLinux: *sketchBinaryLinux,
201 SketchPubKey: pubKey,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700202 SSHPort: *sshPort,
Philip Zeyliger176a5102025-04-24 20:32:37 -0700203 ForceRebuild: *forceRebuild,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000204 OutsideHostname: getHostname(),
205 OutsideOS: runtime.GOOS,
206 OutsideWorkingDir: cwd,
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700207 OneShot: *oneShot,
Pokey Rule0dcebe12025-04-28 14:51:04 +0100208 Prompt: *prompt,
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000209 InitialCommit: *initialCommit,
Earl Lee2e463fb2025-04-17 11:22:22 -0700210 }
211 if err := dockerimg.LaunchContainer(ctx, stdout, stderr, config); err != nil {
212 if *verbose {
213 fmt.Fprintf(os.Stderr, "dockerimg.LaunchContainer failed: %v\ndockerimg.LaunchContainer stderr:\n%s\ndockerimg.LaunchContainer stdout:\n%s\n", err, errbuf.String(), outbuf.String())
214 }
215 return err
216 }
217 return nil
218 }
219
220 var client *http.Client
221 if *httprrFile != "" {
222 var err error
223 var rr *httprr.RecordReplay
224 if *record {
225 rr, err = httprr.OpenForRecording(*httprrFile, http.DefaultTransport)
226 } else {
227 rr, err = httprr.Open(*httprrFile, http.DefaultTransport)
228 }
229 if err != nil {
230 return fmt.Errorf("httprr: %v", err)
231 }
232 // Scrub API keys from requests for security
233 rr.ScrubReq(func(req *http.Request) error {
234 req.Header.Del("x-api-key")
235 req.Header.Del("anthropic-api-key")
236 return nil
237 })
238 client = rr.Client()
239 }
240 wd, err := os.Getwd()
241 if err != nil {
242 return err
243 }
244
245 agentConfig := loop.AgentConfig{
Philip Zeyliger18532b22025-04-23 21:11:46 +0000246 Context: ctx,
247 AntURL: antURL,
248 APIKey: apiKey,
249 HTTPC: client,
250 Budget: ant.Budget{MaxResponses: *maxIterations, MaxWallTime: *maxWallTime, MaxDollars: *maxDollars},
251 GitUsername: *gitUsername,
252 GitEmail: *gitEmail,
253 SessionID: *sessionID,
254 ClientGOOS: runtime.GOOS,
255 ClientGOARCH: runtime.GOARCH,
256 UseAnthropicEdit: os.Getenv("SKETCH_ANTHROPIC_EDIT") == "1",
257 OutsideHostname: *outsideHostname,
258 OutsideOS: *outsideOS,
259 OutsideWorkingDir: *outsideWorkingDir,
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700260 InDocker: inDocker,
Earl Lee2e463fb2025-04-17 11:22:22 -0700261 }
262 agent := loop.NewAgent(agentConfig)
263
264 srv, err := server.New(agent, logFile)
265 if err != nil {
266 return err
267 }
268
Philip Zeyliger5fdd0242025-04-25 19:31:58 -0700269 if !inInsideSketch {
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 ini := loop.AgentInit{
271 WorkingDir: wd,
272 }
273 if err = agent.Init(ini); err != nil {
274 return fmt.Errorf("failed to initialize agent: %v", err)
275 }
276 }
277
278 // Start the agent
279 go agent.Loop(ctx)
280
281 // Start the local HTTP server.
282 ln, err := net.Listen("tcp", *addr)
283 if err != nil {
284 return fmt.Errorf("cannot create debug server listener: %v", err)
285 }
286 go (&http.Server{Handler: srv}).Serve(ln)
287 var ps1URL string
288 if *skabandAddr != "" {
289 ps1URL = fmt.Sprintf("%s/s/%s", *skabandAddr, *sessionID)
290 } else if !inDocker {
291 // Do not tell users about the port inside the container, let the
292 // process running on the host report this.
293 ps1URL = fmt.Sprintf("http://%s", ln.Addr())
294 }
295
Philip Zeyliger5fdd0242025-04-25 19:31:58 -0700296 if inInsideSketch {
Earl Lee2e463fb2025-04-17 11:22:22 -0700297 <-agent.Ready()
298 if ps1URL == "" {
299 ps1URL = agent.URL()
300 }
301 }
302
Pokey Rule0dcebe12025-04-28 14:51:04 +0100303 // Use prompt if provided
304 if *prompt != "" {
305 agent.UserMessage(ctx, *prompt)
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700306 }
307
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700308 // Open the web UI URL in the system browser if requested
Earl Lee2e463fb2025-04-17 11:22:22 -0700309 if *openBrowser {
310 dockerimg.OpenBrowser(ctx, ps1URL)
311 }
312
313 // Create the termui instance
314 s := termui.New(agent, ps1URL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700315
316 // Start skaband connection loop if needed
317 if *skabandAddr != "" {
318 connectFn := func(connected bool) {
David Crawshaw7b436622025-04-24 17:49:01 +0000319 if *verbose {
320 if connected {
321 s.AppendSystemMessage("skaband connected")
322 } else {
323 s.AppendSystemMessage("skaband disconnected")
324 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700325 }
326 }
327 go skabandclient.DialAndServeLoop(ctx, *skabandAddr, *sessionID, pubKey, srv, connectFn)
328 }
329
Pokey Rule0dcebe12025-04-28 14:51:04 +0100330 if *oneShot {
Earl Lee2e463fb2025-04-17 11:22:22 -0700331 for {
332 m := agent.WaitForMessage(ctx)
333 if m.Content != "" {
334 fmt.Printf("💬 %s %s: %s\n", m.Timestamp.Format("15:04:05"), m.Type, m.Content)
335 }
336 if m.EndOfTurn && m.ParentConversationID == nil {
337 fmt.Printf("Total cost: $%0.2f\n", agent.TotalUsage().TotalCostUSD)
338 return nil
339 }
340 }
341 }
342
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700343 defer func() {
344 r := recover()
345 if err := s.RestoreOldState(); err != nil {
346 fmt.Fprintf(os.Stderr, "couldn't restore old terminal state: %s\n", err)
347 }
348 if r != nil {
349 panic(r)
350 }
351 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700352 if err := s.Run(ctx); err != nil {
353 return err
354 }
355
356 return nil
357}
358
359// newSessionID generates a new 10-byte random Session ID.
360func newSessionID() string {
361 u1, u2 := rand.Uint64(), rand.Uint64N(1<<16)
362 s := crock32.Encode(u1) + crock32.Encode(uint64(u2))
363 if len(s) < 16 {
364 s += strings.Repeat("0", 16-len(s))
365 }
366 return s[0:4] + "-" + s[4:8] + "-" + s[8:12] + "-" + s[12:16]
367}
368
Philip Zeyligerd1402952025-04-23 03:54:37 +0000369func getHostname() string {
370 hostname, err := os.Hostname()
371 if err != nil {
372 return "unknown"
373 }
374 return hostname
375}
376
Earl Lee2e463fb2025-04-17 11:22:22 -0700377func defaultGitUsername() string {
378 out, err := exec.Command("git", "config", "user.name").CombinedOutput()
379 if err != nil {
380 return "Sketch🕴️" // TODO: what should this be?
381 }
382 return strings.TrimSpace(string(out))
383}
384
385func defaultGitEmail() string {
386 out, err := exec.Command("git", "config", "user.email").CombinedOutput()
387 if err != nil {
388 return "skallywag@sketch.dev" // TODO: what should this be?
389 }
390 return strings.TrimSpace(string(out))
391}