blob: 0ec6c3fd08a9b4b494861216109e85606d9e4fc0 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package loop
2
3import (
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07004 "cmp"
Earl Lee2e463fb2025-04-17 11:22:22 -07005 "context"
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -07006 _ "embed"
Earl Lee2e463fb2025-04-17 11:22:22 -07007 "encoding/json"
8 "fmt"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +00009 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070010 "log/slog"
11 "net/http"
12 "os"
13 "os/exec"
14 "runtime/debug"
15 "slices"
16 "strings"
17 "sync"
18 "time"
19
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +000020 "sketch.dev/browser"
Earl Lee2e463fb2025-04-17 11:22:22 -070021 "sketch.dev/claudetool"
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +000022 "sketch.dev/claudetool/bashkit"
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -070023 "sketch.dev/experiment"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070024 "sketch.dev/llm"
25 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070026)
27
28const (
29 userCancelMessage = "user requested agent to stop handling responses"
30)
31
Philip Zeyligerb7c58752025-05-01 10:10:17 -070032type MessageIterator interface {
33 // Next blocks until the next message is available. It may
34 // return nil if the underlying iterator context is done.
35 Next() *AgentMessage
36 Close()
37}
38
Earl Lee2e463fb2025-04-17 11:22:22 -070039type CodingAgent interface {
40 // Init initializes an agent inside a docker container.
41 Init(AgentInit) error
42
43 // Ready returns a channel closed after Init successfully called.
44 Ready() <-chan struct{}
45
46 // URL reports the HTTP URL of this agent.
47 URL() string
48
49 // UserMessage enqueues a message to the agent and returns immediately.
50 UserMessage(ctx context.Context, msg string)
51
Philip Zeyligerb7c58752025-05-01 10:10:17 -070052 // Returns an iterator that finishes when the context is done and
53 // starts with the given message index.
54 NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator
Earl Lee2e463fb2025-04-17 11:22:22 -070055
56 // Loop begins the agent loop returns only when ctx is cancelled.
57 Loop(ctx context.Context)
58
Sean McCulloughedc88dc2025-04-30 02:55:01 +000059 CancelTurn(cause error)
Earl Lee2e463fb2025-04-17 11:22:22 -070060
61 CancelToolUse(toolUseID string, cause error) error
62
63 // Returns a subset of the agent's message history.
64 Messages(start int, end int) []AgentMessage
65
66 // Returns the current number of messages in the history
67 MessageCount() int
68
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070069 TotalUsage() conversation.CumulativeUsage
70 OriginalBudget() conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -070071
Earl Lee2e463fb2025-04-17 11:22:22 -070072 WorkingDir() string
73
74 // Diff returns a unified diff of changes made since the agent was instantiated.
75 // If commit is non-nil, it shows the diff for just that specific commit.
76 Diff(commit *string) (string, error)
77
78 // InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
79 InitialCommit() string
80
81 // Title returns the current title of the conversation.
82 Title() string
83
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000084 // BranchName returns the git branch name for the conversation.
85 BranchName() string
86
Earl Lee2e463fb2025-04-17 11:22:22 -070087 // OS returns the operating system of the client.
88 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +000089
Philip Zeyligerc72fff52025-04-29 20:17:54 +000090 // SessionID returns the unique session identifier.
91 SessionID() string
92
Philip Zeyliger99a9a022025-04-27 15:15:25 +000093 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
94 OutstandingLLMCallCount() int
95
96 // OutstandingToolCalls returns the names of outstanding tool calls.
97 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +000098 OutsideOS() string
99 OutsideHostname() string
100 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000101 GitOrigin() string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000102 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
103 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700104
105 // RestartConversation resets the conversation history
106 RestartConversation(ctx context.Context, rev string, initialPrompt string) error
107 // SuggestReprompt suggests a re-prompt based on the current conversation.
108 SuggestReprompt(ctx context.Context) (string, error)
109 // IsInContainer returns true if the agent is running in a container
110 IsInContainer() bool
111 // FirstMessageIndex returns the index of the first message in the current conversation
112 FirstMessageIndex() int
Sean McCulloughd9d45812025-04-30 16:53:41 -0700113
114 CurrentStateName() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700115}
116
117type CodingAgentMessageType string
118
119const (
120 UserMessageType CodingAgentMessageType = "user"
121 AgentMessageType CodingAgentMessageType = "agent"
122 ErrorMessageType CodingAgentMessageType = "error"
123 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
124 ToolUseMessageType CodingAgentMessageType = "tool"
125 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
126 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
127
128 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
129)
130
131type AgentMessage struct {
132 Type CodingAgentMessageType `json:"type"`
133 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
134 EndOfTurn bool `json:"end_of_turn"`
135
136 Content string `json:"content"`
137 ToolName string `json:"tool_name,omitempty"`
138 ToolInput string `json:"input,omitempty"`
139 ToolResult string `json:"tool_result,omitempty"`
140 ToolError bool `json:"tool_error,omitempty"`
141 ToolCallId string `json:"tool_call_id,omitempty"`
142
143 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
144 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
145
Sean McCulloughd9f13372025-04-21 15:08:49 -0700146 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
147 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
148
Earl Lee2e463fb2025-04-17 11:22:22 -0700149 // Commits is a list of git commits for a commit message
150 Commits []*GitCommit `json:"commits,omitempty"`
151
152 Timestamp time.Time `json:"timestamp"`
153 ConversationID string `json:"conversation_id"`
154 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700155 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700156
157 // Message timing information
158 StartTime *time.Time `json:"start_time,omitempty"`
159 EndTime *time.Time `json:"end_time,omitempty"`
160 Elapsed *time.Duration `json:"elapsed,omitempty"`
161
162 // Turn duration - the time taken for a complete agent turn
163 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
164
165 Idx int `json:"idx"`
166}
167
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700168// SetConvo sets m.ConversationID and m.ParentConversationID based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700169func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700170 if convo == nil {
171 m.ConversationID = ""
172 m.ParentConversationID = nil
173 return
174 }
175 m.ConversationID = convo.ID
176 if convo.Parent != nil {
177 m.ParentConversationID = &convo.Parent.ID
178 }
179}
180
Earl Lee2e463fb2025-04-17 11:22:22 -0700181// GitCommit represents a single git commit for a commit message
182type GitCommit struct {
183 Hash string `json:"hash"` // Full commit hash
184 Subject string `json:"subject"` // Commit subject line
185 Body string `json:"body"` // Full commit message body
186 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
187}
188
189// ToolCall represents a single tool call within an agent message
190type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700191 Name string `json:"name"`
192 Input string `json:"input"`
193 ToolCallId string `json:"tool_call_id"`
194 ResultMessage *AgentMessage `json:"result_message,omitempty"`
195 Args string `json:"args,omitempty"`
196 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700197}
198
199func (a *AgentMessage) Attr() slog.Attr {
200 var attrs []any = []any{
201 slog.String("type", string(a.Type)),
202 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700203 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 if a.EndOfTurn {
205 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
206 }
207 if a.Content != "" {
208 attrs = append(attrs, slog.String("content", a.Content))
209 }
210 if a.ToolName != "" {
211 attrs = append(attrs, slog.String("tool_name", a.ToolName))
212 }
213 if a.ToolInput != "" {
214 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
215 }
216 if a.Elapsed != nil {
217 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
218 }
219 if a.TurnDuration != nil {
220 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
221 }
222 if a.ToolResult != "" {
223 attrs = append(attrs, slog.String("tool_result", a.ToolResult))
224 }
225 if a.ToolError {
226 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
227 }
228 if len(a.ToolCalls) > 0 {
229 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
230 for i, tc := range a.ToolCalls {
231 toolCallAttrs = append(toolCallAttrs, slog.Group(
232 fmt.Sprintf("tool_call_%d", i),
233 slog.String("name", tc.Name),
234 slog.String("input", tc.Input),
235 ))
236 }
237 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
238 }
239 if a.ConversationID != "" {
240 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
241 }
242 if a.ParentConversationID != nil {
243 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
244 }
245 if a.Usage != nil && !a.Usage.IsZero() {
246 attrs = append(attrs, a.Usage.Attr())
247 }
248 // TODO: timestamp, convo ids, idx?
249 return slog.Group("agent_message", attrs...)
250}
251
252func errorMessage(err error) AgentMessage {
253 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
254 if os.Getenv(("DEBUG")) == "1" {
255 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
256 }
257
258 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
259}
260
261func budgetMessage(err error) AgentMessage {
262 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
263}
264
265// ConvoInterface defines the interface for conversation interactions
266type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700267 CumulativeUsage() conversation.CumulativeUsage
268 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700270 SendMessage(message llm.Message) (*llm.Response, error)
271 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700272 GetID() string
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700273 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, error)
274 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700275 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700276 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700277}
278
279type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700280 convo ConvoInterface
281 config AgentConfig // config for this agent
282 workingDir string
283 repoRoot string // workingDir may be a subdir of repoRoot
284 url string
285 firstMessageIndex int // index of the first message in the current conversation
286 lastHEAD string // hash of the last HEAD that was pushed to the host (only when under docker)
287 initialCommit string // hash of the Git HEAD when the agent was instantiated or Init()
288 gitRemoteAddr string // HTTP URL of the host git repo (only when under docker)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000289 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700290 ready chan struct{} // closed when the agent is initialized (only when under docker)
291 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700292 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700293 title string
294 branchName string
295 codereview *claudetool.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700296 // State machine to track agent state
297 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000298 // Outside information
299 outsideHostname string
300 outsideOS string
301 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000302 // URL of the git remote 'origin' if it exists
303 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700304
305 // Time when the current turn started (reset at the beginning of InnerLoop)
306 startOfTurn time.Time
307
308 // Inbox - for messages from the user to the agent.
309 // sent on by UserMessage
310 // . e.g. when user types into the chat textarea
311 // read from by GatherMessages
312 inbox chan string
313
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000314 // protects cancelTurn
315 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000317 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700318
319 // protects following
320 mu sync.Mutex
321
322 // Stores all messages for this agent
323 history []AgentMessage
324
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700325 // Iterators add themselves here when they're ready to be notified of new messages.
326 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700327
328 // Track git commits we've already seen (by hash)
329 seenCommits map[string]bool
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000330
331 // Track outstanding LLM call IDs
332 outstandingLLMCalls map[string]struct{}
333
334 // Track outstanding tool calls by ID with their names
335 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700336}
337
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700338// NewIterator implements CodingAgent.
339func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
340 a.mu.Lock()
341 defer a.mu.Unlock()
342
343 return &MessageIteratorImpl{
344 agent: a,
345 ctx: ctx,
346 nextMessageIdx: nextMessageIdx,
347 ch: make(chan *AgentMessage, 100),
348 }
349}
350
351type MessageIteratorImpl struct {
352 agent *Agent
353 ctx context.Context
354 nextMessageIdx int
355 ch chan *AgentMessage
356 subscribed bool
357}
358
359func (m *MessageIteratorImpl) Close() {
360 m.agent.mu.Lock()
361 defer m.agent.mu.Unlock()
362 // Delete ourselves from the subscribers list
363 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
364 return x == m.ch
365 })
366 close(m.ch)
367}
368
369func (m *MessageIteratorImpl) Next() *AgentMessage {
370 // We avoid subscription at creation to let ourselves catch up to "current state"
371 // before subscribing.
372 if !m.subscribed {
373 m.agent.mu.Lock()
374 if m.nextMessageIdx < len(m.agent.history) {
375 msg := &m.agent.history[m.nextMessageIdx]
376 m.nextMessageIdx++
377 m.agent.mu.Unlock()
378 return msg
379 }
380 // The next message doesn't exist yet, so let's subscribe
381 m.agent.subscribers = append(m.agent.subscribers, m.ch)
382 m.subscribed = true
383 m.agent.mu.Unlock()
384 }
385
386 for {
387 select {
388 case <-m.ctx.Done():
389 m.agent.mu.Lock()
390 // Delete ourselves from the subscribers list
391 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
392 return x == m.ch
393 })
394 m.subscribed = false
395 m.agent.mu.Unlock()
396 return nil
397 case msg, ok := <-m.ch:
398 if !ok {
399 // Close may have been called
400 return nil
401 }
402 if msg.Idx == m.nextMessageIdx {
403 m.nextMessageIdx++
404 return msg
405 }
406 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
407 panic("out of order message")
408 }
409 }
410}
411
Sean McCulloughd9d45812025-04-30 16:53:41 -0700412// Assert that Agent satisfies the CodingAgent interface.
413var _ CodingAgent = &Agent{}
414
415// StateName implements CodingAgent.
416func (a *Agent) CurrentStateName() string {
417 if a.stateMachine == nil {
418 return ""
419 }
420 return a.stateMachine.currentState.String()
421}
422
Earl Lee2e463fb2025-04-17 11:22:22 -0700423func (a *Agent) URL() string { return a.url }
424
425// Title returns the current title of the conversation.
426// If no title has been set, returns an empty string.
427func (a *Agent) Title() string {
428 a.mu.Lock()
429 defer a.mu.Unlock()
430 return a.title
431}
432
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000433// BranchName returns the git branch name for the conversation.
434func (a *Agent) BranchName() string {
435 a.mu.Lock()
436 defer a.mu.Unlock()
437 return a.branchName
438}
439
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000440// OutstandingLLMCallCount returns the number of outstanding LLM calls.
441func (a *Agent) OutstandingLLMCallCount() int {
442 a.mu.Lock()
443 defer a.mu.Unlock()
444 return len(a.outstandingLLMCalls)
445}
446
447// OutstandingToolCalls returns the names of outstanding tool calls.
448func (a *Agent) OutstandingToolCalls() []string {
449 a.mu.Lock()
450 defer a.mu.Unlock()
451
452 tools := make([]string, 0, len(a.outstandingToolCalls))
453 for _, toolName := range a.outstandingToolCalls {
454 tools = append(tools, toolName)
455 }
456 return tools
457}
458
Earl Lee2e463fb2025-04-17 11:22:22 -0700459// OS returns the operating system of the client.
460func (a *Agent) OS() string {
461 return a.config.ClientGOOS
462}
463
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000464func (a *Agent) SessionID() string {
465 return a.config.SessionID
466}
467
Philip Zeyliger18532b22025-04-23 21:11:46 +0000468// OutsideOS returns the operating system of the outside system.
469func (a *Agent) OutsideOS() string {
470 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000471}
472
Philip Zeyliger18532b22025-04-23 21:11:46 +0000473// OutsideHostname returns the hostname of the outside system.
474func (a *Agent) OutsideHostname() string {
475 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000476}
477
Philip Zeyliger18532b22025-04-23 21:11:46 +0000478// OutsideWorkingDir returns the working directory on the outside system.
479func (a *Agent) OutsideWorkingDir() string {
480 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000481}
482
483// GitOrigin returns the URL of the git remote 'origin' if it exists.
484func (a *Agent) GitOrigin() string {
485 return a.gitOrigin
486}
487
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000488func (a *Agent) OpenBrowser(url string) {
489 if !a.IsInContainer() {
490 browser.Open(url)
491 return
492 }
493 // We're in Docker, need to send a request to the Git server
494 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700495 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000496 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700497 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000498 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700499 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000500 return
501 }
502 defer resp.Body.Close()
503 if resp.StatusCode == http.StatusOK {
504 return
505 }
506 body, _ := io.ReadAll(resp.Body)
507 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
508}
509
Sean McCullough96b60dd2025-04-30 09:49:10 -0700510// CurrentState returns the current state of the agent's state machine.
511func (a *Agent) CurrentState() State {
512 return a.stateMachine.CurrentState()
513}
514
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700515func (a *Agent) IsInContainer() bool {
516 return a.config.InDocker
517}
518
519func (a *Agent) FirstMessageIndex() int {
520 a.mu.Lock()
521 defer a.mu.Unlock()
522 return a.firstMessageIndex
523}
524
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700525// SetTitleBranch sets the title and branch name of the conversation.
526func (a *Agent) SetTitleBranch(title, branchName string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700527 a.mu.Lock()
528 defer a.mu.Unlock()
529 a.title = title
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700530 a.branchName = branchName
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700531
532 // TODO: We could potentially notify listeners of a state change, but,
533 // realistically, a new message will be sent for the tool result as well.
Earl Lee2e463fb2025-04-17 11:22:22 -0700534}
535
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000536// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700537func (a *Agent) OnToolCall(ctx context.Context, convo *conversation.Convo, id string, toolName string, toolInput json.RawMessage, content llm.Content) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000538 // Track the tool call
539 a.mu.Lock()
540 a.outstandingToolCalls[id] = toolName
541 a.mu.Unlock()
542}
543
Earl Lee2e463fb2025-04-17 11:22:22 -0700544// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700545func (a *Agent) OnToolResult(ctx context.Context, convo *conversation.Convo, toolID string, toolName string, toolInput json.RawMessage, content llm.Content, result *string, err error) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000546 // Remove the tool call from outstanding calls
547 a.mu.Lock()
548 delete(a.outstandingToolCalls, toolID)
549 a.mu.Unlock()
550
Earl Lee2e463fb2025-04-17 11:22:22 -0700551 m := AgentMessage{
552 Type: ToolUseMessageType,
553 Content: content.Text,
554 ToolResult: content.ToolResult,
555 ToolError: content.ToolError,
556 ToolName: toolName,
557 ToolInput: string(toolInput),
558 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700559 StartTime: content.ToolUseStartTime,
560 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700561 }
562
563 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700564 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
565 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700566 m.Elapsed = &elapsed
567 }
568
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700569 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700570 a.pushToOutbox(ctx, m)
571}
572
573// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700574func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000575 a.mu.Lock()
576 defer a.mu.Unlock()
577 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700578 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
579}
580
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700581// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700582// that need to be displayed (as well as tool calls that we send along when
583// they're done). (It would be reasonable to also mention tool calls when they're
584// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700585func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000586 // Remove the LLM call from outstanding calls
587 a.mu.Lock()
588 delete(a.outstandingLLMCalls, id)
589 a.mu.Unlock()
590
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700591 if resp == nil {
592 // LLM API call failed
593 m := AgentMessage{
594 Type: ErrorMessageType,
595 Content: "API call failed, type 'continue' to try again",
596 }
597 m.SetConvo(convo)
598 a.pushToOutbox(ctx, m)
599 return
600 }
601
Earl Lee2e463fb2025-04-17 11:22:22 -0700602 endOfTurn := false
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700603 if resp.StopReason != llm.StopReasonToolUse && convo.Parent == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700604 endOfTurn = true
605 }
606 m := AgentMessage{
607 Type: AgentMessageType,
608 Content: collectTextContent(resp),
609 EndOfTurn: endOfTurn,
610 Usage: &resp.Usage,
611 StartTime: resp.StartTime,
612 EndTime: resp.EndTime,
613 }
614
615 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700616 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700617 var toolCalls []ToolCall
618 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700619 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700620 toolCalls = append(toolCalls, ToolCall{
621 Name: part.ToolName,
622 Input: string(part.ToolInput),
623 ToolCallId: part.ID,
624 })
625 }
626 }
627 m.ToolCalls = toolCalls
628 }
629
630 // Calculate the elapsed time if both start and end times are set
631 if resp.StartTime != nil && resp.EndTime != nil {
632 elapsed := resp.EndTime.Sub(*resp.StartTime)
633 m.Elapsed = &elapsed
634 }
635
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700636 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700637 a.pushToOutbox(ctx, m)
638}
639
640// WorkingDir implements CodingAgent.
641func (a *Agent) WorkingDir() string {
642 return a.workingDir
643}
644
645// MessageCount implements CodingAgent.
646func (a *Agent) MessageCount() int {
647 a.mu.Lock()
648 defer a.mu.Unlock()
649 return len(a.history)
650}
651
652// Messages implements CodingAgent.
653func (a *Agent) Messages(start int, end int) []AgentMessage {
654 a.mu.Lock()
655 defer a.mu.Unlock()
656 return slices.Clone(a.history[start:end])
657}
658
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700659func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700660 return a.originalBudget
661}
662
663// AgentConfig contains configuration for creating a new Agent.
664type AgentConfig struct {
665 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700666 Service llm.Service
667 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700668 GitUsername string
669 GitEmail string
670 SessionID string
671 ClientGOOS string
672 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700673 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700674 UseAnthropicEdit bool
Philip Zeyliger18532b22025-04-23 21:11:46 +0000675 // Outside information
676 OutsideHostname string
677 OutsideOS string
678 OutsideWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -0700679}
680
681// NewAgent creates a new Agent.
682// It is not usable until Init() is called.
683func NewAgent(config AgentConfig) *Agent {
684 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000685 config: config,
686 ready: make(chan struct{}),
687 inbox: make(chan string, 100),
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700688 subscribers: make([]chan *AgentMessage, 0),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000689 startedAt: time.Now(),
690 originalBudget: config.Budget,
691 seenCommits: make(map[string]bool),
692 outsideHostname: config.OutsideHostname,
693 outsideOS: config.OutsideOS,
694 outsideWorkingDir: config.OutsideWorkingDir,
695 outstandingLLMCalls: make(map[string]struct{}),
696 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700697 stateMachine: NewStateMachine(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 }
699 return agent
700}
701
702type AgentInit struct {
703 WorkingDir string
704 NoGit bool // only for testing
705
706 InDocker bool
707 Commit string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000708 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700709 GitRemoteAddr string
710 HostAddr string
711}
712
713func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700714 if a.convo != nil {
715 return fmt.Errorf("Agent.Init: already initialized")
716 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 ctx := a.config.Context
718 if ini.InDocker {
719 cmd := exec.CommandContext(ctx, "git", "stash")
720 cmd.Dir = ini.WorkingDir
721 if out, err := cmd.CombinedOutput(); err != nil {
722 return fmt.Errorf("git stash: %s: %v", out, err)
723 }
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700724 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", ini.GitRemoteAddr)
725 cmd.Dir = ini.WorkingDir
726 if out, err := cmd.CombinedOutput(); err != nil {
727 return fmt.Errorf("git remote add: %s: %v", out, err)
728 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000729 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 cmd.Dir = ini.WorkingDir
731 if out, err := cmd.CombinedOutput(); err != nil {
732 return fmt.Errorf("git fetch: %s: %w", out, err)
733 }
734 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
735 cmd.Dir = ini.WorkingDir
736 if out, err := cmd.CombinedOutput(); err != nil {
737 return fmt.Errorf("git checkout %s: %s: %w", ini.Commit, out, err)
738 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700739 a.lastHEAD = ini.Commit
740 a.gitRemoteAddr = ini.GitRemoteAddr
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000741 a.outsideHTTP = ini.OutsideHTTP
Earl Lee2e463fb2025-04-17 11:22:22 -0700742 a.initialCommit = ini.Commit
743 if ini.HostAddr != "" {
744 a.url = "http://" + ini.HostAddr
745 }
746 }
747 a.workingDir = ini.WorkingDir
748
749 if !ini.NoGit {
750 repoRoot, err := repoRoot(ctx, a.workingDir)
751 if err != nil {
752 return fmt.Errorf("repoRoot: %w", err)
753 }
754 a.repoRoot = repoRoot
755
756 commitHash, err := resolveRef(ctx, a.repoRoot, "HEAD")
757 if err != nil {
758 return fmt.Errorf("resolveRef: %w", err)
759 }
760 a.initialCommit = commitHash
761
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -0700762 llmCodeReview := claudetool.NoLLMReview
763 if experiment.Enabled("llm_review") {
764 llmCodeReview = claudetool.DoLLMReview
765 }
766 codereview, err := claudetool.NewCodeReviewer(ctx, a.repoRoot, a.initialCommit, llmCodeReview)
Earl Lee2e463fb2025-04-17 11:22:22 -0700767 if err != nil {
768 return fmt.Errorf("Agent.Init: claudetool.NewCodeReviewer: %w", err)
769 }
770 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000771
772 a.gitOrigin = getGitOrigin(ctx, ini.WorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700773 }
774 a.lastHEAD = a.initialCommit
775 a.convo = a.initConvo()
776 close(a.ready)
777 return nil
778}
779
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700780//go:embed agent_system_prompt.txt
781var agentSystemPrompt string
782
Earl Lee2e463fb2025-04-17 11:22:22 -0700783// initConvo initializes the conversation.
784// It must not be called until all agent fields are initialized,
785// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700786func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700787 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700788 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700789 convo.PromptCaching = true
790 convo.Budget = a.config.Budget
791
792 var editPrompt string
793 if a.config.UseAnthropicEdit {
794 editPrompt = "Then use the str_replace_editor tool to make those edits. For short complete file replacements, you may use the bash tool with cat and heredoc stdin."
795 } else {
796 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
797 }
798
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700799 convo.SystemPrompt = fmt.Sprintf(agentSystemPrompt, editPrompt, a.config.ClientGOOS, a.config.ClientGOARCH, a.workingDir, a.repoRoot, a.initialCommit)
Earl Lee2e463fb2025-04-17 11:22:22 -0700800
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000801 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
802 bashPermissionCheck := func(command string) error {
803 // Check if branch name is set
804 a.mu.Lock()
805 branchSet := a.branchName != ""
806 a.mu.Unlock()
807
808 // If branch is set, all commands are allowed
809 if branchSet {
810 return nil
811 }
812
813 // If branch is not set, check if this is a git commit command
814 willCommit, err := bashkit.WillRunGitCommit(command)
815 if err != nil {
816 // If there's an error checking, we should allow the command to proceed
817 return nil
818 }
819
820 // If it's a git commit and branch is not set, return an error
821 if willCommit {
822 return fmt.Errorf("you must use the title tool before making git commits")
823 }
824
825 return nil
826 }
827
828 // Create a custom bash tool with the permission check
829 bashTool := claudetool.NewBashTool(bashPermissionCheck)
830
Earl Lee2e463fb2025-04-17 11:22:22 -0700831 // Register all tools with the conversation
832 // When adding, removing, or modifying tools here, double-check that the termui tool display
833 // template in termui/termui.go has pretty-printing support for all tools.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700834 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000835 bashTool, claudetool.Keyword,
Earl Lee2e463fb2025-04-17 11:22:22 -0700836 claudetool.Think, a.titleTool(), makeDoneTool(a.codereview, a.config.GitUsername, a.config.GitEmail),
Sean McCullough485afc62025-04-28 14:28:39 -0700837 a.codereview.Tool(), a.multipleChoiceTool(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700838 }
839 if a.config.UseAnthropicEdit {
840 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
841 } else {
842 convo.Tools = append(convo.Tools, claudetool.Patch)
843 }
844 convo.Listener = a
845 return convo
846}
847
Sean McCullough485afc62025-04-28 14:28:39 -0700848func (a *Agent) multipleChoiceTool() *llm.Tool {
849 ret := &llm.Tool{
850 Name: "multiplechoice",
851 Description: "Present the user with an quick way to answer to your question using one of a short list of possible answers you would expect from the user.",
852 InputSchema: json.RawMessage(`{
853 "type": "object",
854 "description": "The question and a list of answers you would expect the user to choose from.",
855 "properties": {
856 "question": {
857 "type": "string",
858 "description": "The text of the multiple-choice question you would like the user, e.g. 'What kinds of test cases would you like me to add?'"
859 },
860 "responseOptions": {
861 "type": "array",
862 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
863 "items": {
864 "type": "object",
865 "properties": {
866 "caption": {
867 "type": "string",
868 "description": "The caption, e.g. 'Basic coverage', 'Error return values', or 'Malformed input' for the response button. Do NOT include options for responses that would end the conversation like 'Ok', 'No thank you', 'This looks good'"
869 },
870 "responseText": {
871 "type": "string",
872 "description": "The full text of the response, e.g. 'Add unit tests for basic test coverage', 'Add unit tests for error return values', or 'Add unit tests for malformed input'"
873 }
874 },
875 "required": ["caption", "responseText"]
876 }
877 }
878 },
879 "required": ["question", "responseOptions"]
880}`),
881 Run: func(ctx context.Context, input json.RawMessage) (string, error) {
882 // The Run logic for "multiplchoice" tool is a no-op on the server.
883 // The UI will present a list of options for the user to select from,
884 // and that's it as far as "executing" the tool_use goes.
885 // When the user *does* select one of the presented options, that
886 // responseText gets sent as a chat message on behalf of the user.
887 return "end your turn and wait for the user to respond", nil
888 },
889 }
890 return ret
891}
892
893type MultipleChoiceOption struct {
894 Caption string `json:"caption"`
895 ResponseText string `json:"responseText"`
896}
897
898type MultipleChoiceParams struct {
899 Question string `json:"question"`
900 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
901}
902
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +0000903// branchExists reports whether branchName exists, either locally or in well-known remotes.
904func branchExists(dir, branchName string) bool {
905 refs := []string{
906 "refs/heads/",
907 "refs/remotes/origin/",
908 "refs/remotes/sketch-host/",
909 }
910 for _, ref := range refs {
911 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
912 cmd.Dir = dir
913 if cmd.Run() == nil { // exit code 0 means branch exists
914 return true
915 }
916 }
917 return false
918}
919
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700920func (a *Agent) titleTool() *llm.Tool {
921 title := &llm.Tool{
Earl Lee2e463fb2025-04-17 11:22:22 -0700922 Name: "title",
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700923 Description: `Sets the conversation title and creates a git branch for tracking work. MANDATORY: You must use this tool before making any git commits.`,
Earl Lee2e463fb2025-04-17 11:22:22 -0700924 InputSchema: json.RawMessage(`{
925 "type": "object",
926 "properties": {
927 "title": {
928 "type": "string",
Josh Bleecher Snyder250348e2025-04-30 10:31:28 -0700929 "description": "A concise title summarizing what this conversation is about, imperative tense preferred"
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700930 },
931 "branch_name": {
932 "type": "string",
933 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
Earl Lee2e463fb2025-04-17 11:22:22 -0700934 }
935 },
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700936 "required": ["title", "branch_name"]
Earl Lee2e463fb2025-04-17 11:22:22 -0700937}`),
938 Run: func(ctx context.Context, input json.RawMessage) (string, error) {
939 var params struct {
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700940 Title string `json:"title"`
941 BranchName string `json:"branch_name"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700942 }
943 if err := json.Unmarshal(input, &params); err != nil {
944 return "", err
945 }
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700946 // It's unfortunate to not allow title changes,
947 // but it avoids having multiple branches.
948 t := a.Title()
949 if t != "" {
950 return "", fmt.Errorf("title already set to: %s", t)
951 }
952
953 if params.BranchName == "" {
954 return "", fmt.Errorf("branch_name parameter cannot be empty")
955 }
956 if params.Title == "" {
957 return "", fmt.Errorf("title parameter cannot be empty")
958 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -0700959 if params.BranchName != cleanBranchName(params.BranchName) {
960 return "", fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
961 }
962 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +0000963 if branchExists(a.workingDir, branchName) {
964 return "", fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
965 }
966
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700967 a.SetTitleBranch(params.Title, branchName)
968
969 response := fmt.Sprintf("Title set to %q, branch name set to %q", params.Title, branchName)
970 return response, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700971 },
972 }
973 return title
974}
975
976func (a *Agent) Ready() <-chan struct{} {
977 return a.ready
978}
979
980func (a *Agent) UserMessage(ctx context.Context, msg string) {
981 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
982 a.inbox <- msg
983}
984
Sean McCullough485afc62025-04-28 14:28:39 -0700985func (a *Agent) ToolResultMessage(ctx context.Context, toolCallID, msg string) {
986 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg, ToolCallId: toolCallID})
987 a.inbox <- msg
988}
989
Earl Lee2e463fb2025-04-17 11:22:22 -0700990func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
991 return a.convo.CancelToolUse(toolUseID, cause)
992}
993
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000994func (a *Agent) CancelTurn(cause error) {
995 a.cancelTurnMu.Lock()
996 defer a.cancelTurnMu.Unlock()
997 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -0700998 // Force state transition to cancelled state
999 ctx := a.config.Context
1000 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001001 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001002 }
1003}
1004
1005func (a *Agent) Loop(ctxOuter context.Context) {
1006 for {
1007 select {
1008 case <-ctxOuter.Done():
1009 return
1010 default:
1011 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001012 a.cancelTurnMu.Lock()
1013 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001014 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001015 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001016 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001017 a.cancelTurn = cancel
1018 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001019 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1020 if err != nil {
1021 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1022 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001023 cancel(nil)
1024 }
1025 }
1026}
1027
1028func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1029 if m.Timestamp.IsZero() {
1030 m.Timestamp = time.Now()
1031 }
1032
1033 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1034 if m.EndOfTurn && m.Type == AgentMessageType {
1035 turnDuration := time.Since(a.startOfTurn)
1036 m.TurnDuration = &turnDuration
1037 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1038 }
1039
Earl Lee2e463fb2025-04-17 11:22:22 -07001040 a.mu.Lock()
1041 defer a.mu.Unlock()
1042 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001043 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001044 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001045
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001046 // Notify all subscribers
1047 for _, ch := range a.subscribers {
1048 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001049 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001050}
1051
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001052func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1053 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001054 if block {
1055 select {
1056 case <-ctx.Done():
1057 return m, ctx.Err()
1058 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001059 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001060 }
1061 }
1062 for {
1063 select {
1064 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001065 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001066 default:
1067 return m, nil
1068 }
1069 }
1070}
1071
Sean McCullough885a16a2025-04-30 02:49:25 +00001072// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001073func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001074 // Reset the start of turn time
1075 a.startOfTurn = time.Now()
1076
Sean McCullough96b60dd2025-04-30 09:49:10 -07001077 // Transition to waiting for user input state
1078 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1079
Sean McCullough885a16a2025-04-30 02:49:25 +00001080 // Process initial user message
1081 initialResp, err := a.processUserMessage(ctx)
1082 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001083 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001084 return err
1085 }
1086
1087 // Handle edge case where both initialResp and err are nil
1088 if initialResp == nil {
1089 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001090 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1091
Sean McCullough9f4b8082025-04-30 17:34:07 +00001092 a.pushToOutbox(ctx, errorMessage(err))
1093 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001094 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001095
Earl Lee2e463fb2025-04-17 11:22:22 -07001096 // We do this as we go, but let's also do it at the end of the turn
1097 defer func() {
1098 if _, err := a.handleGitCommits(ctx); err != nil {
1099 // Just log the error, don't stop execution
1100 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1101 }
1102 }()
1103
Sean McCullougha1e0e492025-05-01 10:51:08 -07001104 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001105 resp := initialResp
1106 for {
1107 // Check if we are over budget
1108 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001109 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001110 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001111 }
1112
1113 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001114 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001115 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001116 break
1117 }
1118
Sean McCullough96b60dd2025-04-30 09:49:10 -07001119 // Transition to tool use requested state
1120 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1121
Sean McCullough885a16a2025-04-30 02:49:25 +00001122 // Handle tool execution
1123 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1124 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001125 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001126 }
1127
Sean McCullougha1e0e492025-05-01 10:51:08 -07001128 if toolResp == nil {
1129 return fmt.Errorf("cannot continue conversation with a nil tool response")
1130 }
1131
Sean McCullough885a16a2025-04-30 02:49:25 +00001132 // Set the response for the next iteration
1133 resp = toolResp
1134 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001135
1136 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001137}
1138
1139// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001140func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001141 // Wait for at least one message from the user
1142 msgs, err := a.GatherMessages(ctx, true)
1143 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001144 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001145 return nil, err
1146 }
1147
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001148 userMessage := llm.Message{
1149 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001150 Content: msgs,
1151 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001152
Sean McCullough96b60dd2025-04-30 09:49:10 -07001153 // Transition to sending to LLM state
1154 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1155
Sean McCullough885a16a2025-04-30 02:49:25 +00001156 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001157 resp, err := a.convo.SendMessage(userMessage)
1158 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001159 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001160 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001161 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001162 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001163
Sean McCullough96b60dd2025-04-30 09:49:10 -07001164 // Transition to processing LLM response state
1165 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1166
Sean McCullough885a16a2025-04-30 02:49:25 +00001167 return resp, nil
1168}
1169
1170// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001171func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1172 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001173 cancelled := false
1174
Sean McCullough96b60dd2025-04-30 09:49:10 -07001175 // Transition to checking for cancellation state
1176 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1177
Sean McCullough885a16a2025-04-30 02:49:25 +00001178 // Check if the operation was cancelled by the user
1179 select {
1180 case <-ctx.Done():
1181 // Don't actually run any of the tools, but rather build a response
1182 // for each tool_use message letting the LLM know that user canceled it.
1183 var err error
1184 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001185 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001186 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001187 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001188 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001189 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001190 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001191 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001192 // Transition to running tool state
1193 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1194
Sean McCullough885a16a2025-04-30 02:49:25 +00001195 // Add working directory to context for tool execution
1196 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1197
1198 // Execute the tools
1199 var err error
1200 results, err = a.convo.ToolResultContents(ctx, resp)
1201 if ctx.Err() != nil { // e.g. the user canceled the operation
1202 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001203 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001204 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001205 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001206 a.pushToOutbox(ctx, errorMessage(err))
1207 }
1208 }
1209
1210 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001211 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001212 autoqualityMessages := a.processGitChanges(ctx)
1213
1214 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001215 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001216 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001217 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001218 return false, nil
1219 }
1220
1221 // Continue the conversation with tool results and any user messages
1222 return a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1223}
1224
1225// processGitChanges checks for new git commits and runs autoformatters if needed
1226func (a *Agent) processGitChanges(ctx context.Context) []string {
1227 // Check for git commits after tool execution
1228 newCommits, err := a.handleGitCommits(ctx)
1229 if err != nil {
1230 // Just log the error, don't stop execution
1231 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1232 return nil
1233 }
1234
1235 // Run autoformatters if there was exactly one new commit
1236 var autoqualityMessages []string
1237 if len(newCommits) == 1 {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001238 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running autoformatters on new commit")
Sean McCullough885a16a2025-04-30 02:49:25 +00001239 formatted := a.codereview.Autoformat(ctx)
1240 if len(formatted) > 0 {
1241 msg := fmt.Sprintf(`
Earl Lee2e463fb2025-04-17 11:22:22 -07001242I ran autoformatters and they updated these files:
1243
1244%s
1245
1246Please amend your latest git commit with these changes and then continue with what you were doing.`,
Sean McCullough885a16a2025-04-30 02:49:25 +00001247 strings.Join(formatted, "\n"),
1248 )[1:]
1249 a.pushToOutbox(ctx, AgentMessage{
1250 Type: AutoMessageType,
1251 Content: msg,
1252 Timestamp: time.Now(),
1253 })
1254 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001255 }
1256 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001257
1258 return autoqualityMessages
1259}
1260
1261// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001262func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001263 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001264 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001265 msgs, err := a.GatherMessages(ctx, false)
1266 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001267 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001268 return false, nil
1269 }
1270
1271 // Inject any auto-generated messages from quality checks
1272 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001273 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001274 }
1275
1276 // Handle cancellation by appending a message about it
1277 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001278 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001279 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001280 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001281 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1282 } else if err := a.convo.OverBudget(); err != nil {
1283 // Handle budget issues by appending a message about it
1284 budgetMsg := "We've exceeded our budget. Please ask the user to confirm before continuing by ending the turn."
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001285 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001286 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1287 }
1288
1289 // Combine tool results with user messages
1290 results = append(results, msgs...)
1291
1292 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001293 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001294 resp, err := a.convo.SendMessage(llm.Message{
1295 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001296 Content: results,
1297 })
1298 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001299 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001300 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1301 return true, nil // Return true to continue the conversation, but with no response
1302 }
1303
Sean McCullough96b60dd2025-04-30 09:49:10 -07001304 // Transition back to processing LLM response
1305 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1306
Sean McCullough885a16a2025-04-30 02:49:25 +00001307 if cancelled {
1308 return false, nil
1309 }
1310
1311 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001312}
1313
1314func (a *Agent) overBudget(ctx context.Context) error {
1315 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001316 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001317 m := budgetMessage(err)
1318 m.Content = m.Content + "\n\nBudget reset."
1319 a.pushToOutbox(ctx, budgetMessage(err))
1320 a.convo.ResetBudget(a.originalBudget)
1321 return err
1322 }
1323 return nil
1324}
1325
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001326func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001327 // Collect all text content
1328 var allText strings.Builder
1329 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001330 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001331 if allText.Len() > 0 {
1332 allText.WriteString("\n\n")
1333 }
1334 allText.WriteString(content.Text)
1335 }
1336 }
1337 return allText.String()
1338}
1339
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001340func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001341 a.mu.Lock()
1342 defer a.mu.Unlock()
1343 return a.convo.CumulativeUsage()
1344}
1345
Earl Lee2e463fb2025-04-17 11:22:22 -07001346// Diff returns a unified diff of changes made since the agent was instantiated.
1347func (a *Agent) Diff(commit *string) (string, error) {
1348 if a.initialCommit == "" {
1349 return "", fmt.Errorf("no initial commit reference available")
1350 }
1351
1352 // Find the repository root
1353 ctx := context.Background()
1354
1355 // If a specific commit hash is provided, show just that commit's changes
1356 if commit != nil && *commit != "" {
1357 // Validate that the commit looks like a valid git SHA
1358 if !isValidGitSHA(*commit) {
1359 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1360 }
1361
1362 // Get the diff for just this commit
1363 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1364 cmd.Dir = a.repoRoot
1365 output, err := cmd.CombinedOutput()
1366 if err != nil {
1367 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1368 }
1369 return string(output), nil
1370 }
1371
1372 // Otherwise, get the diff between the initial commit and the current state using exec.Command
1373 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.initialCommit)
1374 cmd.Dir = a.repoRoot
1375 output, err := cmd.CombinedOutput()
1376 if err != nil {
1377 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1378 }
1379
1380 return string(output), nil
1381}
1382
1383// InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
1384func (a *Agent) InitialCommit() string {
1385 return a.initialCommit
1386}
1387
1388// handleGitCommits() highlights new commits to the user. When running
1389// under docker, new HEADs are pushed to a branch according to the title.
1390func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1391 if a.repoRoot == "" {
1392 return nil, nil
1393 }
1394
1395 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1396 if err != nil {
1397 return nil, err
1398 }
1399 if head == a.lastHEAD {
1400 return nil, nil // nothing to do
1401 }
1402 defer func() {
1403 a.lastHEAD = head
1404 }()
1405
1406 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1407 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1408 // to the last 100 commits.
1409 var commits []*GitCommit
1410
1411 // Get commits since the initial commit
1412 // Format: <hash>\0<subject>\0<body>\0
1413 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1414 // Limit to 100 commits to avoid overwhelming the user
1415 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+a.initialCommit, head)
1416 cmd.Dir = a.repoRoot
1417 output, err := cmd.Output()
1418 if err != nil {
1419 return nil, fmt.Errorf("failed to get git log: %w", err)
1420 }
1421
1422 // Parse git log output and filter out already seen commits
1423 parsedCommits := parseGitLog(string(output))
1424
1425 var headCommit *GitCommit
1426
1427 // Filter out commits we've already seen
1428 for _, commit := range parsedCommits {
1429 if commit.Hash == head {
1430 headCommit = &commit
1431 }
1432
1433 // Skip if we've seen this commit before. If our head has changed, always include that.
1434 if a.seenCommits[commit.Hash] && commit.Hash != head {
1435 continue
1436 }
1437
1438 // Mark this commit as seen
1439 a.seenCommits[commit.Hash] = true
1440
1441 // Add to our list of new commits
1442 commits = append(commits, &commit)
1443 }
1444
1445 if a.gitRemoteAddr != "" {
1446 if headCommit == nil {
1447 // I think this can only happen if we have a bug or if there's a race.
1448 headCommit = &GitCommit{}
1449 headCommit.Hash = head
1450 headCommit.Subject = "unknown"
1451 commits = append(commits, headCommit)
1452 }
1453
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001454 branch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
Earl Lee2e463fb2025-04-17 11:22:22 -07001455
1456 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1457 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1458 // then use push with lease to replace.
1459 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1460 cmd.Dir = a.workingDir
1461 if out, err := cmd.CombinedOutput(); err != nil {
1462 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1463 } else {
1464 headCommit.PushedBranch = branch
1465 }
1466 }
1467
1468 // If we found new commits, create a message
1469 if len(commits) > 0 {
1470 msg := AgentMessage{
1471 Type: CommitMessageType,
1472 Timestamp: time.Now(),
1473 Commits: commits,
1474 }
1475 a.pushToOutbox(ctx, msg)
1476 }
1477 return commits, nil
1478}
1479
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001480func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001481 return strings.Map(func(r rune) rune {
1482 // lowercase
1483 if r >= 'A' && r <= 'Z' {
1484 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001485 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001486 // replace spaces with dashes
1487 if r == ' ' {
1488 return '-'
1489 }
1490 // allow alphanumerics and dashes
1491 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1492 return r
1493 }
1494 return -1
1495 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001496}
1497
1498// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1499// and returns an array of GitCommit structs.
1500func parseGitLog(output string) []GitCommit {
1501 var commits []GitCommit
1502
1503 // No output means no commits
1504 if len(output) == 0 {
1505 return commits
1506 }
1507
1508 // Split by NULL byte
1509 parts := strings.Split(output, "\x00")
1510
1511 // Process in triplets (hash, subject, body)
1512 for i := 0; i < len(parts); i++ {
1513 // Skip empty parts
1514 if parts[i] == "" {
1515 continue
1516 }
1517
1518 // This should be a hash
1519 hash := strings.TrimSpace(parts[i])
1520
1521 // Make sure we have at least a subject part available
1522 if i+1 >= len(parts) {
1523 break // No more parts available
1524 }
1525
1526 // Get the subject
1527 subject := strings.TrimSpace(parts[i+1])
1528
1529 // Get the body if available
1530 body := ""
1531 if i+2 < len(parts) {
1532 body = strings.TrimSpace(parts[i+2])
1533 }
1534
1535 // Skip to the next triplet
1536 i += 2
1537
1538 commits = append(commits, GitCommit{
1539 Hash: hash,
1540 Subject: subject,
1541 Body: body,
1542 })
1543 }
1544
1545 return commits
1546}
1547
1548func repoRoot(ctx context.Context, dir string) (string, error) {
1549 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1550 stderr := new(strings.Builder)
1551 cmd.Stderr = stderr
1552 cmd.Dir = dir
1553 out, err := cmd.Output()
1554 if err != nil {
1555 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1556 }
1557 return strings.TrimSpace(string(out)), nil
1558}
1559
1560func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1561 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1562 stderr := new(strings.Builder)
1563 cmd.Stderr = stderr
1564 cmd.Dir = dir
1565 out, err := cmd.Output()
1566 if err != nil {
1567 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1568 }
1569 // TODO: validate that out is valid hex
1570 return strings.TrimSpace(string(out)), nil
1571}
1572
1573// isValidGitSHA validates if a string looks like a valid git SHA hash.
1574// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1575func isValidGitSHA(sha string) bool {
1576 // Git SHA must be a hexadecimal string with at least 4 characters
1577 if len(sha) < 4 || len(sha) > 40 {
1578 return false
1579 }
1580
1581 // Check if the string only contains hexadecimal characters
1582 for _, char := range sha {
1583 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1584 return false
1585 }
1586 }
1587
1588 return true
1589}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001590
1591// getGitOrigin returns the URL of the git remote 'origin' if it exists
1592func getGitOrigin(ctx context.Context, dir string) string {
1593 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1594 cmd.Dir = dir
1595 stderr := new(strings.Builder)
1596 cmd.Stderr = stderr
1597 out, err := cmd.Output()
1598 if err != nil {
1599 return ""
1600 }
1601 return strings.TrimSpace(string(out))
1602}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001603
1604func (a *Agent) initGitRevision(ctx context.Context, workingDir, revision string) error {
1605 cmd := exec.CommandContext(ctx, "git", "stash")
1606 cmd.Dir = workingDir
1607 if out, err := cmd.CombinedOutput(); err != nil {
1608 return fmt.Errorf("git stash: %s: %v", out, err)
1609 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +00001610 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001611 cmd.Dir = workingDir
1612 if out, err := cmd.CombinedOutput(); err != nil {
1613 return fmt.Errorf("git fetch: %s: %w", out, err)
1614 }
1615 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", revision)
1616 cmd.Dir = workingDir
1617 if out, err := cmd.CombinedOutput(); err != nil {
1618 return fmt.Errorf("git checkout %s: %s: %w", revision, out, err)
1619 }
1620 a.lastHEAD = revision
1621 a.initialCommit = revision
1622 return nil
1623}
1624
1625func (a *Agent) RestartConversation(ctx context.Context, rev string, initialPrompt string) error {
1626 a.mu.Lock()
1627 a.title = ""
1628 a.firstMessageIndex = len(a.history)
1629 a.convo = a.initConvo()
1630 gitReset := func() error {
1631 if a.config.InDocker && rev != "" {
1632 err := a.initGitRevision(ctx, a.workingDir, rev)
1633 if err != nil {
1634 return err
1635 }
1636 } else if !a.config.InDocker && rev != "" {
1637 return fmt.Errorf("Not resetting git repo when working outside of a container.")
1638 }
1639 return nil
1640 }
1641 err := gitReset()
1642 a.mu.Unlock()
1643 if err != nil {
1644 a.pushToOutbox(a.config.Context, errorMessage(err))
1645 }
1646
1647 a.pushToOutbox(a.config.Context, AgentMessage{
1648 Type: AgentMessageType, Content: "Conversation restarted.",
1649 })
1650 if initialPrompt != "" {
1651 a.UserMessage(ctx, initialPrompt)
1652 }
1653 return nil
1654}
1655
1656func (a *Agent) SuggestReprompt(ctx context.Context) (string, error) {
1657 msg := `The user has requested a suggestion for a re-prompt.
1658
1659 Given the current conversation thus far, suggest a re-prompt that would
1660 capture the instructions and feedback so far, as well as any
1661 research or other information that would be helpful in implementing
1662 the task.
1663
1664 Reply with ONLY the reprompt text.
1665 `
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001666 userMessage := llm.UserStringMessage(msg)
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001667 // By doing this in a subconversation, the agent doesn't call tools (because
1668 // there aren't any), and there's not a concurrency risk with on-going other
1669 // outstanding conversations.
1670 convo := a.convo.SubConvoWithHistory()
1671 resp, err := convo.SendMessage(userMessage)
1672 if err != nil {
1673 a.pushToOutbox(ctx, errorMessage(err))
1674 return "", err
1675 }
1676 textContent := collectTextContent(resp)
1677 return textContent, nil
1678}