blob: 1527681fa4dbf495c2af280654bab9e7788be328 [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 {
Josh Bleecher Snyderb421a242025-05-29 23:22:55 +0000773 Context context.Context
774 Service llm.Service
775 Budget conversation.Budget
776 GitUsername string
777 GitEmail string
778 SessionID string
779 ClientGOOS string
780 ClientGOARCH string
781 InDocker bool
782 OneShot bool
783 WorkingDir string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000784 // Outside information
785 OutsideHostname string
786 OutsideOS string
787 OutsideWorkingDir string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700788
789 // Outtie's HTTP to, e.g., open a browser
790 OutsideHTTP string
791 // Outtie's Git server
792 GitRemoteAddr string
793 // Commit to checkout from Outtie
794 Commit string
Earl Lee2e463fb2025-04-17 11:22:22 -0700795}
796
797// NewAgent creates a new Agent.
798// It is not usable until Init() is called.
799func NewAgent(config AgentConfig) *Agent {
800 agent := &Agent{
Philip Zeyligerf2872992025-05-22 10:35:28 -0700801 config: config,
802 ready: make(chan struct{}),
803 inbox: make(chan string, 100),
804 subscribers: make([]chan *AgentMessage, 0),
805 startedAt: time.Now(),
806 originalBudget: config.Budget,
807 gitState: AgentGitState{
808 seenCommits: make(map[string]bool),
809 gitRemoteAddr: config.GitRemoteAddr,
810 },
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000811 outsideHostname: config.OutsideHostname,
812 outsideOS: config.OutsideOS,
813 outsideWorkingDir: config.OutsideWorkingDir,
814 outstandingLLMCalls: make(map[string]struct{}),
815 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700816 stateMachine: NewStateMachine(),
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700817 workingDir: config.WorkingDir,
818 outsideHTTP: config.OutsideHTTP,
Earl Lee2e463fb2025-04-17 11:22:22 -0700819 }
820 return agent
821}
822
823type AgentInit struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700824 NoGit bool // only for testing
Earl Lee2e463fb2025-04-17 11:22:22 -0700825
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700826 InDocker bool
827 HostAddr string
Earl Lee2e463fb2025-04-17 11:22:22 -0700828}
829
830func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700831 if a.convo != nil {
832 return fmt.Errorf("Agent.Init: already initialized")
833 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700834 ctx := a.config.Context
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700835 slog.InfoContext(ctx, "agent initializing")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700836
Philip Zeyligerf2872992025-05-22 10:35:28 -0700837 // If a remote git addr was specified, we configure the remote
838 if a.gitState.gitRemoteAddr != "" {
839 slog.InfoContext(ctx, "Configuring git remote", slog.String("remote", a.gitState.gitRemoteAddr))
840 cmd := exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", a.gitState.gitRemoteAddr)
841 cmd.Dir = a.workingDir
842 if out, err := cmd.CombinedOutput(); err != nil {
843 return fmt.Errorf("git remote add: %s: %v", out, err)
844 }
845 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
846 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
847 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
848 // origin/main on outtie sketch, which should make it easier to rebase.
849 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
850 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
851 cmd.Dir = a.workingDir
852 if out, err := cmd.CombinedOutput(); err != nil {
853 return fmt.Errorf("git config --add: %s: %v", out, err)
854 }
855 }
856
857 // If a commit was specified, we fetch and reset to it.
858 if a.config.Commit != "" && a.gitState.gitRemoteAddr != "" {
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700859 slog.InfoContext(ctx, "updating git repo", slog.String("commit", a.config.Commit))
860
Earl Lee2e463fb2025-04-17 11:22:22 -0700861 cmd := exec.CommandContext(ctx, "git", "stash")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700862 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700863 if out, err := cmd.CombinedOutput(); err != nil {
864 return fmt.Errorf("git stash: %s: %v", out, err)
865 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000866 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700867 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700868 if out, err := cmd.CombinedOutput(); err != nil {
869 return fmt.Errorf("git fetch: %s: %w", out, err)
870 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700871 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
872 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100873 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
874 // Remove git hooks if they exist and retry
875 // Only try removing hooks if we haven't already removed them during fetch
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700876 hookPath := filepath.Join(a.workingDir, ".git", "hooks")
Pokey Rule7a113622025-05-12 10:58:45 +0100877 if _, statErr := os.Stat(hookPath); statErr == nil {
878 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
879 slog.String("error", err.Error()),
880 slog.String("output", string(checkoutOut)))
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700881 if removeErr := removeGitHooks(ctx, a.workingDir); removeErr != nil {
Pokey Rule7a113622025-05-12 10:58:45 +0100882 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
883 }
884
885 // Retry the checkout operation
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700886 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
887 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100888 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700889 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 +0100890 }
891 } else {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700892 return fmt.Errorf("git checkout %s: %s: %w", a.config.Commit, checkoutOut, err)
Pokey Rule7a113622025-05-12 10:58:45 +0100893 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700894 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700895 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700896
897 if ini.HostAddr != "" {
898 a.url = "http://" + ini.HostAddr
899 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700900
901 if !ini.NoGit {
902 repoRoot, err := repoRoot(ctx, a.workingDir)
903 if err != nil {
904 return fmt.Errorf("repoRoot: %w", err)
905 }
906 a.repoRoot = repoRoot
907
Earl Lee2e463fb2025-04-17 11:22:22 -0700908 if err != nil {
909 return fmt.Errorf("resolveRef: %w", err)
910 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700911
Josh Bleecher Snyder90993a02025-05-28 18:15:15 -0700912 if err := setupGitHooks(a.repoRoot); err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700913 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
914 }
915
Philip Zeyliger49edc922025-05-14 09:45:45 -0700916 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
917 cmd.Dir = repoRoot
918 if out, err := cmd.CombinedOutput(); err != nil {
919 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
920 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700921
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000922 slog.Info("running codebase analysis")
923 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
924 if err != nil {
925 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000926 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000927 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000928
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +0000929 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -0700930 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000931 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700932 }
933 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000934
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700935 a.gitOrigin = getGitOrigin(ctx, a.workingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700936 }
Philip Zeyligerf2872992025-05-22 10:35:28 -0700937 a.gitState.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700938 a.convo = a.initConvo()
939 close(a.ready)
940 return nil
941}
942
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700943//go:embed agent_system_prompt.txt
944var agentSystemPrompt string
945
Earl Lee2e463fb2025-04-17 11:22:22 -0700946// initConvo initializes the conversation.
947// It must not be called until all agent fields are initialized,
948// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700949func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700950 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700951 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700952 convo.PromptCaching = true
953 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000954 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000955 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700956
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000957 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
958 bashPermissionCheck := func(command string) error {
959 // Check if branch name is set
960 a.mu.Lock()
Philip Zeyligerf2872992025-05-22 10:35:28 -0700961 branchSet := a.gitState.BranchName() != ""
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000962 a.mu.Unlock()
963
964 // If branch is set, all commands are allowed
965 if branchSet {
966 return nil
967 }
968
969 // If branch is not set, check if this is a git commit command
970 willCommit, err := bashkit.WillRunGitCommit(command)
971 if err != nil {
972 // If there's an error checking, we should allow the command to proceed
973 return nil
974 }
975
976 // If it's a git commit and branch is not set, return an error
977 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000978 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000979 }
980
981 return nil
982 }
983
Josh Bleecher Snyder495c1fa2025-05-29 00:37:22 +0000984 bashTool := claudetool.NewBashTool(bashPermissionCheck, claudetool.EnableBashToolJITInstall)
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000985
Earl Lee2e463fb2025-04-17 11:22:22 -0700986 // Register all tools with the conversation
987 // When adding, removing, or modifying tools here, double-check that the termui tool display
988 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000989
990 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700991 _, supportsScreenshots := a.config.Service.(*ant.Service)
992 var bTools []*llm.Tool
993 var browserCleanup func()
994
995 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
996 // Add cleanup function to context cancel
997 go func() {
998 <-a.config.Context.Done()
999 browserCleanup()
1000 }()
1001 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001002
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001003 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderb421a242025-05-29 23:22:55 +00001004 bashTool, claudetool.Keyword, claudetool.Patch,
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001005 claudetool.Think, claudetool.TodoRead, claudetool.TodoWrite, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -07001006 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +00001007 }
1008
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +00001009 // One-shot mode is non-interactive, multiple choice requires human response
1010 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001011 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -07001012 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001013
1014 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -07001015 convo.Listener = a
1016 return convo
1017}
1018
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001019var multipleChoiceTool = &llm.Tool{
1020 Name: "multiplechoice",
1021 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.",
1022 EndsTurn: true,
1023 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001024 "type": "object",
1025 "description": "The question and a list of answers you would expect the user to choose from.",
1026 "properties": {
1027 "question": {
1028 "type": "string",
1029 "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?'"
1030 },
1031 "responseOptions": {
1032 "type": "array",
1033 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1034 "items": {
1035 "type": "object",
1036 "properties": {
1037 "caption": {
1038 "type": "string",
1039 "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'"
1040 },
1041 "responseText": {
1042 "type": "string",
1043 "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'"
1044 }
1045 },
1046 "required": ["caption", "responseText"]
1047 }
1048 }
1049 },
1050 "required": ["question", "responseOptions"]
1051}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001052 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1053 // The Run logic for "multiplechoice" tool is a no-op on the server.
1054 // The UI will present a list of options for the user to select from,
1055 // and that's it as far as "executing" the tool_use goes.
1056 // When the user *does* select one of the presented options, that
1057 // responseText gets sent as a chat message on behalf of the user.
1058 return llm.TextContent("end your turn and wait for the user to respond"), nil
1059 },
Sean McCullough485afc62025-04-28 14:28:39 -07001060}
1061
1062type MultipleChoiceOption struct {
1063 Caption string `json:"caption"`
1064 ResponseText string `json:"responseText"`
1065}
1066
1067type MultipleChoiceParams struct {
1068 Question string `json:"question"`
1069 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1070}
1071
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001072// branchExists reports whether branchName exists, either locally or in well-known remotes.
1073func branchExists(dir, branchName string) bool {
1074 refs := []string{
1075 "refs/heads/",
1076 "refs/remotes/origin/",
1077 "refs/remotes/sketch-host/",
1078 }
1079 for _, ref := range refs {
1080 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1081 cmd.Dir = dir
1082 if cmd.Run() == nil { // exit code 0 means branch exists
1083 return true
1084 }
1085 }
1086 return false
1087}
1088
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001089func (a *Agent) titleTool() *llm.Tool {
1090 description := `Sets the conversation title.`
1091 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001092 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001093 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001094 InputSchema: json.RawMessage(`{
1095 "type": "object",
1096 "properties": {
1097 "title": {
1098 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001099 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001100 }
1101 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001102 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001103}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001104 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001105 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001106 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001107 }
1108 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001109 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001110 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001111
1112 // We don't allow changing the title once set to be consistent with the previous behavior
1113 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001114 t := a.Title()
1115 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001116 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001117 }
1118
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001119 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001120 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001121 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001122
1123 a.SetTitle(params.Title)
1124 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001125 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001126 },
1127 }
1128 return titleTool
1129}
1130
1131func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001132 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 +00001133 preCommit := &llm.Tool{
1134 Name: "precommit",
1135 Description: description,
1136 InputSchema: json.RawMessage(`{
1137 "type": "object",
1138 "properties": {
1139 "branch_name": {
1140 "type": "string",
1141 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1142 }
1143 },
1144 "required": ["branch_name"]
1145}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001146 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001147 var params struct {
1148 BranchName string `json:"branch_name"`
1149 }
1150 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001151 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001152 }
1153
1154 b := a.BranchName()
1155 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001156 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001157 }
1158
1159 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001160 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001161 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001162 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001163 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001164 }
1165 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001166 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001167 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001168 }
1169
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001170 a.SetBranch(branchName)
Josh Bleecher Snyderf7bebdd2025-05-14 15:22:24 -07001171 response := fmt.Sprintf("switched to branch sketch/%q - DO NOT change branches unless explicitly requested", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001172
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001173 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1174 if err != nil {
1175 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1176 }
1177 if len(styleHint) > 0 {
1178 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001179 }
1180
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001181 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001182 },
1183 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001184 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001185}
1186
1187func (a *Agent) Ready() <-chan struct{} {
1188 return a.ready
1189}
1190
1191func (a *Agent) UserMessage(ctx context.Context, msg string) {
1192 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1193 a.inbox <- msg
1194}
1195
Earl Lee2e463fb2025-04-17 11:22:22 -07001196func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1197 return a.convo.CancelToolUse(toolUseID, cause)
1198}
1199
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001200func (a *Agent) CancelTurn(cause error) {
1201 a.cancelTurnMu.Lock()
1202 defer a.cancelTurnMu.Unlock()
1203 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001204 // Force state transition to cancelled state
1205 ctx := a.config.Context
1206 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001207 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001208 }
1209}
1210
1211func (a *Agent) Loop(ctxOuter context.Context) {
1212 for {
1213 select {
1214 case <-ctxOuter.Done():
1215 return
1216 default:
1217 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001218 a.cancelTurnMu.Lock()
1219 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001220 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001221 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001222 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001223 a.cancelTurn = cancel
1224 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001225 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1226 if err != nil {
1227 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1228 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001229 cancel(nil)
1230 }
1231 }
1232}
1233
1234func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1235 if m.Timestamp.IsZero() {
1236 m.Timestamp = time.Now()
1237 }
1238
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001239 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1240 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1241 m.Content = m.ToolResult
1242 }
1243
Earl Lee2e463fb2025-04-17 11:22:22 -07001244 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1245 if m.EndOfTurn && m.Type == AgentMessageType {
1246 turnDuration := time.Since(a.startOfTurn)
1247 m.TurnDuration = &turnDuration
1248 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1249 }
1250
Earl Lee2e463fb2025-04-17 11:22:22 -07001251 a.mu.Lock()
1252 defer a.mu.Unlock()
1253 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001254 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001255 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001256
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001257 // Notify all subscribers
1258 for _, ch := range a.subscribers {
1259 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001260 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001261}
1262
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001263func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1264 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001265 if block {
1266 select {
1267 case <-ctx.Done():
1268 return m, ctx.Err()
1269 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001270 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001271 }
1272 }
1273 for {
1274 select {
1275 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001276 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001277 default:
1278 return m, nil
1279 }
1280 }
1281}
1282
Sean McCullough885a16a2025-04-30 02:49:25 +00001283// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001284func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001285 // Reset the start of turn time
1286 a.startOfTurn = time.Now()
1287
Sean McCullough96b60dd2025-04-30 09:49:10 -07001288 // Transition to waiting for user input state
1289 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1290
Sean McCullough885a16a2025-04-30 02:49:25 +00001291 // Process initial user message
1292 initialResp, err := a.processUserMessage(ctx)
1293 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001294 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001295 return err
1296 }
1297
1298 // Handle edge case where both initialResp and err are nil
1299 if initialResp == nil {
1300 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001301 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1302
Sean McCullough9f4b8082025-04-30 17:34:07 +00001303 a.pushToOutbox(ctx, errorMessage(err))
1304 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001305 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001306
Earl Lee2e463fb2025-04-17 11:22:22 -07001307 // We do this as we go, but let's also do it at the end of the turn
1308 defer func() {
1309 if _, err := a.handleGitCommits(ctx); err != nil {
1310 // Just log the error, don't stop execution
1311 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1312 }
1313 }()
1314
Sean McCullougha1e0e492025-05-01 10:51:08 -07001315 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001316 resp := initialResp
1317 for {
1318 // Check if we are over budget
1319 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001320 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001321 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001322 }
1323
1324 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001325 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001326 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001327 break
1328 }
1329
Sean McCullough96b60dd2025-04-30 09:49:10 -07001330 // Transition to tool use requested state
1331 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1332
Sean McCullough885a16a2025-04-30 02:49:25 +00001333 // Handle tool execution
1334 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1335 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001336 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001337 }
1338
Sean McCullougha1e0e492025-05-01 10:51:08 -07001339 if toolResp == nil {
1340 return fmt.Errorf("cannot continue conversation with a nil tool response")
1341 }
1342
Sean McCullough885a16a2025-04-30 02:49:25 +00001343 // Set the response for the next iteration
1344 resp = toolResp
1345 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001346
1347 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001348}
1349
1350// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001351func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001352 // Wait for at least one message from the user
1353 msgs, err := a.GatherMessages(ctx, true)
1354 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001355 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001356 return nil, err
1357 }
1358
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001359 userMessage := llm.Message{
1360 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001361 Content: msgs,
1362 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001363
Sean McCullough96b60dd2025-04-30 09:49:10 -07001364 // Transition to sending to LLM state
1365 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1366
Sean McCullough885a16a2025-04-30 02:49:25 +00001367 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001368 resp, err := a.convo.SendMessage(userMessage)
1369 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001370 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001371 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001372 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001373 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001374
Sean McCullough96b60dd2025-04-30 09:49:10 -07001375 // Transition to processing LLM response state
1376 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1377
Sean McCullough885a16a2025-04-30 02:49:25 +00001378 return resp, nil
1379}
1380
1381// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001382func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1383 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001384 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001385 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001386
Sean McCullough96b60dd2025-04-30 09:49:10 -07001387 // Transition to checking for cancellation state
1388 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1389
Sean McCullough885a16a2025-04-30 02:49:25 +00001390 // Check if the operation was cancelled by the user
1391 select {
1392 case <-ctx.Done():
1393 // Don't actually run any of the tools, but rather build a response
1394 // for each tool_use message letting the LLM know that user canceled it.
1395 var err error
1396 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001397 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001398 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001399 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001400 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001401 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001402 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001403 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001404 // Transition to running tool state
1405 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1406
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001407 // Add working directory and session ID to context for tool execution
Sean McCullough885a16a2025-04-30 02:49:25 +00001408 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001409 ctx = claudetool.WithSessionID(ctx, a.config.SessionID)
Sean McCullough885a16a2025-04-30 02:49:25 +00001410
1411 // Execute the tools
1412 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001413 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001414 if ctx.Err() != nil { // e.g. the user canceled the operation
1415 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001416 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001417 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001418 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001419 a.pushToOutbox(ctx, errorMessage(err))
1420 }
1421 }
1422
1423 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001424 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001425 autoqualityMessages := a.processGitChanges(ctx)
1426
1427 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001428 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001429 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001430 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001431 return false, nil
1432 }
1433
1434 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001435 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1436 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001437}
1438
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001439// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001440func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001441 // Check for git commits
1442 _, err := a.handleGitCommits(ctx)
1443 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001444 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001445 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001446 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001447 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001448}
1449
1450// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1451// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001452func (a *Agent) processGitChanges(ctx context.Context) []string {
1453 // Check for git commits after tool execution
1454 newCommits, err := a.handleGitCommits(ctx)
1455 if err != nil {
1456 // Just log the error, don't stop execution
1457 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1458 return nil
1459 }
1460
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001461 // Run mechanical checks if there was exactly one new commit.
1462 if len(newCommits) != 1 {
1463 return nil
1464 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001465 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001466 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1467 msg := a.codereview.RunMechanicalChecks(ctx)
1468 if msg != "" {
1469 a.pushToOutbox(ctx, AgentMessage{
1470 Type: AutoMessageType,
1471 Content: msg,
1472 Timestamp: time.Now(),
1473 })
1474 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001475 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001476
1477 return autoqualityMessages
1478}
1479
1480// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001481func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001482 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001483 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001484 msgs, err := a.GatherMessages(ctx, false)
1485 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001486 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001487 return false, nil
1488 }
1489
1490 // Inject any auto-generated messages from quality checks
1491 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001492 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001493 }
1494
1495 // Handle cancellation by appending a message about it
1496 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001497 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001498 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001499 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001500 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1501 } else if err := a.convo.OverBudget(); err != nil {
1502 // Handle budget issues by appending a message about it
1503 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 -07001504 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001505 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1506 }
1507
1508 // Combine tool results with user messages
1509 results = append(results, msgs...)
1510
1511 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001512 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001513 resp, err := a.convo.SendMessage(llm.Message{
1514 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001515 Content: results,
1516 })
1517 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001518 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001519 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1520 return true, nil // Return true to continue the conversation, but with no response
1521 }
1522
Sean McCullough96b60dd2025-04-30 09:49:10 -07001523 // Transition back to processing LLM response
1524 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1525
Sean McCullough885a16a2025-04-30 02:49:25 +00001526 if cancelled {
1527 return false, nil
1528 }
1529
1530 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001531}
1532
1533func (a *Agent) overBudget(ctx context.Context) error {
1534 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001535 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001536 m := budgetMessage(err)
1537 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001538 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001539 a.convo.ResetBudget(a.originalBudget)
1540 return err
1541 }
1542 return nil
1543}
1544
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001545func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001546 // Collect all text content
1547 var allText strings.Builder
1548 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001549 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001550 if allText.Len() > 0 {
1551 allText.WriteString("\n\n")
1552 }
1553 allText.WriteString(content.Text)
1554 }
1555 }
1556 return allText.String()
1557}
1558
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001559func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001560 a.mu.Lock()
1561 defer a.mu.Unlock()
1562 return a.convo.CumulativeUsage()
1563}
1564
Earl Lee2e463fb2025-04-17 11:22:22 -07001565// Diff returns a unified diff of changes made since the agent was instantiated.
1566func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001567 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001568 return "", fmt.Errorf("no initial commit reference available")
1569 }
1570
1571 // Find the repository root
1572 ctx := context.Background()
1573
1574 // If a specific commit hash is provided, show just that commit's changes
1575 if commit != nil && *commit != "" {
1576 // Validate that the commit looks like a valid git SHA
1577 if !isValidGitSHA(*commit) {
1578 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1579 }
1580
1581 // Get the diff for just this commit
1582 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1583 cmd.Dir = a.repoRoot
1584 output, err := cmd.CombinedOutput()
1585 if err != nil {
1586 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1587 }
1588 return string(output), nil
1589 }
1590
1591 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001592 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001593 cmd.Dir = a.repoRoot
1594 output, err := cmd.CombinedOutput()
1595 if err != nil {
1596 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1597 }
1598
1599 return string(output), nil
1600}
1601
Philip Zeyliger49edc922025-05-14 09:45:45 -07001602// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1603// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1604func (a *Agent) SketchGitBaseRef() string {
1605 if a.IsInContainer() {
1606 return "sketch-base"
1607 } else {
1608 return "sketch-base-" + a.SessionID()
1609 }
1610}
1611
1612// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1613func (a *Agent) SketchGitBase() string {
1614 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1615 cmd.Dir = a.repoRoot
1616 output, err := cmd.CombinedOutput()
1617 if err != nil {
1618 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1619 return "HEAD"
1620 }
1621 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001622}
1623
Pokey Rule7a113622025-05-12 10:58:45 +01001624// removeGitHooks removes the Git hooks directory from the repository
1625func removeGitHooks(_ context.Context, repoPath string) error {
1626 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1627
1628 // Check if hooks directory exists
1629 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1630 // Directory doesn't exist, nothing to do
1631 return nil
1632 }
1633
1634 // Remove the hooks directory
1635 err := os.RemoveAll(hooksDir)
1636 if err != nil {
1637 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1638 }
1639
1640 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001641 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001642 if err != nil {
1643 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1644 }
1645
1646 return nil
1647}
1648
Philip Zeyligerf2872992025-05-22 10:35:28 -07001649func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1650 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef())
1651 for _, msg := range msgs {
1652 a.pushToOutbox(ctx, msg)
1653 }
1654 return commits, error
1655}
1656
Earl Lee2e463fb2025-04-17 11:22:22 -07001657// handleGitCommits() highlights new commits to the user. When running
1658// under docker, new HEADs are pushed to a branch according to the title.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001659func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string) ([]AgentMessage, []*GitCommit, error) {
1660 ags.mu.Lock()
1661 defer ags.mu.Unlock()
1662
1663 msgs := []AgentMessage{}
1664 if repoRoot == "" {
1665 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001666 }
1667
Philip Zeyligerf2872992025-05-22 10:35:28 -07001668 head, err := resolveRef(ctx, repoRoot, "HEAD")
Earl Lee2e463fb2025-04-17 11:22:22 -07001669 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001670 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001671 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001672 if head == ags.lastHEAD {
1673 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001674 }
1675 defer func() {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001676 ags.lastHEAD = head
Earl Lee2e463fb2025-04-17 11:22:22 -07001677 }()
1678
1679 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1680 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1681 // to the last 100 commits.
1682 var commits []*GitCommit
1683
1684 // Get commits since the initial commit
1685 // Format: <hash>\0<subject>\0<body>\0
1686 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1687 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyligerf2872992025-05-22 10:35:28 -07001688 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+baseRef, head)
1689 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07001690 output, err := cmd.Output()
1691 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001692 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07001693 }
1694
1695 // Parse git log output and filter out already seen commits
1696 parsedCommits := parseGitLog(string(output))
1697
1698 var headCommit *GitCommit
1699
1700 // Filter out commits we've already seen
1701 for _, commit := range parsedCommits {
1702 if commit.Hash == head {
1703 headCommit = &commit
1704 }
1705
1706 // Skip if we've seen this commit before. If our head has changed, always include that.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001707 if ags.seenCommits[commit.Hash] && commit.Hash != head {
Earl Lee2e463fb2025-04-17 11:22:22 -07001708 continue
1709 }
1710
1711 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07001712 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07001713
1714 // Add to our list of new commits
1715 commits = append(commits, &commit)
1716 }
1717
Philip Zeyligerf2872992025-05-22 10:35:28 -07001718 if ags.gitRemoteAddr != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001719 if headCommit == nil {
1720 // I think this can only happen if we have a bug or if there's a race.
1721 headCommit = &GitCommit{}
1722 headCommit.Hash = head
1723 headCommit.Subject = "unknown"
1724 commits = append(commits, headCommit)
1725 }
1726
Philip Zeyligerf2872992025-05-22 10:35:28 -07001727 originalBranch := cmp.Or(ags.branchName, "sketch/"+sessionID)
Philip Zeyliger113e2052025-05-09 21:59:40 +00001728 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001729
1730 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1731 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1732 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001733
1734 // Try up to 10 times with different branch names if the branch is checked out on the remote
1735 var out []byte
1736 var err error
1737 for retries := range 10 {
1738 if retries > 0 {
1739 // Add a numeric suffix to the branch name
1740 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1741 }
1742
Philip Zeyligerf2872992025-05-22 10:35:28 -07001743 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1744 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00001745 out, err = cmd.CombinedOutput()
1746
1747 if err == nil {
1748 // Success! Break out of the retry loop
1749 break
1750 }
1751
1752 // Check if this is the "refusing to update checked out branch" error
1753 if !strings.Contains(string(out), "refusing to update checked out branch") {
1754 // This is a different error, so don't retry
1755 break
1756 }
1757
1758 // If we're on the last retry, we'll report the error
1759 if retries == 9 {
1760 break
1761 }
1762 }
1763
1764 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001765 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001766 } else {
1767 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001768 // Update the agent's branch name if we ended up using a different one
1769 if branch != originalBranch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001770 ags.branchName = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001771 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001772 }
1773 }
1774
1775 // If we found new commits, create a message
1776 if len(commits) > 0 {
1777 msg := AgentMessage{
1778 Type: CommitMessageType,
1779 Timestamp: time.Now(),
1780 Commits: commits,
1781 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001782 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001783 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001784 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001785}
1786
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001787func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001788 return strings.Map(func(r rune) rune {
1789 // lowercase
1790 if r >= 'A' && r <= 'Z' {
1791 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001792 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001793 // replace spaces with dashes
1794 if r == ' ' {
1795 return '-'
1796 }
1797 // allow alphanumerics and dashes
1798 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1799 return r
1800 }
1801 return -1
1802 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001803}
1804
1805// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1806// and returns an array of GitCommit structs.
1807func parseGitLog(output string) []GitCommit {
1808 var commits []GitCommit
1809
1810 // No output means no commits
1811 if len(output) == 0 {
1812 return commits
1813 }
1814
1815 // Split by NULL byte
1816 parts := strings.Split(output, "\x00")
1817
1818 // Process in triplets (hash, subject, body)
1819 for i := 0; i < len(parts); i++ {
1820 // Skip empty parts
1821 if parts[i] == "" {
1822 continue
1823 }
1824
1825 // This should be a hash
1826 hash := strings.TrimSpace(parts[i])
1827
1828 // Make sure we have at least a subject part available
1829 if i+1 >= len(parts) {
1830 break // No more parts available
1831 }
1832
1833 // Get the subject
1834 subject := strings.TrimSpace(parts[i+1])
1835
1836 // Get the body if available
1837 body := ""
1838 if i+2 < len(parts) {
1839 body = strings.TrimSpace(parts[i+2])
1840 }
1841
1842 // Skip to the next triplet
1843 i += 2
1844
1845 commits = append(commits, GitCommit{
1846 Hash: hash,
1847 Subject: subject,
1848 Body: body,
1849 })
1850 }
1851
1852 return commits
1853}
1854
1855func repoRoot(ctx context.Context, dir string) (string, error) {
1856 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1857 stderr := new(strings.Builder)
1858 cmd.Stderr = stderr
1859 cmd.Dir = dir
1860 out, err := cmd.Output()
1861 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001862 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07001863 }
1864 return strings.TrimSpace(string(out)), nil
1865}
1866
1867func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1868 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1869 stderr := new(strings.Builder)
1870 cmd.Stderr = stderr
1871 cmd.Dir = dir
1872 out, err := cmd.Output()
1873 if err != nil {
1874 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1875 }
1876 // TODO: validate that out is valid hex
1877 return strings.TrimSpace(string(out)), nil
1878}
1879
1880// isValidGitSHA validates if a string looks like a valid git SHA hash.
1881// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1882func isValidGitSHA(sha string) bool {
1883 // Git SHA must be a hexadecimal string with at least 4 characters
1884 if len(sha) < 4 || len(sha) > 40 {
1885 return false
1886 }
1887
1888 // Check if the string only contains hexadecimal characters
1889 for _, char := range sha {
1890 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1891 return false
1892 }
1893 }
1894
1895 return true
1896}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001897
1898// getGitOrigin returns the URL of the git remote 'origin' if it exists
1899func getGitOrigin(ctx context.Context, dir string) string {
1900 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1901 cmd.Dir = dir
1902 stderr := new(strings.Builder)
1903 cmd.Stderr = stderr
1904 out, err := cmd.Output()
1905 if err != nil {
1906 return ""
1907 }
1908 return strings.TrimSpace(string(out))
1909}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001910
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001911// systemPromptData contains the data used to render the system prompt template
1912type systemPromptData struct {
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001913 ClientGOOS string
1914 ClientGOARCH string
1915 WorkingDir string
1916 RepoRoot string
1917 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001918 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001919}
1920
1921// renderSystemPrompt renders the system prompt template.
1922func (a *Agent) renderSystemPrompt() string {
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001923 data := systemPromptData{
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001924 ClientGOOS: a.config.ClientGOOS,
1925 ClientGOARCH: a.config.ClientGOARCH,
1926 WorkingDir: a.workingDir,
1927 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07001928 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001929 Codebase: a.codebase,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001930 }
1931
1932 tmpl, err := template.New("system").Parse(agentSystemPrompt)
1933 if err != nil {
1934 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
1935 }
1936 buf := new(strings.Builder)
1937 err = tmpl.Execute(buf, data)
1938 if err != nil {
1939 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
1940 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001941 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001942 return buf.String()
1943}
Philip Zeyligereab12de2025-05-14 02:35:53 +00001944
1945// StateTransitionIterator provides an iterator over state transitions.
1946type StateTransitionIterator interface {
1947 // Next blocks until a new state transition is available or context is done.
1948 // Returns nil if the context is cancelled.
1949 Next() *StateTransition
1950 // Close removes the listener and cleans up resources.
1951 Close()
1952}
1953
1954// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
1955type StateTransitionIteratorImpl struct {
1956 agent *Agent
1957 ctx context.Context
1958 ch chan StateTransition
1959 unsubscribe func()
1960}
1961
1962// Next blocks until a new state transition is available or the context is cancelled.
1963func (s *StateTransitionIteratorImpl) Next() *StateTransition {
1964 select {
1965 case <-s.ctx.Done():
1966 return nil
1967 case transition, ok := <-s.ch:
1968 if !ok {
1969 return nil
1970 }
1971 transitionCopy := transition
1972 return &transitionCopy
1973 }
1974}
1975
1976// Close removes the listener and cleans up resources.
1977func (s *StateTransitionIteratorImpl) Close() {
1978 if s.unsubscribe != nil {
1979 s.unsubscribe()
1980 s.unsubscribe = nil
1981 }
1982}
1983
1984// NewStateTransitionIterator returns an iterator that receives state transitions.
1985func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
1986 a.mu.Lock()
1987 defer a.mu.Unlock()
1988
1989 // Create channel to receive state transitions
1990 ch := make(chan StateTransition, 10)
1991
1992 // Add a listener to the state machine
1993 unsubscribe := a.stateMachine.AddTransitionListener(ch)
1994
1995 return &StateTransitionIteratorImpl{
1996 agent: a,
1997 ctx: ctx,
1998 ch: ch,
1999 unsubscribe: unsubscribe,
2000 }
2001}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002002
2003// setupGitHooks creates or updates git hooks in the specified working directory.
2004func setupGitHooks(workingDir string) error {
2005 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2006
2007 _, err := os.Stat(hooksDir)
2008 if os.IsNotExist(err) {
2009 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2010 }
2011 if err != nil {
2012 return fmt.Errorf("error checking git hooks directory: %w", err)
2013 }
2014
2015 // Define the post-commit hook content
2016 postCommitHook := `#!/bin/bash
2017echo "<post_commit_hook>"
2018echo "Please review this commit message and fix it if it is incorrect."
2019echo "This hook only echos the commit message; it does not modify it."
2020echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2021echo "<last_commit_message>"
2022git log -1 --pretty=%B
2023echo "</last_commit_message>"
2024echo "</post_commit_hook>"
2025`
2026
2027 // Define the prepare-commit-msg hook content
2028 prepareCommitMsgHook := `#!/bin/bash
2029# Add Co-Authored-By and Change-ID trailers to commit messages
2030# Check if these trailers already exist before adding them
2031
2032commit_file="$1"
2033COMMIT_SOURCE="$2"
2034
2035# Skip for merges, squashes, or when using a commit template
2036if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2037 [ "$COMMIT_SOURCE" = "squash" ]; then
2038 exit 0
2039fi
2040
2041commit_msg=$(cat "$commit_file")
2042
2043needs_co_author=true
2044needs_change_id=true
2045
2046# Check if commit message already has Co-Authored-By trailer
2047if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2048 needs_co_author=false
2049fi
2050
2051# Check if commit message already has Change-ID trailer
2052if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2053 needs_change_id=false
2054fi
2055
2056# Only modify if at least one trailer needs to be added
2057if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
Josh Bleecher Snyderb509a5d2025-05-23 15:49:42 +00002058 # Ensure there's a proper blank line before trailers
2059 if [ -s "$commit_file" ]; then
2060 # Check if file ends with newline by reading last character
2061 last_char=$(tail -c 1 "$commit_file")
2062
2063 if [ "$last_char" != "" ]; then
2064 # File doesn't end with newline - add two newlines (complete line + blank line)
2065 echo "" >> "$commit_file"
2066 echo "" >> "$commit_file"
2067 else
2068 # File ends with newline - check if we already have a blank line
2069 last_line=$(tail -1 "$commit_file")
2070 if [ -n "$last_line" ]; then
2071 # Last line has content - add one newline for blank line
2072 echo "" >> "$commit_file"
2073 fi
2074 # If last line is empty, we already have a blank line - don't add anything
2075 fi
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002076 fi
2077
2078 # Add trailers if needed
2079 if [ "$needs_co_author" = true ]; then
2080 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2081 fi
2082
2083 if [ "$needs_change_id" = true ]; then
2084 change_id=$(openssl rand -hex 8)
2085 echo "Change-ID: s${change_id}k" >> "$commit_file"
2086 fi
2087fi
2088`
2089
2090 // Update or create the post-commit hook
2091 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2092 if err != nil {
2093 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2094 }
2095
2096 // Update or create the prepare-commit-msg hook
2097 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2098 if err != nil {
2099 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2100 }
2101
2102 return nil
2103}
2104
2105// updateOrCreateHook creates a new hook file or updates an existing one
2106// by appending the new content if it doesn't already contain it.
2107func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2108 // Check if the hook already exists
2109 buf, err := os.ReadFile(hookPath)
2110 if os.IsNotExist(err) {
2111 // Hook doesn't exist, create it
2112 err = os.WriteFile(hookPath, []byte(content), 0o755)
2113 if err != nil {
2114 return fmt.Errorf("failed to create hook: %w", err)
2115 }
2116 return nil
2117 }
2118 if err != nil {
2119 return fmt.Errorf("error reading existing hook: %w", err)
2120 }
2121
2122 // Hook exists, check if our content is already in it by looking for a distinctive line
2123 code := string(buf)
2124 if strings.Contains(code, distinctiveLine) {
2125 // Already contains our content, nothing to do
2126 return nil
2127 }
2128
2129 // Append our content to the existing hook
2130 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2131 if err != nil {
2132 return fmt.Errorf("failed to open hook for appending: %w", err)
2133 }
2134 defer f.Close()
2135
2136 // Ensure there's a newline at the end of the existing content if needed
2137 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2138 _, err = f.WriteString("\n")
2139 if err != nil {
2140 return fmt.Errorf("failed to add newline to hook: %w", err)
2141 }
2142 }
2143
2144 // Add a separator before our content
2145 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2146 if err != nil {
2147 return fmt.Errorf("failed to append to hook: %w", err)
2148 }
2149
2150 return nil
2151}