blob: e77f5881d38a3162bd066e6d1da6677d345421ce [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"
Pokey Rule7a113622025-05-12 10:58:45 +010014 "path/filepath"
Earl Lee2e463fb2025-04-17 11:22:22 -070015 "runtime/debug"
16 "slices"
17 "strings"
18 "sync"
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +000019 "text/template"
Earl Lee2e463fb2025-04-17 11:22:22 -070020 "time"
21
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +000022 "sketch.dev/browser"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "sketch.dev/claudetool"
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +000024 "sketch.dev/claudetool/bashkit"
Autoformatter4962f152025-05-06 17:24:20 +000025 "sketch.dev/claudetool/browse"
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +000026 "sketch.dev/claudetool/codereview"
Josh Bleecher Snydera997be62025-05-07 22:52:46 +000027 "sketch.dev/claudetool/onstart"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070028 "sketch.dev/llm"
Philip Zeyliger72252cb2025-05-10 17:00:08 -070029 "sketch.dev/llm/ant"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070030 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070031)
32
33const (
34 userCancelMessage = "user requested agent to stop handling responses"
35)
36
Philip Zeyligerb7c58752025-05-01 10:10:17 -070037type MessageIterator interface {
38 // Next blocks until the next message is available. It may
39 // return nil if the underlying iterator context is done.
40 Next() *AgentMessage
41 Close()
42}
43
Earl Lee2e463fb2025-04-17 11:22:22 -070044type CodingAgent interface {
45 // Init initializes an agent inside a docker container.
46 Init(AgentInit) error
47
48 // Ready returns a channel closed after Init successfully called.
49 Ready() <-chan struct{}
50
51 // URL reports the HTTP URL of this agent.
52 URL() string
53
54 // UserMessage enqueues a message to the agent and returns immediately.
55 UserMessage(ctx context.Context, msg string)
56
Philip Zeyligerb7c58752025-05-01 10:10:17 -070057 // Returns an iterator that finishes when the context is done and
58 // starts with the given message index.
59 NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator
Earl Lee2e463fb2025-04-17 11:22:22 -070060
Philip Zeyligereab12de2025-05-14 02:35:53 +000061 // Returns an iterator that notifies of state transitions until the context is done.
62 NewStateTransitionIterator(ctx context.Context) StateTransitionIterator
63
Earl Lee2e463fb2025-04-17 11:22:22 -070064 // Loop begins the agent loop returns only when ctx is cancelled.
65 Loop(ctx context.Context)
66
Sean McCulloughedc88dc2025-04-30 02:55:01 +000067 CancelTurn(cause error)
Earl Lee2e463fb2025-04-17 11:22:22 -070068
69 CancelToolUse(toolUseID string, cause error) error
70
71 // Returns a subset of the agent's message history.
72 Messages(start int, end int) []AgentMessage
73
74 // Returns the current number of messages in the history
75 MessageCount() int
76
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070077 TotalUsage() conversation.CumulativeUsage
78 OriginalBudget() conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -070079
Earl Lee2e463fb2025-04-17 11:22:22 -070080 WorkingDir() string
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +000081 RepoRoot() string
Earl Lee2e463fb2025-04-17 11:22:22 -070082
83 // Diff returns a unified diff of changes made since the agent was instantiated.
84 // If commit is non-nil, it shows the diff for just that specific commit.
85 Diff(commit *string) (string, error)
86
Philip Zeyliger49edc922025-05-14 09:45:45 -070087 // SketchGitBase returns the commit that's the "base" for Sketch's work. It
88 // starts out as the commit where sketch started, but a user can move it if need
89 // be, for example in the case of a rebase. It is stored as a git tag.
90 SketchGitBase() string
Earl Lee2e463fb2025-04-17 11:22:22 -070091
Philip Zeyligerd3ac1122025-05-14 02:54:18 +000092 // SketchGitBase returns the symbolic name for the "base" for Sketch's work.
93 // (Typically, this is "sketch-base")
94 SketchGitBaseRef() string
95
Earl Lee2e463fb2025-04-17 11:22:22 -070096 // Title returns the current title of the conversation.
97 Title() string
98
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000099 // BranchName returns the git branch name for the conversation.
100 BranchName() string
101
Earl Lee2e463fb2025-04-17 11:22:22 -0700102 // OS returns the operating system of the client.
103 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000104
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000105 // SessionID returns the unique session identifier.
106 SessionID() string
107
Philip Zeyliger75bd37d2025-05-22 18:49:14 +0000108 // DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -0700109 DetectGitChanges(ctx context.Context) error
Philip Zeyliger75bd37d2025-05-22 18:49:14 +0000110
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000111 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
112 OutstandingLLMCallCount() int
113
114 // OutstandingToolCalls returns the names of outstanding tool calls.
115 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000116 OutsideOS() string
117 OutsideHostname() string
118 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000119 GitOrigin() string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000120 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
121 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700122
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700123 // IsInContainer returns true if the agent is running in a container
124 IsInContainer() bool
125 // FirstMessageIndex returns the index of the first message in the current conversation
126 FirstMessageIndex() int
Sean McCulloughd9d45812025-04-30 16:53:41 -0700127
128 CurrentStateName() string
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700129 // CurrentTodoContent returns the current todo list data as JSON, or empty string if no todos exist
130 CurrentTodoContent() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700131}
132
133type CodingAgentMessageType string
134
135const (
136 UserMessageType CodingAgentMessageType = "user"
137 AgentMessageType CodingAgentMessageType = "agent"
138 ErrorMessageType CodingAgentMessageType = "error"
139 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
140 ToolUseMessageType CodingAgentMessageType = "tool"
141 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
142 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
143
144 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
145)
146
147type AgentMessage struct {
148 Type CodingAgentMessageType `json:"type"`
149 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
150 EndOfTurn bool `json:"end_of_turn"`
151
152 Content string `json:"content"`
153 ToolName string `json:"tool_name,omitempty"`
154 ToolInput string `json:"input,omitempty"`
155 ToolResult string `json:"tool_result,omitempty"`
156 ToolError bool `json:"tool_error,omitempty"`
157 ToolCallId string `json:"tool_call_id,omitempty"`
158
159 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
160 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
161
Sean McCulloughd9f13372025-04-21 15:08:49 -0700162 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
163 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
164
Earl Lee2e463fb2025-04-17 11:22:22 -0700165 // Commits is a list of git commits for a commit message
166 Commits []*GitCommit `json:"commits,omitempty"`
167
168 Timestamp time.Time `json:"timestamp"`
169 ConversationID string `json:"conversation_id"`
170 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700171 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700172
173 // Message timing information
174 StartTime *time.Time `json:"start_time,omitempty"`
175 EndTime *time.Time `json:"end_time,omitempty"`
176 Elapsed *time.Duration `json:"elapsed,omitempty"`
177
178 // Turn duration - the time taken for a complete agent turn
179 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
180
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000181 // HideOutput indicates that this message should not be rendered in the UI.
182 // This is useful for subconversations that generate output that shouldn't be shown to the user.
183 HideOutput bool `json:"hide_output,omitempty"`
184
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700185 // TodoContent contains the agent's todo file content when it has changed
186 TodoContent *string `json:"todo_content,omitempty"`
187
Earl Lee2e463fb2025-04-17 11:22:22 -0700188 Idx int `json:"idx"`
189}
190
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000191// SetConvo sets m.ConversationID, m.ParentConversationID, and m.HideOutput based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700192func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700193 if convo == nil {
194 m.ConversationID = ""
195 m.ParentConversationID = nil
196 return
197 }
198 m.ConversationID = convo.ID
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000199 m.HideOutput = convo.Hidden
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700200 if convo.Parent != nil {
201 m.ParentConversationID = &convo.Parent.ID
202 }
203}
204
Earl Lee2e463fb2025-04-17 11:22:22 -0700205// GitCommit represents a single git commit for a commit message
206type GitCommit struct {
207 Hash string `json:"hash"` // Full commit hash
208 Subject string `json:"subject"` // Commit subject line
209 Body string `json:"body"` // Full commit message body
210 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
211}
212
213// ToolCall represents a single tool call within an agent message
214type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700215 Name string `json:"name"`
216 Input string `json:"input"`
217 ToolCallId string `json:"tool_call_id"`
218 ResultMessage *AgentMessage `json:"result_message,omitempty"`
219 Args string `json:"args,omitempty"`
220 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700221}
222
223func (a *AgentMessage) Attr() slog.Attr {
224 var attrs []any = []any{
225 slog.String("type", string(a.Type)),
226 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700227 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700228 if a.EndOfTurn {
229 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
230 }
231 if a.Content != "" {
232 attrs = append(attrs, slog.String("content", a.Content))
233 }
234 if a.ToolName != "" {
235 attrs = append(attrs, slog.String("tool_name", a.ToolName))
236 }
237 if a.ToolInput != "" {
238 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
239 }
240 if a.Elapsed != nil {
241 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
242 }
243 if a.TurnDuration != nil {
244 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
245 }
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700246 if len(a.ToolResult) > 0 {
247 attrs = append(attrs, slog.Any("tool_result", a.ToolResult))
Earl Lee2e463fb2025-04-17 11:22:22 -0700248 }
249 if a.ToolError {
250 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
251 }
252 if len(a.ToolCalls) > 0 {
253 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
254 for i, tc := range a.ToolCalls {
255 toolCallAttrs = append(toolCallAttrs, slog.Group(
256 fmt.Sprintf("tool_call_%d", i),
257 slog.String("name", tc.Name),
258 slog.String("input", tc.Input),
259 ))
260 }
261 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
262 }
263 if a.ConversationID != "" {
264 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
265 }
266 if a.ParentConversationID != nil {
267 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
268 }
269 if a.Usage != nil && !a.Usage.IsZero() {
270 attrs = append(attrs, a.Usage.Attr())
271 }
272 // TODO: timestamp, convo ids, idx?
273 return slog.Group("agent_message", attrs...)
274}
275
276func errorMessage(err error) AgentMessage {
277 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
278 if os.Getenv(("DEBUG")) == "1" {
279 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
280 }
281
282 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
283}
284
285func budgetMessage(err error) AgentMessage {
286 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
287}
288
289// ConvoInterface defines the interface for conversation interactions
290type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700291 CumulativeUsage() conversation.CumulativeUsage
292 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700293 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700294 SendMessage(message llm.Message) (*llm.Response, error)
295 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700296 GetID() string
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +0000297 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, bool, error)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700298 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700299 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700300 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700301}
302
Philip Zeyligerf2872992025-05-22 10:35:28 -0700303// AgentGitState holds the state necessary for pushing to a remote git repo
304// when HEAD changes. If gitRemoteAddr is set, then we push to sketch/
305// any time we notice we need to.
306type AgentGitState struct {
307 mu sync.Mutex // protects following
308 lastHEAD string // hash of the last HEAD that was pushed to the host
309 gitRemoteAddr string // HTTP URL of the host git repo
310 seenCommits map[string]bool // Track git commits we've already seen (by hash)
311 branchName string
312}
313
314func (ags *AgentGitState) SetBranchName(branchName string) {
315 ags.mu.Lock()
316 defer ags.mu.Unlock()
317 ags.branchName = branchName
318}
319
320func (ags *AgentGitState) BranchName() string {
321 ags.mu.Lock()
322 defer ags.mu.Unlock()
323 return ags.branchName
324}
325
Earl Lee2e463fb2025-04-17 11:22:22 -0700326type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700327 convo ConvoInterface
328 config AgentConfig // config for this agent
Philip Zeyligerf2872992025-05-22 10:35:28 -0700329 gitState AgentGitState
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700330 workingDir string
331 repoRoot string // workingDir may be a subdir of repoRoot
332 url string
333 firstMessageIndex int // index of the first message in the current conversation
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000334 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700335 ready chan struct{} // closed when the agent is initialized (only when under docker)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000336 codebase *onstart.Codebase
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700337 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700338 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700339 title string
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000340 codereview *codereview.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700341 // State machine to track agent state
342 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000343 // Outside information
344 outsideHostname string
345 outsideOS string
346 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000347 // URL of the git remote 'origin' if it exists
348 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700349
350 // Time when the current turn started (reset at the beginning of InnerLoop)
351 startOfTurn time.Time
352
353 // Inbox - for messages from the user to the agent.
354 // sent on by UserMessage
355 // . e.g. when user types into the chat textarea
356 // read from by GatherMessages
357 inbox chan string
358
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000359 // protects cancelTurn
360 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700361 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000362 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700363
364 // protects following
365 mu sync.Mutex
366
367 // Stores all messages for this agent
368 history []AgentMessage
369
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700370 // Iterators add themselves here when they're ready to be notified of new messages.
371 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700372
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000373 // Track outstanding LLM call IDs
374 outstandingLLMCalls map[string]struct{}
375
376 // Track outstanding tool calls by ID with their names
377 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700378}
379
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700380// NewIterator implements CodingAgent.
381func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
382 a.mu.Lock()
383 defer a.mu.Unlock()
384
385 return &MessageIteratorImpl{
386 agent: a,
387 ctx: ctx,
388 nextMessageIdx: nextMessageIdx,
389 ch: make(chan *AgentMessage, 100),
390 }
391}
392
393type MessageIteratorImpl struct {
394 agent *Agent
395 ctx context.Context
396 nextMessageIdx int
397 ch chan *AgentMessage
398 subscribed bool
399}
400
401func (m *MessageIteratorImpl) Close() {
402 m.agent.mu.Lock()
403 defer m.agent.mu.Unlock()
404 // Delete ourselves from the subscribers list
405 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
406 return x == m.ch
407 })
408 close(m.ch)
409}
410
411func (m *MessageIteratorImpl) Next() *AgentMessage {
412 // We avoid subscription at creation to let ourselves catch up to "current state"
413 // before subscribing.
414 if !m.subscribed {
415 m.agent.mu.Lock()
416 if m.nextMessageIdx < len(m.agent.history) {
417 msg := &m.agent.history[m.nextMessageIdx]
418 m.nextMessageIdx++
419 m.agent.mu.Unlock()
420 return msg
421 }
422 // The next message doesn't exist yet, so let's subscribe
423 m.agent.subscribers = append(m.agent.subscribers, m.ch)
424 m.subscribed = true
425 m.agent.mu.Unlock()
426 }
427
428 for {
429 select {
430 case <-m.ctx.Done():
431 m.agent.mu.Lock()
432 // Delete ourselves from the subscribers list
433 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
434 return x == m.ch
435 })
436 m.subscribed = false
437 m.agent.mu.Unlock()
438 return nil
439 case msg, ok := <-m.ch:
440 if !ok {
441 // Close may have been called
442 return nil
443 }
444 if msg.Idx == m.nextMessageIdx {
445 m.nextMessageIdx++
446 return msg
447 }
448 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
449 panic("out of order message")
450 }
451 }
452}
453
Sean McCulloughd9d45812025-04-30 16:53:41 -0700454// Assert that Agent satisfies the CodingAgent interface.
455var _ CodingAgent = &Agent{}
456
457// StateName implements CodingAgent.
458func (a *Agent) CurrentStateName() string {
459 if a.stateMachine == nil {
460 return ""
461 }
Josh Bleecher Snydered17fdf2025-05-23 17:26:07 +0000462 return a.stateMachine.CurrentState().String()
Sean McCulloughd9d45812025-04-30 16:53:41 -0700463}
464
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700465// CurrentTodoContent returns the current todo list data as JSON.
466// It returns an empty string if no todos exist.
467func (a *Agent) CurrentTodoContent() string {
468 todoPath := claudetool.TodoFilePath(a.config.SessionID)
469 content, err := os.ReadFile(todoPath)
470 if err != nil {
471 return ""
472 }
473 return string(content)
474}
475
Earl Lee2e463fb2025-04-17 11:22:22 -0700476func (a *Agent) URL() string { return a.url }
477
478// Title returns the current title of the conversation.
479// If no title has been set, returns an empty string.
480func (a *Agent) Title() string {
481 a.mu.Lock()
482 defer a.mu.Unlock()
483 return a.title
484}
485
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000486// BranchName returns the git branch name for the conversation.
487func (a *Agent) BranchName() string {
Philip Zeyligerf2872992025-05-22 10:35:28 -0700488 return a.gitState.BranchName()
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000489}
490
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000491// OutstandingLLMCallCount returns the number of outstanding LLM calls.
492func (a *Agent) OutstandingLLMCallCount() int {
493 a.mu.Lock()
494 defer a.mu.Unlock()
495 return len(a.outstandingLLMCalls)
496}
497
498// OutstandingToolCalls returns the names of outstanding tool calls.
499func (a *Agent) OutstandingToolCalls() []string {
500 a.mu.Lock()
501 defer a.mu.Unlock()
502
503 tools := make([]string, 0, len(a.outstandingToolCalls))
504 for _, toolName := range a.outstandingToolCalls {
505 tools = append(tools, toolName)
506 }
507 return tools
508}
509
Earl Lee2e463fb2025-04-17 11:22:22 -0700510// OS returns the operating system of the client.
511func (a *Agent) OS() string {
512 return a.config.ClientGOOS
513}
514
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000515func (a *Agent) SessionID() string {
516 return a.config.SessionID
517}
518
Philip Zeyliger18532b22025-04-23 21:11:46 +0000519// OutsideOS returns the operating system of the outside system.
520func (a *Agent) OutsideOS() string {
521 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000522}
523
Philip Zeyliger18532b22025-04-23 21:11:46 +0000524// OutsideHostname returns the hostname of the outside system.
525func (a *Agent) OutsideHostname() string {
526 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000527}
528
Philip Zeyliger18532b22025-04-23 21:11:46 +0000529// OutsideWorkingDir returns the working directory on the outside system.
530func (a *Agent) OutsideWorkingDir() string {
531 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000532}
533
534// GitOrigin returns the URL of the git remote 'origin' if it exists.
535func (a *Agent) GitOrigin() string {
536 return a.gitOrigin
537}
538
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000539func (a *Agent) OpenBrowser(url string) {
540 if !a.IsInContainer() {
541 browser.Open(url)
542 return
543 }
544 // We're in Docker, need to send a request to the Git server
545 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700546 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000547 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700548 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000549 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700550 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000551 return
552 }
553 defer resp.Body.Close()
554 if resp.StatusCode == http.StatusOK {
555 return
556 }
557 body, _ := io.ReadAll(resp.Body)
558 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
559}
560
Sean McCullough96b60dd2025-04-30 09:49:10 -0700561// CurrentState returns the current state of the agent's state machine.
562func (a *Agent) CurrentState() State {
563 return a.stateMachine.CurrentState()
564}
565
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700566func (a *Agent) IsInContainer() bool {
567 return a.config.InDocker
568}
569
570func (a *Agent) FirstMessageIndex() int {
571 a.mu.Lock()
572 defer a.mu.Unlock()
573 return a.firstMessageIndex
574}
575
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000576// SetTitle sets the title of the conversation.
577func (a *Agent) SetTitle(title string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700578 a.mu.Lock()
579 defer a.mu.Unlock()
580 a.title = title
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000581}
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700582
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000583// SetBranch sets the branch name of the conversation.
584func (a *Agent) SetBranch(branchName string) {
585 a.mu.Lock()
586 defer a.mu.Unlock()
Philip Zeyligerf2872992025-05-22 10:35:28 -0700587 a.gitState.SetBranchName(branchName)
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000588 convo, ok := a.convo.(*conversation.Convo)
589 if ok {
590 convo.ExtraData["branch"] = branchName
591 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700592}
593
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000594// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700595func (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 +0000596 // Track the tool call
597 a.mu.Lock()
598 a.outstandingToolCalls[id] = toolName
599 a.mu.Unlock()
600}
601
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700602// contentToString converts []llm.Content to a string, concatenating all text content and skipping non-text types.
603// If there's only one element in the array and it's a text type, it returns that text directly.
604// It also processes nested ToolResult arrays recursively.
605func contentToString(contents []llm.Content) string {
606 if len(contents) == 0 {
607 return ""
608 }
609
610 // If there's only one element and it's a text type, return it directly
611 if len(contents) == 1 && contents[0].Type == llm.ContentTypeText {
612 return contents[0].Text
613 }
614
615 // Otherwise, concatenate all text content
616 var result strings.Builder
617 for _, content := range contents {
618 if content.Type == llm.ContentTypeText {
619 result.WriteString(content.Text)
620 } else if content.Type == llm.ContentTypeToolResult && len(content.ToolResult) > 0 {
621 // Recursively process nested tool results
622 result.WriteString(contentToString(content.ToolResult))
623 }
624 }
625
626 return result.String()
627}
628
Earl Lee2e463fb2025-04-17 11:22:22 -0700629// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700630func (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 +0000631 // Remove the tool call from outstanding calls
632 a.mu.Lock()
633 delete(a.outstandingToolCalls, toolID)
634 a.mu.Unlock()
635
Earl Lee2e463fb2025-04-17 11:22:22 -0700636 m := AgentMessage{
637 Type: ToolUseMessageType,
638 Content: content.Text,
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700639 ToolResult: contentToString(content.ToolResult),
Earl Lee2e463fb2025-04-17 11:22:22 -0700640 ToolError: content.ToolError,
641 ToolName: toolName,
642 ToolInput: string(toolInput),
643 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700644 StartTime: content.ToolUseStartTime,
645 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700646 }
647
648 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700649 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
650 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700651 m.Elapsed = &elapsed
652 }
653
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700654 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700655 a.pushToOutbox(ctx, m)
656}
657
658// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700659func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000660 a.mu.Lock()
661 defer a.mu.Unlock()
662 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700663 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
664}
665
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700666// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700667// that need to be displayed (as well as tool calls that we send along when
668// they're done). (It would be reasonable to also mention tool calls when they're
669// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700670func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000671 // Remove the LLM call from outstanding calls
672 a.mu.Lock()
673 delete(a.outstandingLLMCalls, id)
674 a.mu.Unlock()
675
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700676 if resp == nil {
677 // LLM API call failed
678 m := AgentMessage{
679 Type: ErrorMessageType,
680 Content: "API call failed, type 'continue' to try again",
681 }
682 m.SetConvo(convo)
683 a.pushToOutbox(ctx, m)
684 return
685 }
686
Earl Lee2e463fb2025-04-17 11:22:22 -0700687 endOfTurn := false
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700688 if convo.Parent == nil { // subconvos never end the turn
689 switch resp.StopReason {
690 case llm.StopReasonToolUse:
691 // Check whether any of the tool calls are for tools that should end the turn
692 ToolSearch:
693 for _, part := range resp.Content {
694 if part.Type != llm.ContentTypeToolUse {
695 continue
696 }
Sean McCullough021557a2025-05-05 23:20:53 +0000697 // Find the tool by name
698 for _, tool := range convo.Tools {
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700699 if tool.Name == part.ToolName {
700 endOfTurn = tool.EndsTurn
701 break ToolSearch
Sean McCullough021557a2025-05-05 23:20:53 +0000702 }
703 }
Sean McCullough021557a2025-05-05 23:20:53 +0000704 }
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700705 default:
706 endOfTurn = true
Sean McCullough021557a2025-05-05 23:20:53 +0000707 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700708 }
709 m := AgentMessage{
710 Type: AgentMessageType,
711 Content: collectTextContent(resp),
712 EndOfTurn: endOfTurn,
713 Usage: &resp.Usage,
714 StartTime: resp.StartTime,
715 EndTime: resp.EndTime,
716 }
717
718 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700719 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700720 var toolCalls []ToolCall
721 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700722 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700723 toolCalls = append(toolCalls, ToolCall{
724 Name: part.ToolName,
725 Input: string(part.ToolInput),
726 ToolCallId: part.ID,
727 })
728 }
729 }
730 m.ToolCalls = toolCalls
731 }
732
733 // Calculate the elapsed time if both start and end times are set
734 if resp.StartTime != nil && resp.EndTime != nil {
735 elapsed := resp.EndTime.Sub(*resp.StartTime)
736 m.Elapsed = &elapsed
737 }
738
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700739 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700740 a.pushToOutbox(ctx, m)
741}
742
743// WorkingDir implements CodingAgent.
744func (a *Agent) WorkingDir() string {
745 return a.workingDir
746}
747
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +0000748// RepoRoot returns the git repository root directory.
749func (a *Agent) RepoRoot() string {
750 return a.repoRoot
751}
752
Earl Lee2e463fb2025-04-17 11:22:22 -0700753// MessageCount implements CodingAgent.
754func (a *Agent) MessageCount() int {
755 a.mu.Lock()
756 defer a.mu.Unlock()
757 return len(a.history)
758}
759
760// Messages implements CodingAgent.
761func (a *Agent) Messages(start int, end int) []AgentMessage {
762 a.mu.Lock()
763 defer a.mu.Unlock()
764 return slices.Clone(a.history[start:end])
765}
766
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700767func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700768 return a.originalBudget
769}
770
771// AgentConfig contains configuration for creating a new Agent.
772type AgentConfig struct {
773 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700774 Service llm.Service
775 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700776 GitUsername string
777 GitEmail string
778 SessionID string
779 ClientGOOS string
780 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700781 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700782 UseAnthropicEdit bool
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000783 OneShot bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700784 WorkingDir string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000785 // Outside information
786 OutsideHostname string
787 OutsideOS string
788 OutsideWorkingDir string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700789
790 // Outtie's HTTP to, e.g., open a browser
791 OutsideHTTP string
792 // Outtie's Git server
793 GitRemoteAddr string
794 // Commit to checkout from Outtie
795 Commit string
Earl Lee2e463fb2025-04-17 11:22:22 -0700796}
797
798// NewAgent creates a new Agent.
799// It is not usable until Init() is called.
800func NewAgent(config AgentConfig) *Agent {
801 agent := &Agent{
Philip Zeyligerf2872992025-05-22 10:35:28 -0700802 config: config,
803 ready: make(chan struct{}),
804 inbox: make(chan string, 100),
805 subscribers: make([]chan *AgentMessage, 0),
806 startedAt: time.Now(),
807 originalBudget: config.Budget,
808 gitState: AgentGitState{
809 seenCommits: make(map[string]bool),
810 gitRemoteAddr: config.GitRemoteAddr,
811 },
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000812 outsideHostname: config.OutsideHostname,
813 outsideOS: config.OutsideOS,
814 outsideWorkingDir: config.OutsideWorkingDir,
815 outstandingLLMCalls: make(map[string]struct{}),
816 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700817 stateMachine: NewStateMachine(),
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700818 workingDir: config.WorkingDir,
819 outsideHTTP: config.OutsideHTTP,
Earl Lee2e463fb2025-04-17 11:22:22 -0700820 }
821 return agent
822}
823
824type AgentInit struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700825 NoGit bool // only for testing
Earl Lee2e463fb2025-04-17 11:22:22 -0700826
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700827 InDocker bool
828 HostAddr string
Earl Lee2e463fb2025-04-17 11:22:22 -0700829}
830
831func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700832 if a.convo != nil {
833 return fmt.Errorf("Agent.Init: already initialized")
834 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700835 ctx := a.config.Context
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700836 slog.InfoContext(ctx, "agent initializing")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700837
Philip Zeyligerf2872992025-05-22 10:35:28 -0700838 // If a remote git addr was specified, we configure the remote
839 if a.gitState.gitRemoteAddr != "" {
840 slog.InfoContext(ctx, "Configuring git remote", slog.String("remote", a.gitState.gitRemoteAddr))
841 cmd := exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", a.gitState.gitRemoteAddr)
842 cmd.Dir = a.workingDir
843 if out, err := cmd.CombinedOutput(); err != nil {
844 return fmt.Errorf("git remote add: %s: %v", out, err)
845 }
846 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
847 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
848 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
849 // origin/main on outtie sketch, which should make it easier to rebase.
850 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
851 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
852 cmd.Dir = a.workingDir
853 if out, err := cmd.CombinedOutput(); err != nil {
854 return fmt.Errorf("git config --add: %s: %v", out, err)
855 }
856 }
857
858 // If a commit was specified, we fetch and reset to it.
859 if a.config.Commit != "" && a.gitState.gitRemoteAddr != "" {
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700860 slog.InfoContext(ctx, "updating git repo", slog.String("commit", a.config.Commit))
861
Earl Lee2e463fb2025-04-17 11:22:22 -0700862 cmd := exec.CommandContext(ctx, "git", "stash")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700863 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700864 if out, err := cmd.CombinedOutput(); err != nil {
865 return fmt.Errorf("git stash: %s: %v", out, err)
866 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000867 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700868 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700869 if out, err := cmd.CombinedOutput(); err != nil {
870 return fmt.Errorf("git fetch: %s: %w", out, err)
871 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700872 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
873 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100874 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
875 // Remove git hooks if they exist and retry
876 // Only try removing hooks if we haven't already removed them during fetch
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700877 hookPath := filepath.Join(a.workingDir, ".git", "hooks")
Pokey Rule7a113622025-05-12 10:58:45 +0100878 if _, statErr := os.Stat(hookPath); statErr == nil {
879 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
880 slog.String("error", err.Error()),
881 slog.String("output", string(checkoutOut)))
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700882 if removeErr := removeGitHooks(ctx, a.workingDir); removeErr != nil {
Pokey Rule7a113622025-05-12 10:58:45 +0100883 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
884 }
885
886 // Retry the checkout operation
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700887 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
888 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100889 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700890 return fmt.Errorf("git checkout %s failed even after removing hooks: %s: %w", a.config.Commit, retryOut, retryErr)
Pokey Rule7a113622025-05-12 10:58:45 +0100891 }
892 } else {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700893 return fmt.Errorf("git checkout %s: %s: %w", a.config.Commit, checkoutOut, err)
Pokey Rule7a113622025-05-12 10:58:45 +0100894 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700895 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700896 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700897
898 if ini.HostAddr != "" {
899 a.url = "http://" + ini.HostAddr
900 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700901
902 if !ini.NoGit {
903 repoRoot, err := repoRoot(ctx, a.workingDir)
904 if err != nil {
905 return fmt.Errorf("repoRoot: %w", err)
906 }
907 a.repoRoot = repoRoot
908
Earl Lee2e463fb2025-04-17 11:22:22 -0700909 if err != nil {
910 return fmt.Errorf("resolveRef: %w", err)
911 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700912
Josh Bleecher Snyder90993a02025-05-28 18:15:15 -0700913 if err := setupGitHooks(a.repoRoot); err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700914 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
915 }
916
Philip Zeyliger49edc922025-05-14 09:45:45 -0700917 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
918 cmd.Dir = repoRoot
919 if out, err := cmd.CombinedOutput(); err != nil {
920 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
921 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700922
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000923 slog.Info("running codebase analysis")
924 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
925 if err != nil {
926 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000927 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000928 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000929
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +0000930 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -0700931 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000932 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700933 }
934 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000935
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700936 a.gitOrigin = getGitOrigin(ctx, a.workingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700937 }
Philip Zeyligerf2872992025-05-22 10:35:28 -0700938 a.gitState.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700939 a.convo = a.initConvo()
940 close(a.ready)
941 return nil
942}
943
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700944//go:embed agent_system_prompt.txt
945var agentSystemPrompt string
946
Earl Lee2e463fb2025-04-17 11:22:22 -0700947// initConvo initializes the conversation.
948// It must not be called until all agent fields are initialized,
949// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700950func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700951 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700952 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700953 convo.PromptCaching = true
954 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000955 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000956 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700957
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000958 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
959 bashPermissionCheck := func(command string) error {
960 // Check if branch name is set
961 a.mu.Lock()
Philip Zeyligerf2872992025-05-22 10:35:28 -0700962 branchSet := a.gitState.BranchName() != ""
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000963 a.mu.Unlock()
964
965 // If branch is set, all commands are allowed
966 if branchSet {
967 return nil
968 }
969
970 // If branch is not set, check if this is a git commit command
971 willCommit, err := bashkit.WillRunGitCommit(command)
972 if err != nil {
973 // If there's an error checking, we should allow the command to proceed
974 return nil
975 }
976
977 // If it's a git commit and branch is not set, return an error
978 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000979 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000980 }
981
982 return nil
983 }
984
985 // Create a custom bash tool with the permission check
986 bashTool := claudetool.NewBashTool(bashPermissionCheck)
987
Earl Lee2e463fb2025-04-17 11:22:22 -0700988 // Register all tools with the conversation
989 // When adding, removing, or modifying tools here, double-check that the termui tool display
990 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000991
992 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700993 _, supportsScreenshots := a.config.Service.(*ant.Service)
994 var bTools []*llm.Tool
995 var browserCleanup func()
996
997 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
998 // Add cleanup function to context cancel
999 go func() {
1000 <-a.config.Context.Done()
1001 browserCleanup()
1002 }()
1003 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001004
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001005 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001006 bashTool, claudetool.Keyword,
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001007 claudetool.Think, claudetool.TodoRead, claudetool.TodoWrite, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -07001008 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +00001009 }
1010
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +00001011 // One-shot mode is non-interactive, multiple choice requires human response
1012 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001013 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -07001014 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001015
1016 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -07001017 if a.config.UseAnthropicEdit {
1018 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
1019 } else {
1020 convo.Tools = append(convo.Tools, claudetool.Patch)
1021 }
1022 convo.Listener = a
1023 return convo
1024}
1025
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001026var multipleChoiceTool = &llm.Tool{
1027 Name: "multiplechoice",
1028 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.",
1029 EndsTurn: true,
1030 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001031 "type": "object",
1032 "description": "The question and a list of answers you would expect the user to choose from.",
1033 "properties": {
1034 "question": {
1035 "type": "string",
1036 "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?'"
1037 },
1038 "responseOptions": {
1039 "type": "array",
1040 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1041 "items": {
1042 "type": "object",
1043 "properties": {
1044 "caption": {
1045 "type": "string",
1046 "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'"
1047 },
1048 "responseText": {
1049 "type": "string",
1050 "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'"
1051 }
1052 },
1053 "required": ["caption", "responseText"]
1054 }
1055 }
1056 },
1057 "required": ["question", "responseOptions"]
1058}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001059 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1060 // The Run logic for "multiplechoice" tool is a no-op on the server.
1061 // The UI will present a list of options for the user to select from,
1062 // and that's it as far as "executing" the tool_use goes.
1063 // When the user *does* select one of the presented options, that
1064 // responseText gets sent as a chat message on behalf of the user.
1065 return llm.TextContent("end your turn and wait for the user to respond"), nil
1066 },
Sean McCullough485afc62025-04-28 14:28:39 -07001067}
1068
1069type MultipleChoiceOption struct {
1070 Caption string `json:"caption"`
1071 ResponseText string `json:"responseText"`
1072}
1073
1074type MultipleChoiceParams struct {
1075 Question string `json:"question"`
1076 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1077}
1078
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001079// branchExists reports whether branchName exists, either locally or in well-known remotes.
1080func branchExists(dir, branchName string) bool {
1081 refs := []string{
1082 "refs/heads/",
1083 "refs/remotes/origin/",
1084 "refs/remotes/sketch-host/",
1085 }
1086 for _, ref := range refs {
1087 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1088 cmd.Dir = dir
1089 if cmd.Run() == nil { // exit code 0 means branch exists
1090 return true
1091 }
1092 }
1093 return false
1094}
1095
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001096func (a *Agent) titleTool() *llm.Tool {
1097 description := `Sets the conversation title.`
1098 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001099 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001100 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001101 InputSchema: json.RawMessage(`{
1102 "type": "object",
1103 "properties": {
1104 "title": {
1105 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001106 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001107 }
1108 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001109 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001110}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001111 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001112 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001113 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001114 }
1115 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001116 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001117 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001118
1119 // We don't allow changing the title once set to be consistent with the previous behavior
1120 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001121 t := a.Title()
1122 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001123 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001124 }
1125
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001126 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001127 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001128 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001129
1130 a.SetTitle(params.Title)
1131 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001132 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001133 },
1134 }
1135 return titleTool
1136}
1137
1138func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001139 description := `Creates a git branch for tracking work and provides git commit message style guidance. MANDATORY: You must use this tool before making any git commits.`
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001140 preCommit := &llm.Tool{
1141 Name: "precommit",
1142 Description: description,
1143 InputSchema: json.RawMessage(`{
1144 "type": "object",
1145 "properties": {
1146 "branch_name": {
1147 "type": "string",
1148 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1149 }
1150 },
1151 "required": ["branch_name"]
1152}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001153 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001154 var params struct {
1155 BranchName string `json:"branch_name"`
1156 }
1157 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001158 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001159 }
1160
1161 b := a.BranchName()
1162 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001163 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001164 }
1165
1166 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001167 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001168 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001169 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001170 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001171 }
1172 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001173 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001174 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001175 }
1176
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001177 a.SetBranch(branchName)
Josh Bleecher Snyderf7bebdd2025-05-14 15:22:24 -07001178 response := fmt.Sprintf("switched to branch sketch/%q - DO NOT change branches unless explicitly requested", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001179
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001180 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1181 if err != nil {
1182 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1183 }
1184 if len(styleHint) > 0 {
1185 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001186 }
1187
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001188 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001189 },
1190 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001191 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001192}
1193
1194func (a *Agent) Ready() <-chan struct{} {
1195 return a.ready
1196}
1197
1198func (a *Agent) UserMessage(ctx context.Context, msg string) {
1199 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1200 a.inbox <- msg
1201}
1202
Earl Lee2e463fb2025-04-17 11:22:22 -07001203func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1204 return a.convo.CancelToolUse(toolUseID, cause)
1205}
1206
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001207func (a *Agent) CancelTurn(cause error) {
1208 a.cancelTurnMu.Lock()
1209 defer a.cancelTurnMu.Unlock()
1210 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001211 // Force state transition to cancelled state
1212 ctx := a.config.Context
1213 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001214 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001215 }
1216}
1217
1218func (a *Agent) Loop(ctxOuter context.Context) {
1219 for {
1220 select {
1221 case <-ctxOuter.Done():
1222 return
1223 default:
1224 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001225 a.cancelTurnMu.Lock()
1226 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001227 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001228 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001229 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001230 a.cancelTurn = cancel
1231 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001232 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1233 if err != nil {
1234 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1235 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001236 cancel(nil)
1237 }
1238 }
1239}
1240
1241func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1242 if m.Timestamp.IsZero() {
1243 m.Timestamp = time.Now()
1244 }
1245
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001246 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1247 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1248 m.Content = m.ToolResult
1249 }
1250
Earl Lee2e463fb2025-04-17 11:22:22 -07001251 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1252 if m.EndOfTurn && m.Type == AgentMessageType {
1253 turnDuration := time.Since(a.startOfTurn)
1254 m.TurnDuration = &turnDuration
1255 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1256 }
1257
Earl Lee2e463fb2025-04-17 11:22:22 -07001258 a.mu.Lock()
1259 defer a.mu.Unlock()
1260 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001261 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001262 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001263
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001264 // Notify all subscribers
1265 for _, ch := range a.subscribers {
1266 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001267 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001268}
1269
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001270func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1271 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001272 if block {
1273 select {
1274 case <-ctx.Done():
1275 return m, ctx.Err()
1276 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001277 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001278 }
1279 }
1280 for {
1281 select {
1282 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001283 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001284 default:
1285 return m, nil
1286 }
1287 }
1288}
1289
Sean McCullough885a16a2025-04-30 02:49:25 +00001290// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001291func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001292 // Reset the start of turn time
1293 a.startOfTurn = time.Now()
1294
Sean McCullough96b60dd2025-04-30 09:49:10 -07001295 // Transition to waiting for user input state
1296 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1297
Sean McCullough885a16a2025-04-30 02:49:25 +00001298 // Process initial user message
1299 initialResp, err := a.processUserMessage(ctx)
1300 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001301 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001302 return err
1303 }
1304
1305 // Handle edge case where both initialResp and err are nil
1306 if initialResp == nil {
1307 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001308 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1309
Sean McCullough9f4b8082025-04-30 17:34:07 +00001310 a.pushToOutbox(ctx, errorMessage(err))
1311 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001312 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001313
Earl Lee2e463fb2025-04-17 11:22:22 -07001314 // We do this as we go, but let's also do it at the end of the turn
1315 defer func() {
1316 if _, err := a.handleGitCommits(ctx); err != nil {
1317 // Just log the error, don't stop execution
1318 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1319 }
1320 }()
1321
Sean McCullougha1e0e492025-05-01 10:51:08 -07001322 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001323 resp := initialResp
1324 for {
1325 // Check if we are over budget
1326 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001327 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001328 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001329 }
1330
1331 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001332 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001333 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001334 break
1335 }
1336
Sean McCullough96b60dd2025-04-30 09:49:10 -07001337 // Transition to tool use requested state
1338 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1339
Sean McCullough885a16a2025-04-30 02:49:25 +00001340 // Handle tool execution
1341 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1342 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001343 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001344 }
1345
Sean McCullougha1e0e492025-05-01 10:51:08 -07001346 if toolResp == nil {
1347 return fmt.Errorf("cannot continue conversation with a nil tool response")
1348 }
1349
Sean McCullough885a16a2025-04-30 02:49:25 +00001350 // Set the response for the next iteration
1351 resp = toolResp
1352 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001353
1354 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001355}
1356
1357// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001358func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001359 // Wait for at least one message from the user
1360 msgs, err := a.GatherMessages(ctx, true)
1361 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001362 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001363 return nil, err
1364 }
1365
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001366 userMessage := llm.Message{
1367 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001368 Content: msgs,
1369 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001370
Sean McCullough96b60dd2025-04-30 09:49:10 -07001371 // Transition to sending to LLM state
1372 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1373
Sean McCullough885a16a2025-04-30 02:49:25 +00001374 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001375 resp, err := a.convo.SendMessage(userMessage)
1376 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001377 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001378 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001379 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001380 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001381
Sean McCullough96b60dd2025-04-30 09:49:10 -07001382 // Transition to processing LLM response state
1383 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1384
Sean McCullough885a16a2025-04-30 02:49:25 +00001385 return resp, nil
1386}
1387
1388// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001389func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1390 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001391 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001392 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001393
Sean McCullough96b60dd2025-04-30 09:49:10 -07001394 // Transition to checking for cancellation state
1395 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1396
Sean McCullough885a16a2025-04-30 02:49:25 +00001397 // Check if the operation was cancelled by the user
1398 select {
1399 case <-ctx.Done():
1400 // Don't actually run any of the tools, but rather build a response
1401 // for each tool_use message letting the LLM know that user canceled it.
1402 var err error
1403 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001404 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001405 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001406 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001407 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001408 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001409 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001410 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001411 // Transition to running tool state
1412 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1413
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001414 // Add working directory and session ID to context for tool execution
Sean McCullough885a16a2025-04-30 02:49:25 +00001415 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001416 ctx = claudetool.WithSessionID(ctx, a.config.SessionID)
Sean McCullough885a16a2025-04-30 02:49:25 +00001417
1418 // Execute the tools
1419 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001420 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001421 if ctx.Err() != nil { // e.g. the user canceled the operation
1422 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001423 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001424 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001425 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001426 a.pushToOutbox(ctx, errorMessage(err))
1427 }
1428 }
1429
1430 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001431 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001432 autoqualityMessages := a.processGitChanges(ctx)
1433
1434 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001435 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001436 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001437 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001438 return false, nil
1439 }
1440
1441 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001442 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1443 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001444}
1445
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001446// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001447func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001448 // Check for git commits
1449 _, err := a.handleGitCommits(ctx)
1450 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001451 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001452 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001453 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001454 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001455}
1456
1457// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1458// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001459func (a *Agent) processGitChanges(ctx context.Context) []string {
1460 // Check for git commits after tool execution
1461 newCommits, err := a.handleGitCommits(ctx)
1462 if err != nil {
1463 // Just log the error, don't stop execution
1464 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1465 return nil
1466 }
1467
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001468 // Run mechanical checks if there was exactly one new commit.
1469 if len(newCommits) != 1 {
1470 return nil
1471 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001472 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001473 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1474 msg := a.codereview.RunMechanicalChecks(ctx)
1475 if msg != "" {
1476 a.pushToOutbox(ctx, AgentMessage{
1477 Type: AutoMessageType,
1478 Content: msg,
1479 Timestamp: time.Now(),
1480 })
1481 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001482 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001483
1484 return autoqualityMessages
1485}
1486
1487// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001488func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001489 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001490 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001491 msgs, err := a.GatherMessages(ctx, false)
1492 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001493 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001494 return false, nil
1495 }
1496
1497 // Inject any auto-generated messages from quality checks
1498 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001499 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001500 }
1501
1502 // Handle cancellation by appending a message about it
1503 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001504 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001505 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001506 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001507 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1508 } else if err := a.convo.OverBudget(); err != nil {
1509 // Handle budget issues by appending a message about it
1510 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 -07001511 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001512 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1513 }
1514
1515 // Combine tool results with user messages
1516 results = append(results, msgs...)
1517
1518 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001519 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001520 resp, err := a.convo.SendMessage(llm.Message{
1521 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001522 Content: results,
1523 })
1524 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001525 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001526 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1527 return true, nil // Return true to continue the conversation, but with no response
1528 }
1529
Sean McCullough96b60dd2025-04-30 09:49:10 -07001530 // Transition back to processing LLM response
1531 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1532
Sean McCullough885a16a2025-04-30 02:49:25 +00001533 if cancelled {
1534 return false, nil
1535 }
1536
1537 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001538}
1539
1540func (a *Agent) overBudget(ctx context.Context) error {
1541 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001542 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001543 m := budgetMessage(err)
1544 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001545 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001546 a.convo.ResetBudget(a.originalBudget)
1547 return err
1548 }
1549 return nil
1550}
1551
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001552func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001553 // Collect all text content
1554 var allText strings.Builder
1555 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001556 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001557 if allText.Len() > 0 {
1558 allText.WriteString("\n\n")
1559 }
1560 allText.WriteString(content.Text)
1561 }
1562 }
1563 return allText.String()
1564}
1565
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001566func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001567 a.mu.Lock()
1568 defer a.mu.Unlock()
1569 return a.convo.CumulativeUsage()
1570}
1571
Earl Lee2e463fb2025-04-17 11:22:22 -07001572// Diff returns a unified diff of changes made since the agent was instantiated.
1573func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001574 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001575 return "", fmt.Errorf("no initial commit reference available")
1576 }
1577
1578 // Find the repository root
1579 ctx := context.Background()
1580
1581 // If a specific commit hash is provided, show just that commit's changes
1582 if commit != nil && *commit != "" {
1583 // Validate that the commit looks like a valid git SHA
1584 if !isValidGitSHA(*commit) {
1585 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1586 }
1587
1588 // Get the diff for just this commit
1589 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1590 cmd.Dir = a.repoRoot
1591 output, err := cmd.CombinedOutput()
1592 if err != nil {
1593 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1594 }
1595 return string(output), nil
1596 }
1597
1598 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001599 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001600 cmd.Dir = a.repoRoot
1601 output, err := cmd.CombinedOutput()
1602 if err != nil {
1603 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1604 }
1605
1606 return string(output), nil
1607}
1608
Philip Zeyliger49edc922025-05-14 09:45:45 -07001609// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1610// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1611func (a *Agent) SketchGitBaseRef() string {
1612 if a.IsInContainer() {
1613 return "sketch-base"
1614 } else {
1615 return "sketch-base-" + a.SessionID()
1616 }
1617}
1618
1619// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1620func (a *Agent) SketchGitBase() string {
1621 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1622 cmd.Dir = a.repoRoot
1623 output, err := cmd.CombinedOutput()
1624 if err != nil {
1625 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1626 return "HEAD"
1627 }
1628 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001629}
1630
Pokey Rule7a113622025-05-12 10:58:45 +01001631// removeGitHooks removes the Git hooks directory from the repository
1632func removeGitHooks(_ context.Context, repoPath string) error {
1633 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1634
1635 // Check if hooks directory exists
1636 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1637 // Directory doesn't exist, nothing to do
1638 return nil
1639 }
1640
1641 // Remove the hooks directory
1642 err := os.RemoveAll(hooksDir)
1643 if err != nil {
1644 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1645 }
1646
1647 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001648 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001649 if err != nil {
1650 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1651 }
1652
1653 return nil
1654}
1655
Philip Zeyligerf2872992025-05-22 10:35:28 -07001656func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1657 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef())
1658 for _, msg := range msgs {
1659 a.pushToOutbox(ctx, msg)
1660 }
1661 return commits, error
1662}
1663
Earl Lee2e463fb2025-04-17 11:22:22 -07001664// handleGitCommits() highlights new commits to the user. When running
1665// under docker, new HEADs are pushed to a branch according to the title.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001666func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string) ([]AgentMessage, []*GitCommit, error) {
1667 ags.mu.Lock()
1668 defer ags.mu.Unlock()
1669
1670 msgs := []AgentMessage{}
1671 if repoRoot == "" {
1672 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001673 }
1674
Philip Zeyligerf2872992025-05-22 10:35:28 -07001675 head, err := resolveRef(ctx, repoRoot, "HEAD")
Earl Lee2e463fb2025-04-17 11:22:22 -07001676 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001677 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001678 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001679 if head == ags.lastHEAD {
1680 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001681 }
1682 defer func() {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001683 ags.lastHEAD = head
Earl Lee2e463fb2025-04-17 11:22:22 -07001684 }()
1685
1686 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1687 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1688 // to the last 100 commits.
1689 var commits []*GitCommit
1690
1691 // Get commits since the initial commit
1692 // Format: <hash>\0<subject>\0<body>\0
1693 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1694 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyligerf2872992025-05-22 10:35:28 -07001695 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+baseRef, head)
1696 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07001697 output, err := cmd.Output()
1698 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001699 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07001700 }
1701
1702 // Parse git log output and filter out already seen commits
1703 parsedCommits := parseGitLog(string(output))
1704
1705 var headCommit *GitCommit
1706
1707 // Filter out commits we've already seen
1708 for _, commit := range parsedCommits {
1709 if commit.Hash == head {
1710 headCommit = &commit
1711 }
1712
1713 // Skip if we've seen this commit before. If our head has changed, always include that.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001714 if ags.seenCommits[commit.Hash] && commit.Hash != head {
Earl Lee2e463fb2025-04-17 11:22:22 -07001715 continue
1716 }
1717
1718 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07001719 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07001720
1721 // Add to our list of new commits
1722 commits = append(commits, &commit)
1723 }
1724
Philip Zeyligerf2872992025-05-22 10:35:28 -07001725 if ags.gitRemoteAddr != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001726 if headCommit == nil {
1727 // I think this can only happen if we have a bug or if there's a race.
1728 headCommit = &GitCommit{}
1729 headCommit.Hash = head
1730 headCommit.Subject = "unknown"
1731 commits = append(commits, headCommit)
1732 }
1733
Philip Zeyligerf2872992025-05-22 10:35:28 -07001734 originalBranch := cmp.Or(ags.branchName, "sketch/"+sessionID)
Philip Zeyliger113e2052025-05-09 21:59:40 +00001735 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001736
1737 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1738 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1739 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001740
1741 // Try up to 10 times with different branch names if the branch is checked out on the remote
1742 var out []byte
1743 var err error
1744 for retries := range 10 {
1745 if retries > 0 {
1746 // Add a numeric suffix to the branch name
1747 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1748 }
1749
Philip Zeyligerf2872992025-05-22 10:35:28 -07001750 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1751 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00001752 out, err = cmd.CombinedOutput()
1753
1754 if err == nil {
1755 // Success! Break out of the retry loop
1756 break
1757 }
1758
1759 // Check if this is the "refusing to update checked out branch" error
1760 if !strings.Contains(string(out), "refusing to update checked out branch") {
1761 // This is a different error, so don't retry
1762 break
1763 }
1764
1765 // If we're on the last retry, we'll report the error
1766 if retries == 9 {
1767 break
1768 }
1769 }
1770
1771 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001772 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001773 } else {
1774 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001775 // Update the agent's branch name if we ended up using a different one
1776 if branch != originalBranch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001777 ags.branchName = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001778 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001779 }
1780 }
1781
1782 // If we found new commits, create a message
1783 if len(commits) > 0 {
1784 msg := AgentMessage{
1785 Type: CommitMessageType,
1786 Timestamp: time.Now(),
1787 Commits: commits,
1788 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001789 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001790 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001791 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001792}
1793
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001794func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001795 return strings.Map(func(r rune) rune {
1796 // lowercase
1797 if r >= 'A' && r <= 'Z' {
1798 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001799 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001800 // replace spaces with dashes
1801 if r == ' ' {
1802 return '-'
1803 }
1804 // allow alphanumerics and dashes
1805 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1806 return r
1807 }
1808 return -1
1809 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001810}
1811
1812// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1813// and returns an array of GitCommit structs.
1814func parseGitLog(output string) []GitCommit {
1815 var commits []GitCommit
1816
1817 // No output means no commits
1818 if len(output) == 0 {
1819 return commits
1820 }
1821
1822 // Split by NULL byte
1823 parts := strings.Split(output, "\x00")
1824
1825 // Process in triplets (hash, subject, body)
1826 for i := 0; i < len(parts); i++ {
1827 // Skip empty parts
1828 if parts[i] == "" {
1829 continue
1830 }
1831
1832 // This should be a hash
1833 hash := strings.TrimSpace(parts[i])
1834
1835 // Make sure we have at least a subject part available
1836 if i+1 >= len(parts) {
1837 break // No more parts available
1838 }
1839
1840 // Get the subject
1841 subject := strings.TrimSpace(parts[i+1])
1842
1843 // Get the body if available
1844 body := ""
1845 if i+2 < len(parts) {
1846 body = strings.TrimSpace(parts[i+2])
1847 }
1848
1849 // Skip to the next triplet
1850 i += 2
1851
1852 commits = append(commits, GitCommit{
1853 Hash: hash,
1854 Subject: subject,
1855 Body: body,
1856 })
1857 }
1858
1859 return commits
1860}
1861
1862func repoRoot(ctx context.Context, dir string) (string, error) {
1863 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1864 stderr := new(strings.Builder)
1865 cmd.Stderr = stderr
1866 cmd.Dir = dir
1867 out, err := cmd.Output()
1868 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001869 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07001870 }
1871 return strings.TrimSpace(string(out)), nil
1872}
1873
1874func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1875 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1876 stderr := new(strings.Builder)
1877 cmd.Stderr = stderr
1878 cmd.Dir = dir
1879 out, err := cmd.Output()
1880 if err != nil {
1881 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1882 }
1883 // TODO: validate that out is valid hex
1884 return strings.TrimSpace(string(out)), nil
1885}
1886
1887// isValidGitSHA validates if a string looks like a valid git SHA hash.
1888// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1889func isValidGitSHA(sha string) bool {
1890 // Git SHA must be a hexadecimal string with at least 4 characters
1891 if len(sha) < 4 || len(sha) > 40 {
1892 return false
1893 }
1894
1895 // Check if the string only contains hexadecimal characters
1896 for _, char := range sha {
1897 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1898 return false
1899 }
1900 }
1901
1902 return true
1903}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001904
1905// getGitOrigin returns the URL of the git remote 'origin' if it exists
1906func getGitOrigin(ctx context.Context, dir string) string {
1907 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1908 cmd.Dir = dir
1909 stderr := new(strings.Builder)
1910 cmd.Stderr = stderr
1911 out, err := cmd.Output()
1912 if err != nil {
1913 return ""
1914 }
1915 return strings.TrimSpace(string(out))
1916}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001917
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001918// systemPromptData contains the data used to render the system prompt template
1919type systemPromptData struct {
1920 EditPrompt string
1921 ClientGOOS string
1922 ClientGOARCH string
1923 WorkingDir string
1924 RepoRoot string
1925 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001926 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001927}
1928
1929// renderSystemPrompt renders the system prompt template.
1930func (a *Agent) renderSystemPrompt() string {
1931 // Determine the appropriate edit prompt based on config
1932 var editPrompt string
1933 if a.config.UseAnthropicEdit {
1934 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."
1935 } else {
1936 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
1937 }
1938
1939 data := systemPromptData{
1940 EditPrompt: editPrompt,
1941 ClientGOOS: a.config.ClientGOOS,
1942 ClientGOARCH: a.config.ClientGOARCH,
1943 WorkingDir: a.workingDir,
1944 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07001945 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001946 Codebase: a.codebase,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001947 }
1948
1949 tmpl, err := template.New("system").Parse(agentSystemPrompt)
1950 if err != nil {
1951 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
1952 }
1953 buf := new(strings.Builder)
1954 err = tmpl.Execute(buf, data)
1955 if err != nil {
1956 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
1957 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001958 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001959 return buf.String()
1960}
Philip Zeyligereab12de2025-05-14 02:35:53 +00001961
1962// StateTransitionIterator provides an iterator over state transitions.
1963type StateTransitionIterator interface {
1964 // Next blocks until a new state transition is available or context is done.
1965 // Returns nil if the context is cancelled.
1966 Next() *StateTransition
1967 // Close removes the listener and cleans up resources.
1968 Close()
1969}
1970
1971// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
1972type StateTransitionIteratorImpl struct {
1973 agent *Agent
1974 ctx context.Context
1975 ch chan StateTransition
1976 unsubscribe func()
1977}
1978
1979// Next blocks until a new state transition is available or the context is cancelled.
1980func (s *StateTransitionIteratorImpl) Next() *StateTransition {
1981 select {
1982 case <-s.ctx.Done():
1983 return nil
1984 case transition, ok := <-s.ch:
1985 if !ok {
1986 return nil
1987 }
1988 transitionCopy := transition
1989 return &transitionCopy
1990 }
1991}
1992
1993// Close removes the listener and cleans up resources.
1994func (s *StateTransitionIteratorImpl) Close() {
1995 if s.unsubscribe != nil {
1996 s.unsubscribe()
1997 s.unsubscribe = nil
1998 }
1999}
2000
2001// NewStateTransitionIterator returns an iterator that receives state transitions.
2002func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2003 a.mu.Lock()
2004 defer a.mu.Unlock()
2005
2006 // Create channel to receive state transitions
2007 ch := make(chan StateTransition, 10)
2008
2009 // Add a listener to the state machine
2010 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2011
2012 return &StateTransitionIteratorImpl{
2013 agent: a,
2014 ctx: ctx,
2015 ch: ch,
2016 unsubscribe: unsubscribe,
2017 }
2018}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002019
2020// setupGitHooks creates or updates git hooks in the specified working directory.
2021func setupGitHooks(workingDir string) error {
2022 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2023
2024 _, err := os.Stat(hooksDir)
2025 if os.IsNotExist(err) {
2026 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2027 }
2028 if err != nil {
2029 return fmt.Errorf("error checking git hooks directory: %w", err)
2030 }
2031
2032 // Define the post-commit hook content
2033 postCommitHook := `#!/bin/bash
2034echo "<post_commit_hook>"
2035echo "Please review this commit message and fix it if it is incorrect."
2036echo "This hook only echos the commit message; it does not modify it."
2037echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2038echo "<last_commit_message>"
2039git log -1 --pretty=%B
2040echo "</last_commit_message>"
2041echo "</post_commit_hook>"
2042`
2043
2044 // Define the prepare-commit-msg hook content
2045 prepareCommitMsgHook := `#!/bin/bash
2046# Add Co-Authored-By and Change-ID trailers to commit messages
2047# Check if these trailers already exist before adding them
2048
2049commit_file="$1"
2050COMMIT_SOURCE="$2"
2051
2052# Skip for merges, squashes, or when using a commit template
2053if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2054 [ "$COMMIT_SOURCE" = "squash" ]; then
2055 exit 0
2056fi
2057
2058commit_msg=$(cat "$commit_file")
2059
2060needs_co_author=true
2061needs_change_id=true
2062
2063# Check if commit message already has Co-Authored-By trailer
2064if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2065 needs_co_author=false
2066fi
2067
2068# Check if commit message already has Change-ID trailer
2069if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2070 needs_change_id=false
2071fi
2072
2073# Only modify if at least one trailer needs to be added
2074if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
Josh Bleecher Snyderb509a5d2025-05-23 15:49:42 +00002075 # Ensure there's a proper blank line before trailers
2076 if [ -s "$commit_file" ]; then
2077 # Check if file ends with newline by reading last character
2078 last_char=$(tail -c 1 "$commit_file")
2079
2080 if [ "$last_char" != "" ]; then
2081 # File doesn't end with newline - add two newlines (complete line + blank line)
2082 echo "" >> "$commit_file"
2083 echo "" >> "$commit_file"
2084 else
2085 # File ends with newline - check if we already have a blank line
2086 last_line=$(tail -1 "$commit_file")
2087 if [ -n "$last_line" ]; then
2088 # Last line has content - add one newline for blank line
2089 echo "" >> "$commit_file"
2090 fi
2091 # If last line is empty, we already have a blank line - don't add anything
2092 fi
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002093 fi
2094
2095 # Add trailers if needed
2096 if [ "$needs_co_author" = true ]; then
2097 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2098 fi
2099
2100 if [ "$needs_change_id" = true ]; then
2101 change_id=$(openssl rand -hex 8)
2102 echo "Change-ID: s${change_id}k" >> "$commit_file"
2103 fi
2104fi
2105`
2106
2107 // Update or create the post-commit hook
2108 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2109 if err != nil {
2110 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2111 }
2112
2113 // Update or create the prepare-commit-msg hook
2114 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2115 if err != nil {
2116 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2117 }
2118
2119 return nil
2120}
2121
2122// updateOrCreateHook creates a new hook file or updates an existing one
2123// by appending the new content if it doesn't already contain it.
2124func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2125 // Check if the hook already exists
2126 buf, err := os.ReadFile(hookPath)
2127 if os.IsNotExist(err) {
2128 // Hook doesn't exist, create it
2129 err = os.WriteFile(hookPath, []byte(content), 0o755)
2130 if err != nil {
2131 return fmt.Errorf("failed to create hook: %w", err)
2132 }
2133 return nil
2134 }
2135 if err != nil {
2136 return fmt.Errorf("error reading existing hook: %w", err)
2137 }
2138
2139 // Hook exists, check if our content is already in it by looking for a distinctive line
2140 code := string(buf)
2141 if strings.Contains(code, distinctiveLine) {
2142 // Already contains our content, nothing to do
2143 return nil
2144 }
2145
2146 // Append our content to the existing hook
2147 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2148 if err != nil {
2149 return fmt.Errorf("failed to open hook for appending: %w", err)
2150 }
2151 defer f.Close()
2152
2153 // Ensure there's a newline at the end of the existing content if needed
2154 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2155 _, err = f.WriteString("\n")
2156 if err != nil {
2157 return fmt.Errorf("failed to add newline to hook: %w", err)
2158 }
2159 }
2160
2161 // Add a separator before our content
2162 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2163 if err != nil {
2164 return fmt.Errorf("failed to append to hook: %w", err)
2165 }
2166
2167 return nil
2168}