blob: f9450ab7f34cc70d3431ef39d3cae859eaa3bf44 [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
Earl Lee2e463fb2025-04-17 11:22:22 -0700129}
130
131type CodingAgentMessageType string
132
133const (
134 UserMessageType CodingAgentMessageType = "user"
135 AgentMessageType CodingAgentMessageType = "agent"
136 ErrorMessageType CodingAgentMessageType = "error"
137 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
138 ToolUseMessageType CodingAgentMessageType = "tool"
139 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
140 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
141
142 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
143)
144
145type AgentMessage struct {
146 Type CodingAgentMessageType `json:"type"`
147 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
148 EndOfTurn bool `json:"end_of_turn"`
149
150 Content string `json:"content"`
151 ToolName string `json:"tool_name,omitempty"`
152 ToolInput string `json:"input,omitempty"`
153 ToolResult string `json:"tool_result,omitempty"`
154 ToolError bool `json:"tool_error,omitempty"`
155 ToolCallId string `json:"tool_call_id,omitempty"`
156
157 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
158 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
159
Sean McCulloughd9f13372025-04-21 15:08:49 -0700160 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
161 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
162
Earl Lee2e463fb2025-04-17 11:22:22 -0700163 // Commits is a list of git commits for a commit message
164 Commits []*GitCommit `json:"commits,omitempty"`
165
166 Timestamp time.Time `json:"timestamp"`
167 ConversationID string `json:"conversation_id"`
168 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700169 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700170
171 // Message timing information
172 StartTime *time.Time `json:"start_time,omitempty"`
173 EndTime *time.Time `json:"end_time,omitempty"`
174 Elapsed *time.Duration `json:"elapsed,omitempty"`
175
176 // Turn duration - the time taken for a complete agent turn
177 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
178
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000179 // HideOutput indicates that this message should not be rendered in the UI.
180 // This is useful for subconversations that generate output that shouldn't be shown to the user.
181 HideOutput bool `json:"hide_output,omitempty"`
182
Earl Lee2e463fb2025-04-17 11:22:22 -0700183 Idx int `json:"idx"`
184}
185
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000186// SetConvo sets m.ConversationID, m.ParentConversationID, and m.HideOutput based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700187func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700188 if convo == nil {
189 m.ConversationID = ""
190 m.ParentConversationID = nil
191 return
192 }
193 m.ConversationID = convo.ID
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000194 m.HideOutput = convo.Hidden
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700195 if convo.Parent != nil {
196 m.ParentConversationID = &convo.Parent.ID
197 }
198}
199
Earl Lee2e463fb2025-04-17 11:22:22 -0700200// GitCommit represents a single git commit for a commit message
201type GitCommit struct {
202 Hash string `json:"hash"` // Full commit hash
203 Subject string `json:"subject"` // Commit subject line
204 Body string `json:"body"` // Full commit message body
205 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
206}
207
208// ToolCall represents a single tool call within an agent message
209type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700210 Name string `json:"name"`
211 Input string `json:"input"`
212 ToolCallId string `json:"tool_call_id"`
213 ResultMessage *AgentMessage `json:"result_message,omitempty"`
214 Args string `json:"args,omitempty"`
215 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700216}
217
218func (a *AgentMessage) Attr() slog.Attr {
219 var attrs []any = []any{
220 slog.String("type", string(a.Type)),
221 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700222 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700223 if a.EndOfTurn {
224 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
225 }
226 if a.Content != "" {
227 attrs = append(attrs, slog.String("content", a.Content))
228 }
229 if a.ToolName != "" {
230 attrs = append(attrs, slog.String("tool_name", a.ToolName))
231 }
232 if a.ToolInput != "" {
233 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
234 }
235 if a.Elapsed != nil {
236 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
237 }
238 if a.TurnDuration != nil {
239 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
240 }
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700241 if len(a.ToolResult) > 0 {
242 attrs = append(attrs, slog.Any("tool_result", a.ToolResult))
Earl Lee2e463fb2025-04-17 11:22:22 -0700243 }
244 if a.ToolError {
245 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
246 }
247 if len(a.ToolCalls) > 0 {
248 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
249 for i, tc := range a.ToolCalls {
250 toolCallAttrs = append(toolCallAttrs, slog.Group(
251 fmt.Sprintf("tool_call_%d", i),
252 slog.String("name", tc.Name),
253 slog.String("input", tc.Input),
254 ))
255 }
256 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
257 }
258 if a.ConversationID != "" {
259 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
260 }
261 if a.ParentConversationID != nil {
262 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
263 }
264 if a.Usage != nil && !a.Usage.IsZero() {
265 attrs = append(attrs, a.Usage.Attr())
266 }
267 // TODO: timestamp, convo ids, idx?
268 return slog.Group("agent_message", attrs...)
269}
270
271func errorMessage(err error) AgentMessage {
272 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
273 if os.Getenv(("DEBUG")) == "1" {
274 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
275 }
276
277 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
278}
279
280func budgetMessage(err error) AgentMessage {
281 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
282}
283
284// ConvoInterface defines the interface for conversation interactions
285type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700286 CumulativeUsage() conversation.CumulativeUsage
287 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700288 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700289 SendMessage(message llm.Message) (*llm.Response, error)
290 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700291 GetID() string
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +0000292 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, bool, error)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700293 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700294 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700295 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700296}
297
Philip Zeyligerf2872992025-05-22 10:35:28 -0700298// AgentGitState holds the state necessary for pushing to a remote git repo
299// when HEAD changes. If gitRemoteAddr is set, then we push to sketch/
300// any time we notice we need to.
301type AgentGitState struct {
302 mu sync.Mutex // protects following
303 lastHEAD string // hash of the last HEAD that was pushed to the host
304 gitRemoteAddr string // HTTP URL of the host git repo
305 seenCommits map[string]bool // Track git commits we've already seen (by hash)
306 branchName string
307}
308
309func (ags *AgentGitState) SetBranchName(branchName string) {
310 ags.mu.Lock()
311 defer ags.mu.Unlock()
312 ags.branchName = branchName
313}
314
315func (ags *AgentGitState) BranchName() string {
316 ags.mu.Lock()
317 defer ags.mu.Unlock()
318 return ags.branchName
319}
320
Earl Lee2e463fb2025-04-17 11:22:22 -0700321type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700322 convo ConvoInterface
323 config AgentConfig // config for this agent
Philip Zeyligerf2872992025-05-22 10:35:28 -0700324 gitState AgentGitState
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700325 workingDir string
326 repoRoot string // workingDir may be a subdir of repoRoot
327 url string
328 firstMessageIndex int // index of the first message in the current conversation
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000329 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700330 ready chan struct{} // closed when the agent is initialized (only when under docker)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000331 codebase *onstart.Codebase
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700332 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700333 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700334 title string
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000335 codereview *codereview.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700336 // State machine to track agent state
337 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000338 // Outside information
339 outsideHostname string
340 outsideOS string
341 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000342 // URL of the git remote 'origin' if it exists
343 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700344
345 // Time when the current turn started (reset at the beginning of InnerLoop)
346 startOfTurn time.Time
347
348 // Inbox - for messages from the user to the agent.
349 // sent on by UserMessage
350 // . e.g. when user types into the chat textarea
351 // read from by GatherMessages
352 inbox chan string
353
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000354 // protects cancelTurn
355 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700356 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000357 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700358
359 // protects following
360 mu sync.Mutex
361
362 // Stores all messages for this agent
363 history []AgentMessage
364
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700365 // Iterators add themselves here when they're ready to be notified of new messages.
366 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700367
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000368 // Track outstanding LLM call IDs
369 outstandingLLMCalls map[string]struct{}
370
371 // Track outstanding tool calls by ID with their names
372 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700373}
374
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700375// NewIterator implements CodingAgent.
376func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
377 a.mu.Lock()
378 defer a.mu.Unlock()
379
380 return &MessageIteratorImpl{
381 agent: a,
382 ctx: ctx,
383 nextMessageIdx: nextMessageIdx,
384 ch: make(chan *AgentMessage, 100),
385 }
386}
387
388type MessageIteratorImpl struct {
389 agent *Agent
390 ctx context.Context
391 nextMessageIdx int
392 ch chan *AgentMessage
393 subscribed bool
394}
395
396func (m *MessageIteratorImpl) Close() {
397 m.agent.mu.Lock()
398 defer m.agent.mu.Unlock()
399 // Delete ourselves from the subscribers list
400 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
401 return x == m.ch
402 })
403 close(m.ch)
404}
405
406func (m *MessageIteratorImpl) Next() *AgentMessage {
407 // We avoid subscription at creation to let ourselves catch up to "current state"
408 // before subscribing.
409 if !m.subscribed {
410 m.agent.mu.Lock()
411 if m.nextMessageIdx < len(m.agent.history) {
412 msg := &m.agent.history[m.nextMessageIdx]
413 m.nextMessageIdx++
414 m.agent.mu.Unlock()
415 return msg
416 }
417 // The next message doesn't exist yet, so let's subscribe
418 m.agent.subscribers = append(m.agent.subscribers, m.ch)
419 m.subscribed = true
420 m.agent.mu.Unlock()
421 }
422
423 for {
424 select {
425 case <-m.ctx.Done():
426 m.agent.mu.Lock()
427 // Delete ourselves from the subscribers list
428 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
429 return x == m.ch
430 })
431 m.subscribed = false
432 m.agent.mu.Unlock()
433 return nil
434 case msg, ok := <-m.ch:
435 if !ok {
436 // Close may have been called
437 return nil
438 }
439 if msg.Idx == m.nextMessageIdx {
440 m.nextMessageIdx++
441 return msg
442 }
443 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
444 panic("out of order message")
445 }
446 }
447}
448
Sean McCulloughd9d45812025-04-30 16:53:41 -0700449// Assert that Agent satisfies the CodingAgent interface.
450var _ CodingAgent = &Agent{}
451
452// StateName implements CodingAgent.
453func (a *Agent) CurrentStateName() string {
454 if a.stateMachine == nil {
455 return ""
456 }
Josh Bleecher Snydered17fdf2025-05-23 17:26:07 +0000457 return a.stateMachine.CurrentState().String()
Sean McCulloughd9d45812025-04-30 16:53:41 -0700458}
459
Earl Lee2e463fb2025-04-17 11:22:22 -0700460func (a *Agent) URL() string { return a.url }
461
462// Title returns the current title of the conversation.
463// If no title has been set, returns an empty string.
464func (a *Agent) Title() string {
465 a.mu.Lock()
466 defer a.mu.Unlock()
467 return a.title
468}
469
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000470// BranchName returns the git branch name for the conversation.
471func (a *Agent) BranchName() string {
Philip Zeyligerf2872992025-05-22 10:35:28 -0700472 return a.gitState.BranchName()
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000473}
474
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000475// OutstandingLLMCallCount returns the number of outstanding LLM calls.
476func (a *Agent) OutstandingLLMCallCount() int {
477 a.mu.Lock()
478 defer a.mu.Unlock()
479 return len(a.outstandingLLMCalls)
480}
481
482// OutstandingToolCalls returns the names of outstanding tool calls.
483func (a *Agent) OutstandingToolCalls() []string {
484 a.mu.Lock()
485 defer a.mu.Unlock()
486
487 tools := make([]string, 0, len(a.outstandingToolCalls))
488 for _, toolName := range a.outstandingToolCalls {
489 tools = append(tools, toolName)
490 }
491 return tools
492}
493
Earl Lee2e463fb2025-04-17 11:22:22 -0700494// OS returns the operating system of the client.
495func (a *Agent) OS() string {
496 return a.config.ClientGOOS
497}
498
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000499func (a *Agent) SessionID() string {
500 return a.config.SessionID
501}
502
Philip Zeyliger18532b22025-04-23 21:11:46 +0000503// OutsideOS returns the operating system of the outside system.
504func (a *Agent) OutsideOS() string {
505 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000506}
507
Philip Zeyliger18532b22025-04-23 21:11:46 +0000508// OutsideHostname returns the hostname of the outside system.
509func (a *Agent) OutsideHostname() string {
510 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000511}
512
Philip Zeyliger18532b22025-04-23 21:11:46 +0000513// OutsideWorkingDir returns the working directory on the outside system.
514func (a *Agent) OutsideWorkingDir() string {
515 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000516}
517
518// GitOrigin returns the URL of the git remote 'origin' if it exists.
519func (a *Agent) GitOrigin() string {
520 return a.gitOrigin
521}
522
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000523func (a *Agent) OpenBrowser(url string) {
524 if !a.IsInContainer() {
525 browser.Open(url)
526 return
527 }
528 // We're in Docker, need to send a request to the Git server
529 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700530 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000531 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700532 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000533 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700534 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000535 return
536 }
537 defer resp.Body.Close()
538 if resp.StatusCode == http.StatusOK {
539 return
540 }
541 body, _ := io.ReadAll(resp.Body)
542 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
543}
544
Sean McCullough96b60dd2025-04-30 09:49:10 -0700545// CurrentState returns the current state of the agent's state machine.
546func (a *Agent) CurrentState() State {
547 return a.stateMachine.CurrentState()
548}
549
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700550func (a *Agent) IsInContainer() bool {
551 return a.config.InDocker
552}
553
554func (a *Agent) FirstMessageIndex() int {
555 a.mu.Lock()
556 defer a.mu.Unlock()
557 return a.firstMessageIndex
558}
559
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000560// SetTitle sets the title of the conversation.
561func (a *Agent) SetTitle(title string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700562 a.mu.Lock()
563 defer a.mu.Unlock()
564 a.title = title
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000565}
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700566
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000567// SetBranch sets the branch name of the conversation.
568func (a *Agent) SetBranch(branchName string) {
569 a.mu.Lock()
570 defer a.mu.Unlock()
Philip Zeyligerf2872992025-05-22 10:35:28 -0700571 a.gitState.SetBranchName(branchName)
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000572 convo, ok := a.convo.(*conversation.Convo)
573 if ok {
574 convo.ExtraData["branch"] = branchName
575 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700576}
577
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000578// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700579func (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 +0000580 // Track the tool call
581 a.mu.Lock()
582 a.outstandingToolCalls[id] = toolName
583 a.mu.Unlock()
584}
585
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700586// contentToString converts []llm.Content to a string, concatenating all text content and skipping non-text types.
587// If there's only one element in the array and it's a text type, it returns that text directly.
588// It also processes nested ToolResult arrays recursively.
589func contentToString(contents []llm.Content) string {
590 if len(contents) == 0 {
591 return ""
592 }
593
594 // If there's only one element and it's a text type, return it directly
595 if len(contents) == 1 && contents[0].Type == llm.ContentTypeText {
596 return contents[0].Text
597 }
598
599 // Otherwise, concatenate all text content
600 var result strings.Builder
601 for _, content := range contents {
602 if content.Type == llm.ContentTypeText {
603 result.WriteString(content.Text)
604 } else if content.Type == llm.ContentTypeToolResult && len(content.ToolResult) > 0 {
605 // Recursively process nested tool results
606 result.WriteString(contentToString(content.ToolResult))
607 }
608 }
609
610 return result.String()
611}
612
Earl Lee2e463fb2025-04-17 11:22:22 -0700613// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700614func (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 +0000615 // Remove the tool call from outstanding calls
616 a.mu.Lock()
617 delete(a.outstandingToolCalls, toolID)
618 a.mu.Unlock()
619
Earl Lee2e463fb2025-04-17 11:22:22 -0700620 m := AgentMessage{
621 Type: ToolUseMessageType,
622 Content: content.Text,
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700623 ToolResult: contentToString(content.ToolResult),
Earl Lee2e463fb2025-04-17 11:22:22 -0700624 ToolError: content.ToolError,
625 ToolName: toolName,
626 ToolInput: string(toolInput),
627 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700628 StartTime: content.ToolUseStartTime,
629 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700630 }
631
632 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700633 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
634 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700635 m.Elapsed = &elapsed
636 }
637
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700638 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700639 a.pushToOutbox(ctx, m)
640}
641
642// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700643func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000644 a.mu.Lock()
645 defer a.mu.Unlock()
646 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700647 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
648}
649
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700650// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700651// that need to be displayed (as well as tool calls that we send along when
652// they're done). (It would be reasonable to also mention tool calls when they're
653// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700654func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000655 // Remove the LLM call from outstanding calls
656 a.mu.Lock()
657 delete(a.outstandingLLMCalls, id)
658 a.mu.Unlock()
659
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700660 if resp == nil {
661 // LLM API call failed
662 m := AgentMessage{
663 Type: ErrorMessageType,
664 Content: "API call failed, type 'continue' to try again",
665 }
666 m.SetConvo(convo)
667 a.pushToOutbox(ctx, m)
668 return
669 }
670
Earl Lee2e463fb2025-04-17 11:22:22 -0700671 endOfTurn := false
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700672 if convo.Parent == nil { // subconvos never end the turn
673 switch resp.StopReason {
674 case llm.StopReasonToolUse:
675 // Check whether any of the tool calls are for tools that should end the turn
676 ToolSearch:
677 for _, part := range resp.Content {
678 if part.Type != llm.ContentTypeToolUse {
679 continue
680 }
Sean McCullough021557a2025-05-05 23:20:53 +0000681 // Find the tool by name
682 for _, tool := range convo.Tools {
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700683 if tool.Name == part.ToolName {
684 endOfTurn = tool.EndsTurn
685 break ToolSearch
Sean McCullough021557a2025-05-05 23:20:53 +0000686 }
687 }
Sean McCullough021557a2025-05-05 23:20:53 +0000688 }
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700689 default:
690 endOfTurn = true
Sean McCullough021557a2025-05-05 23:20:53 +0000691 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700692 }
693 m := AgentMessage{
694 Type: AgentMessageType,
695 Content: collectTextContent(resp),
696 EndOfTurn: endOfTurn,
697 Usage: &resp.Usage,
698 StartTime: resp.StartTime,
699 EndTime: resp.EndTime,
700 }
701
702 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700703 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700704 var toolCalls []ToolCall
705 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700706 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700707 toolCalls = append(toolCalls, ToolCall{
708 Name: part.ToolName,
709 Input: string(part.ToolInput),
710 ToolCallId: part.ID,
711 })
712 }
713 }
714 m.ToolCalls = toolCalls
715 }
716
717 // Calculate the elapsed time if both start and end times are set
718 if resp.StartTime != nil && resp.EndTime != nil {
719 elapsed := resp.EndTime.Sub(*resp.StartTime)
720 m.Elapsed = &elapsed
721 }
722
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700723 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700724 a.pushToOutbox(ctx, m)
725}
726
727// WorkingDir implements CodingAgent.
728func (a *Agent) WorkingDir() string {
729 return a.workingDir
730}
731
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +0000732// RepoRoot returns the git repository root directory.
733func (a *Agent) RepoRoot() string {
734 return a.repoRoot
735}
736
Earl Lee2e463fb2025-04-17 11:22:22 -0700737// MessageCount implements CodingAgent.
738func (a *Agent) MessageCount() int {
739 a.mu.Lock()
740 defer a.mu.Unlock()
741 return len(a.history)
742}
743
744// Messages implements CodingAgent.
745func (a *Agent) Messages(start int, end int) []AgentMessage {
746 a.mu.Lock()
747 defer a.mu.Unlock()
748 return slices.Clone(a.history[start:end])
749}
750
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700751func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700752 return a.originalBudget
753}
754
755// AgentConfig contains configuration for creating a new Agent.
756type AgentConfig struct {
757 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700758 Service llm.Service
759 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700760 GitUsername string
761 GitEmail string
762 SessionID string
763 ClientGOOS string
764 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700765 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700766 UseAnthropicEdit bool
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000767 OneShot bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700768 WorkingDir string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000769 // Outside information
770 OutsideHostname string
771 OutsideOS string
772 OutsideWorkingDir string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700773
774 // Outtie's HTTP to, e.g., open a browser
775 OutsideHTTP string
776 // Outtie's Git server
777 GitRemoteAddr string
778 // Commit to checkout from Outtie
779 Commit string
Earl Lee2e463fb2025-04-17 11:22:22 -0700780}
781
782// NewAgent creates a new Agent.
783// It is not usable until Init() is called.
784func NewAgent(config AgentConfig) *Agent {
785 agent := &Agent{
Philip Zeyligerf2872992025-05-22 10:35:28 -0700786 config: config,
787 ready: make(chan struct{}),
788 inbox: make(chan string, 100),
789 subscribers: make([]chan *AgentMessage, 0),
790 startedAt: time.Now(),
791 originalBudget: config.Budget,
792 gitState: AgentGitState{
793 seenCommits: make(map[string]bool),
794 gitRemoteAddr: config.GitRemoteAddr,
795 },
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000796 outsideHostname: config.OutsideHostname,
797 outsideOS: config.OutsideOS,
798 outsideWorkingDir: config.OutsideWorkingDir,
799 outstandingLLMCalls: make(map[string]struct{}),
800 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700801 stateMachine: NewStateMachine(),
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700802 workingDir: config.WorkingDir,
803 outsideHTTP: config.OutsideHTTP,
Earl Lee2e463fb2025-04-17 11:22:22 -0700804 }
805 return agent
806}
807
808type AgentInit struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700809 NoGit bool // only for testing
Earl Lee2e463fb2025-04-17 11:22:22 -0700810
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700811 InDocker bool
812 HostAddr string
Earl Lee2e463fb2025-04-17 11:22:22 -0700813}
814
815func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700816 if a.convo != nil {
817 return fmt.Errorf("Agent.Init: already initialized")
818 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700819 ctx := a.config.Context
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700820 slog.InfoContext(ctx, "agent initializing")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700821
Philip Zeyligerf2872992025-05-22 10:35:28 -0700822 // If a remote git addr was specified, we configure the remote
823 if a.gitState.gitRemoteAddr != "" {
824 slog.InfoContext(ctx, "Configuring git remote", slog.String("remote", a.gitState.gitRemoteAddr))
825 cmd := exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", a.gitState.gitRemoteAddr)
826 cmd.Dir = a.workingDir
827 if out, err := cmd.CombinedOutput(); err != nil {
828 return fmt.Errorf("git remote add: %s: %v", out, err)
829 }
830 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
831 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
832 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
833 // origin/main on outtie sketch, which should make it easier to rebase.
834 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
835 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
836 cmd.Dir = a.workingDir
837 if out, err := cmd.CombinedOutput(); err != nil {
838 return fmt.Errorf("git config --add: %s: %v", out, err)
839 }
840 }
841
842 // If a commit was specified, we fetch and reset to it.
843 if a.config.Commit != "" && a.gitState.gitRemoteAddr != "" {
Philip Zeyliger716bfee2025-05-21 18:32:31 -0700844 slog.InfoContext(ctx, "updating git repo", slog.String("commit", a.config.Commit))
845
Earl Lee2e463fb2025-04-17 11:22:22 -0700846 cmd := exec.CommandContext(ctx, "git", "stash")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700847 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700848 if out, err := cmd.CombinedOutput(); err != nil {
849 return fmt.Errorf("git stash: %s: %v", out, err)
850 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000851 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700852 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700853 if out, err := cmd.CombinedOutput(); err != nil {
854 return fmt.Errorf("git fetch: %s: %w", out, err)
855 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700856 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
857 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100858 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
859 // Remove git hooks if they exist and retry
860 // Only try removing hooks if we haven't already removed them during fetch
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700861 hookPath := filepath.Join(a.workingDir, ".git", "hooks")
Pokey Rule7a113622025-05-12 10:58:45 +0100862 if _, statErr := os.Stat(hookPath); statErr == nil {
863 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
864 slog.String("error", err.Error()),
865 slog.String("output", string(checkoutOut)))
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700866 if removeErr := removeGitHooks(ctx, a.workingDir); removeErr != nil {
Pokey Rule7a113622025-05-12 10:58:45 +0100867 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
868 }
869
870 // Retry the checkout operation
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 retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700874 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 +0100875 }
876 } else {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700877 return fmt.Errorf("git checkout %s: %s: %w", a.config.Commit, checkoutOut, err)
Pokey Rule7a113622025-05-12 10:58:45 +0100878 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700879 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700880 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700881
882 if ini.HostAddr != "" {
883 a.url = "http://" + ini.HostAddr
884 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700885
886 if !ini.NoGit {
887 repoRoot, err := repoRoot(ctx, a.workingDir)
888 if err != nil {
889 return fmt.Errorf("repoRoot: %w", err)
890 }
891 a.repoRoot = repoRoot
892
Earl Lee2e463fb2025-04-17 11:22:22 -0700893 if err != nil {
894 return fmt.Errorf("resolveRef: %w", err)
895 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700896
Josh Bleecher Snyder90993a02025-05-28 18:15:15 -0700897 if err := setupGitHooks(a.repoRoot); err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700898 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
899 }
900
Philip Zeyliger49edc922025-05-14 09:45:45 -0700901 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
902 cmd.Dir = repoRoot
903 if out, err := cmd.CombinedOutput(); err != nil {
904 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
905 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700906
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000907 slog.Info("running codebase analysis")
908 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
909 if err != nil {
910 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000911 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000912 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000913
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +0000914 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -0700915 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000916 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700917 }
918 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000919
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700920 a.gitOrigin = getGitOrigin(ctx, a.workingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700921 }
Philip Zeyligerf2872992025-05-22 10:35:28 -0700922 a.gitState.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700923 a.convo = a.initConvo()
924 close(a.ready)
925 return nil
926}
927
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700928//go:embed agent_system_prompt.txt
929var agentSystemPrompt string
930
Earl Lee2e463fb2025-04-17 11:22:22 -0700931// initConvo initializes the conversation.
932// It must not be called until all agent fields are initialized,
933// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700934func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700935 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700936 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700937 convo.PromptCaching = true
938 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000939 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000940 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700941
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000942 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
943 bashPermissionCheck := func(command string) error {
944 // Check if branch name is set
945 a.mu.Lock()
Philip Zeyligerf2872992025-05-22 10:35:28 -0700946 branchSet := a.gitState.BranchName() != ""
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000947 a.mu.Unlock()
948
949 // If branch is set, all commands are allowed
950 if branchSet {
951 return nil
952 }
953
954 // If branch is not set, check if this is a git commit command
955 willCommit, err := bashkit.WillRunGitCommit(command)
956 if err != nil {
957 // If there's an error checking, we should allow the command to proceed
958 return nil
959 }
960
961 // If it's a git commit and branch is not set, return an error
962 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000963 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000964 }
965
966 return nil
967 }
968
969 // Create a custom bash tool with the permission check
970 bashTool := claudetool.NewBashTool(bashPermissionCheck)
971
Earl Lee2e463fb2025-04-17 11:22:22 -0700972 // Register all tools with the conversation
973 // When adding, removing, or modifying tools here, double-check that the termui tool display
974 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000975
976 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700977 _, supportsScreenshots := a.config.Service.(*ant.Service)
978 var bTools []*llm.Tool
979 var browserCleanup func()
980
981 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
982 // Add cleanup function to context cancel
983 go func() {
984 <-a.config.Context.Done()
985 browserCleanup()
986 }()
987 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000988
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700989 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000990 bashTool, claudetool.Keyword,
Josh Bleecher Snyder93202652025-05-08 02:05:57 +0000991 claudetool.Think, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -0700992 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000993 }
994
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000995 // One-shot mode is non-interactive, multiple choice requires human response
996 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700997 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -0700998 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000999
1000 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -07001001 if a.config.UseAnthropicEdit {
1002 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
1003 } else {
1004 convo.Tools = append(convo.Tools, claudetool.Patch)
1005 }
1006 convo.Listener = a
1007 return convo
1008}
1009
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001010var multipleChoiceTool = &llm.Tool{
1011 Name: "multiplechoice",
1012 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.",
1013 EndsTurn: true,
1014 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001015 "type": "object",
1016 "description": "The question and a list of answers you would expect the user to choose from.",
1017 "properties": {
1018 "question": {
1019 "type": "string",
1020 "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?'"
1021 },
1022 "responseOptions": {
1023 "type": "array",
1024 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1025 "items": {
1026 "type": "object",
1027 "properties": {
1028 "caption": {
1029 "type": "string",
1030 "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'"
1031 },
1032 "responseText": {
1033 "type": "string",
1034 "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'"
1035 }
1036 },
1037 "required": ["caption", "responseText"]
1038 }
1039 }
1040 },
1041 "required": ["question", "responseOptions"]
1042}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001043 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1044 // The Run logic for "multiplechoice" tool is a no-op on the server.
1045 // The UI will present a list of options for the user to select from,
1046 // and that's it as far as "executing" the tool_use goes.
1047 // When the user *does* select one of the presented options, that
1048 // responseText gets sent as a chat message on behalf of the user.
1049 return llm.TextContent("end your turn and wait for the user to respond"), nil
1050 },
Sean McCullough485afc62025-04-28 14:28:39 -07001051}
1052
1053type MultipleChoiceOption struct {
1054 Caption string `json:"caption"`
1055 ResponseText string `json:"responseText"`
1056}
1057
1058type MultipleChoiceParams struct {
1059 Question string `json:"question"`
1060 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1061}
1062
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001063// branchExists reports whether branchName exists, either locally or in well-known remotes.
1064func branchExists(dir, branchName string) bool {
1065 refs := []string{
1066 "refs/heads/",
1067 "refs/remotes/origin/",
1068 "refs/remotes/sketch-host/",
1069 }
1070 for _, ref := range refs {
1071 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1072 cmd.Dir = dir
1073 if cmd.Run() == nil { // exit code 0 means branch exists
1074 return true
1075 }
1076 }
1077 return false
1078}
1079
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001080func (a *Agent) titleTool() *llm.Tool {
1081 description := `Sets the conversation title.`
1082 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001083 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001084 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001085 InputSchema: json.RawMessage(`{
1086 "type": "object",
1087 "properties": {
1088 "title": {
1089 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001090 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001091 }
1092 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001093 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001094}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001095 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001096 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001097 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001098 }
1099 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001100 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001101 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001102
1103 // We don't allow changing the title once set to be consistent with the previous behavior
1104 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001105 t := a.Title()
1106 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001107 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001108 }
1109
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001110 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001111 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001112 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001113
1114 a.SetTitle(params.Title)
1115 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001116 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001117 },
1118 }
1119 return titleTool
1120}
1121
1122func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001123 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 +00001124 preCommit := &llm.Tool{
1125 Name: "precommit",
1126 Description: description,
1127 InputSchema: json.RawMessage(`{
1128 "type": "object",
1129 "properties": {
1130 "branch_name": {
1131 "type": "string",
1132 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1133 }
1134 },
1135 "required": ["branch_name"]
1136}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001137 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001138 var params struct {
1139 BranchName string `json:"branch_name"`
1140 }
1141 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001142 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001143 }
1144
1145 b := a.BranchName()
1146 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001147 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001148 }
1149
1150 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001151 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001152 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001153 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001154 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001155 }
1156 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001157 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001158 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001159 }
1160
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001161 a.SetBranch(branchName)
Josh Bleecher Snyderf7bebdd2025-05-14 15:22:24 -07001162 response := fmt.Sprintf("switched to branch sketch/%q - DO NOT change branches unless explicitly requested", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001163
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001164 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1165 if err != nil {
1166 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1167 }
1168 if len(styleHint) > 0 {
1169 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001170 }
1171
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001172 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001173 },
1174 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001175 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001176}
1177
1178func (a *Agent) Ready() <-chan struct{} {
1179 return a.ready
1180}
1181
1182func (a *Agent) UserMessage(ctx context.Context, msg string) {
1183 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1184 a.inbox <- msg
1185}
1186
Earl Lee2e463fb2025-04-17 11:22:22 -07001187func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1188 return a.convo.CancelToolUse(toolUseID, cause)
1189}
1190
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001191func (a *Agent) CancelTurn(cause error) {
1192 a.cancelTurnMu.Lock()
1193 defer a.cancelTurnMu.Unlock()
1194 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001195 // Force state transition to cancelled state
1196 ctx := a.config.Context
1197 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001198 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001199 }
1200}
1201
1202func (a *Agent) Loop(ctxOuter context.Context) {
1203 for {
1204 select {
1205 case <-ctxOuter.Done():
1206 return
1207 default:
1208 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001209 a.cancelTurnMu.Lock()
1210 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001211 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001212 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001213 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001214 a.cancelTurn = cancel
1215 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001216 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1217 if err != nil {
1218 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1219 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001220 cancel(nil)
1221 }
1222 }
1223}
1224
1225func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1226 if m.Timestamp.IsZero() {
1227 m.Timestamp = time.Now()
1228 }
1229
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001230 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1231 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1232 m.Content = m.ToolResult
1233 }
1234
Earl Lee2e463fb2025-04-17 11:22:22 -07001235 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1236 if m.EndOfTurn && m.Type == AgentMessageType {
1237 turnDuration := time.Since(a.startOfTurn)
1238 m.TurnDuration = &turnDuration
1239 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1240 }
1241
Earl Lee2e463fb2025-04-17 11:22:22 -07001242 a.mu.Lock()
1243 defer a.mu.Unlock()
1244 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001245 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001246 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001247
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001248 // Notify all subscribers
1249 for _, ch := range a.subscribers {
1250 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001251 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001252}
1253
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001254func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1255 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001256 if block {
1257 select {
1258 case <-ctx.Done():
1259 return m, ctx.Err()
1260 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001261 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001262 }
1263 }
1264 for {
1265 select {
1266 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001267 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001268 default:
1269 return m, nil
1270 }
1271 }
1272}
1273
Sean McCullough885a16a2025-04-30 02:49:25 +00001274// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001275func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001276 // Reset the start of turn time
1277 a.startOfTurn = time.Now()
1278
Sean McCullough96b60dd2025-04-30 09:49:10 -07001279 // Transition to waiting for user input state
1280 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1281
Sean McCullough885a16a2025-04-30 02:49:25 +00001282 // Process initial user message
1283 initialResp, err := a.processUserMessage(ctx)
1284 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001285 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001286 return err
1287 }
1288
1289 // Handle edge case where both initialResp and err are nil
1290 if initialResp == nil {
1291 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001292 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1293
Sean McCullough9f4b8082025-04-30 17:34:07 +00001294 a.pushToOutbox(ctx, errorMessage(err))
1295 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001296 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001297
Earl Lee2e463fb2025-04-17 11:22:22 -07001298 // We do this as we go, but let's also do it at the end of the turn
1299 defer func() {
1300 if _, err := a.handleGitCommits(ctx); err != nil {
1301 // Just log the error, don't stop execution
1302 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1303 }
1304 }()
1305
Sean McCullougha1e0e492025-05-01 10:51:08 -07001306 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001307 resp := initialResp
1308 for {
1309 // Check if we are over budget
1310 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001311 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001312 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001313 }
1314
1315 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001316 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001317 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001318 break
1319 }
1320
Sean McCullough96b60dd2025-04-30 09:49:10 -07001321 // Transition to tool use requested state
1322 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1323
Sean McCullough885a16a2025-04-30 02:49:25 +00001324 // Handle tool execution
1325 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1326 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001327 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001328 }
1329
Sean McCullougha1e0e492025-05-01 10:51:08 -07001330 if toolResp == nil {
1331 return fmt.Errorf("cannot continue conversation with a nil tool response")
1332 }
1333
Sean McCullough885a16a2025-04-30 02:49:25 +00001334 // Set the response for the next iteration
1335 resp = toolResp
1336 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001337
1338 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001339}
1340
1341// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001342func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001343 // Wait for at least one message from the user
1344 msgs, err := a.GatherMessages(ctx, true)
1345 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001346 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001347 return nil, err
1348 }
1349
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001350 userMessage := llm.Message{
1351 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001352 Content: msgs,
1353 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001354
Sean McCullough96b60dd2025-04-30 09:49:10 -07001355 // Transition to sending to LLM state
1356 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1357
Sean McCullough885a16a2025-04-30 02:49:25 +00001358 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001359 resp, err := a.convo.SendMessage(userMessage)
1360 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001361 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001362 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001363 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001364 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001365
Sean McCullough96b60dd2025-04-30 09:49:10 -07001366 // Transition to processing LLM response state
1367 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1368
Sean McCullough885a16a2025-04-30 02:49:25 +00001369 return resp, nil
1370}
1371
1372// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001373func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1374 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001375 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001376 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001377
Sean McCullough96b60dd2025-04-30 09:49:10 -07001378 // Transition to checking for cancellation state
1379 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1380
Sean McCullough885a16a2025-04-30 02:49:25 +00001381 // Check if the operation was cancelled by the user
1382 select {
1383 case <-ctx.Done():
1384 // Don't actually run any of the tools, but rather build a response
1385 // for each tool_use message letting the LLM know that user canceled it.
1386 var err error
1387 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001388 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001389 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001390 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001391 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001392 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001393 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001394 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001395 // Transition to running tool state
1396 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1397
Sean McCullough885a16a2025-04-30 02:49:25 +00001398 // Add working directory to context for tool execution
1399 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1400
1401 // Execute the tools
1402 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001403 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001404 if ctx.Err() != nil { // e.g. the user canceled the operation
1405 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001406 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001407 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001408 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001409 a.pushToOutbox(ctx, errorMessage(err))
1410 }
1411 }
1412
1413 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001414 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001415 autoqualityMessages := a.processGitChanges(ctx)
1416
1417 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001418 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001419 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001420 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001421 return false, nil
1422 }
1423
1424 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001425 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1426 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001427}
1428
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001429// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001430func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001431 // Check for git commits
1432 _, err := a.handleGitCommits(ctx)
1433 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001434 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001435 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001436 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001437 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001438}
1439
1440// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1441// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001442func (a *Agent) processGitChanges(ctx context.Context) []string {
1443 // Check for git commits after tool execution
1444 newCommits, err := a.handleGitCommits(ctx)
1445 if err != nil {
1446 // Just log the error, don't stop execution
1447 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1448 return nil
1449 }
1450
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001451 // Run mechanical checks if there was exactly one new commit.
1452 if len(newCommits) != 1 {
1453 return nil
1454 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001455 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001456 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1457 msg := a.codereview.RunMechanicalChecks(ctx)
1458 if msg != "" {
1459 a.pushToOutbox(ctx, AgentMessage{
1460 Type: AutoMessageType,
1461 Content: msg,
1462 Timestamp: time.Now(),
1463 })
1464 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001465 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001466
1467 return autoqualityMessages
1468}
1469
1470// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001471func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001472 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001473 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001474 msgs, err := a.GatherMessages(ctx, false)
1475 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001476 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001477 return false, nil
1478 }
1479
1480 // Inject any auto-generated messages from quality checks
1481 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001482 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001483 }
1484
1485 // Handle cancellation by appending a message about it
1486 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001487 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001488 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001489 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001490 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1491 } else if err := a.convo.OverBudget(); err != nil {
1492 // Handle budget issues by appending a message about it
1493 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 -07001494 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001495 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1496 }
1497
1498 // Combine tool results with user messages
1499 results = append(results, msgs...)
1500
1501 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001502 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001503 resp, err := a.convo.SendMessage(llm.Message{
1504 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001505 Content: results,
1506 })
1507 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001508 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001509 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1510 return true, nil // Return true to continue the conversation, but with no response
1511 }
1512
Sean McCullough96b60dd2025-04-30 09:49:10 -07001513 // Transition back to processing LLM response
1514 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1515
Sean McCullough885a16a2025-04-30 02:49:25 +00001516 if cancelled {
1517 return false, nil
1518 }
1519
1520 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001521}
1522
1523func (a *Agent) overBudget(ctx context.Context) error {
1524 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001525 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001526 m := budgetMessage(err)
1527 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001528 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001529 a.convo.ResetBudget(a.originalBudget)
1530 return err
1531 }
1532 return nil
1533}
1534
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001535func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001536 // Collect all text content
1537 var allText strings.Builder
1538 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001539 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001540 if allText.Len() > 0 {
1541 allText.WriteString("\n\n")
1542 }
1543 allText.WriteString(content.Text)
1544 }
1545 }
1546 return allText.String()
1547}
1548
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001549func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001550 a.mu.Lock()
1551 defer a.mu.Unlock()
1552 return a.convo.CumulativeUsage()
1553}
1554
Earl Lee2e463fb2025-04-17 11:22:22 -07001555// Diff returns a unified diff of changes made since the agent was instantiated.
1556func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001557 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001558 return "", fmt.Errorf("no initial commit reference available")
1559 }
1560
1561 // Find the repository root
1562 ctx := context.Background()
1563
1564 // If a specific commit hash is provided, show just that commit's changes
1565 if commit != nil && *commit != "" {
1566 // Validate that the commit looks like a valid git SHA
1567 if !isValidGitSHA(*commit) {
1568 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1569 }
1570
1571 // Get the diff for just this commit
1572 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1573 cmd.Dir = a.repoRoot
1574 output, err := cmd.CombinedOutput()
1575 if err != nil {
1576 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1577 }
1578 return string(output), nil
1579 }
1580
1581 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001582 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001583 cmd.Dir = a.repoRoot
1584 output, err := cmd.CombinedOutput()
1585 if err != nil {
1586 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1587 }
1588
1589 return string(output), nil
1590}
1591
Philip Zeyliger49edc922025-05-14 09:45:45 -07001592// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1593// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1594func (a *Agent) SketchGitBaseRef() string {
1595 if a.IsInContainer() {
1596 return "sketch-base"
1597 } else {
1598 return "sketch-base-" + a.SessionID()
1599 }
1600}
1601
1602// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1603func (a *Agent) SketchGitBase() string {
1604 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1605 cmd.Dir = a.repoRoot
1606 output, err := cmd.CombinedOutput()
1607 if err != nil {
1608 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1609 return "HEAD"
1610 }
1611 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001612}
1613
Pokey Rule7a113622025-05-12 10:58:45 +01001614// removeGitHooks removes the Git hooks directory from the repository
1615func removeGitHooks(_ context.Context, repoPath string) error {
1616 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1617
1618 // Check if hooks directory exists
1619 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1620 // Directory doesn't exist, nothing to do
1621 return nil
1622 }
1623
1624 // Remove the hooks directory
1625 err := os.RemoveAll(hooksDir)
1626 if err != nil {
1627 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1628 }
1629
1630 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001631 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001632 if err != nil {
1633 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1634 }
1635
1636 return nil
1637}
1638
Philip Zeyligerf2872992025-05-22 10:35:28 -07001639func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1640 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef())
1641 for _, msg := range msgs {
1642 a.pushToOutbox(ctx, msg)
1643 }
1644 return commits, error
1645}
1646
Earl Lee2e463fb2025-04-17 11:22:22 -07001647// handleGitCommits() highlights new commits to the user. When running
1648// under docker, new HEADs are pushed to a branch according to the title.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001649func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string) ([]AgentMessage, []*GitCommit, error) {
1650 ags.mu.Lock()
1651 defer ags.mu.Unlock()
1652
1653 msgs := []AgentMessage{}
1654 if repoRoot == "" {
1655 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001656 }
1657
Philip Zeyligerf2872992025-05-22 10:35:28 -07001658 head, err := resolveRef(ctx, repoRoot, "HEAD")
Earl Lee2e463fb2025-04-17 11:22:22 -07001659 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001660 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001661 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001662 if head == ags.lastHEAD {
1663 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001664 }
1665 defer func() {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001666 ags.lastHEAD = head
Earl Lee2e463fb2025-04-17 11:22:22 -07001667 }()
1668
1669 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1670 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1671 // to the last 100 commits.
1672 var commits []*GitCommit
1673
1674 // Get commits since the initial commit
1675 // Format: <hash>\0<subject>\0<body>\0
1676 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1677 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyligerf2872992025-05-22 10:35:28 -07001678 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+baseRef, head)
1679 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07001680 output, err := cmd.Output()
1681 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001682 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07001683 }
1684
1685 // Parse git log output and filter out already seen commits
1686 parsedCommits := parseGitLog(string(output))
1687
1688 var headCommit *GitCommit
1689
1690 // Filter out commits we've already seen
1691 for _, commit := range parsedCommits {
1692 if commit.Hash == head {
1693 headCommit = &commit
1694 }
1695
1696 // Skip if we've seen this commit before. If our head has changed, always include that.
Philip Zeyligerf2872992025-05-22 10:35:28 -07001697 if ags.seenCommits[commit.Hash] && commit.Hash != head {
Earl Lee2e463fb2025-04-17 11:22:22 -07001698 continue
1699 }
1700
1701 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07001702 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07001703
1704 // Add to our list of new commits
1705 commits = append(commits, &commit)
1706 }
1707
Philip Zeyligerf2872992025-05-22 10:35:28 -07001708 if ags.gitRemoteAddr != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001709 if headCommit == nil {
1710 // I think this can only happen if we have a bug or if there's a race.
1711 headCommit = &GitCommit{}
1712 headCommit.Hash = head
1713 headCommit.Subject = "unknown"
1714 commits = append(commits, headCommit)
1715 }
1716
Philip Zeyligerf2872992025-05-22 10:35:28 -07001717 originalBranch := cmp.Or(ags.branchName, "sketch/"+sessionID)
Philip Zeyliger113e2052025-05-09 21:59:40 +00001718 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001719
1720 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1721 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1722 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001723
1724 // Try up to 10 times with different branch names if the branch is checked out on the remote
1725 var out []byte
1726 var err error
1727 for retries := range 10 {
1728 if retries > 0 {
1729 // Add a numeric suffix to the branch name
1730 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1731 }
1732
Philip Zeyligerf2872992025-05-22 10:35:28 -07001733 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1734 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00001735 out, err = cmd.CombinedOutput()
1736
1737 if err == nil {
1738 // Success! Break out of the retry loop
1739 break
1740 }
1741
1742 // Check if this is the "refusing to update checked out branch" error
1743 if !strings.Contains(string(out), "refusing to update checked out branch") {
1744 // This is a different error, so don't retry
1745 break
1746 }
1747
1748 // If we're on the last retry, we'll report the error
1749 if retries == 9 {
1750 break
1751 }
1752 }
1753
1754 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001755 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001756 } else {
1757 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001758 // Update the agent's branch name if we ended up using a different one
1759 if branch != originalBranch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001760 ags.branchName = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001761 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001762 }
1763 }
1764
1765 // If we found new commits, create a message
1766 if len(commits) > 0 {
1767 msg := AgentMessage{
1768 Type: CommitMessageType,
1769 Timestamp: time.Now(),
1770 Commits: commits,
1771 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001772 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001773 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07001774 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001775}
1776
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001777func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001778 return strings.Map(func(r rune) rune {
1779 // lowercase
1780 if r >= 'A' && r <= 'Z' {
1781 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001782 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001783 // replace spaces with dashes
1784 if r == ' ' {
1785 return '-'
1786 }
1787 // allow alphanumerics and dashes
1788 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1789 return r
1790 }
1791 return -1
1792 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001793}
1794
1795// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1796// and returns an array of GitCommit structs.
1797func parseGitLog(output string) []GitCommit {
1798 var commits []GitCommit
1799
1800 // No output means no commits
1801 if len(output) == 0 {
1802 return commits
1803 }
1804
1805 // Split by NULL byte
1806 parts := strings.Split(output, "\x00")
1807
1808 // Process in triplets (hash, subject, body)
1809 for i := 0; i < len(parts); i++ {
1810 // Skip empty parts
1811 if parts[i] == "" {
1812 continue
1813 }
1814
1815 // This should be a hash
1816 hash := strings.TrimSpace(parts[i])
1817
1818 // Make sure we have at least a subject part available
1819 if i+1 >= len(parts) {
1820 break // No more parts available
1821 }
1822
1823 // Get the subject
1824 subject := strings.TrimSpace(parts[i+1])
1825
1826 // Get the body if available
1827 body := ""
1828 if i+2 < len(parts) {
1829 body = strings.TrimSpace(parts[i+2])
1830 }
1831
1832 // Skip to the next triplet
1833 i += 2
1834
1835 commits = append(commits, GitCommit{
1836 Hash: hash,
1837 Subject: subject,
1838 Body: body,
1839 })
1840 }
1841
1842 return commits
1843}
1844
1845func repoRoot(ctx context.Context, dir string) (string, error) {
1846 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1847 stderr := new(strings.Builder)
1848 cmd.Stderr = stderr
1849 cmd.Dir = dir
1850 out, err := cmd.Output()
1851 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001852 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07001853 }
1854 return strings.TrimSpace(string(out)), nil
1855}
1856
1857func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1858 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1859 stderr := new(strings.Builder)
1860 cmd.Stderr = stderr
1861 cmd.Dir = dir
1862 out, err := cmd.Output()
1863 if err != nil {
1864 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1865 }
1866 // TODO: validate that out is valid hex
1867 return strings.TrimSpace(string(out)), nil
1868}
1869
1870// isValidGitSHA validates if a string looks like a valid git SHA hash.
1871// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1872func isValidGitSHA(sha string) bool {
1873 // Git SHA must be a hexadecimal string with at least 4 characters
1874 if len(sha) < 4 || len(sha) > 40 {
1875 return false
1876 }
1877
1878 // Check if the string only contains hexadecimal characters
1879 for _, char := range sha {
1880 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1881 return false
1882 }
1883 }
1884
1885 return true
1886}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001887
1888// getGitOrigin returns the URL of the git remote 'origin' if it exists
1889func getGitOrigin(ctx context.Context, dir string) string {
1890 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1891 cmd.Dir = dir
1892 stderr := new(strings.Builder)
1893 cmd.Stderr = stderr
1894 out, err := cmd.Output()
1895 if err != nil {
1896 return ""
1897 }
1898 return strings.TrimSpace(string(out))
1899}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001900
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001901// systemPromptData contains the data used to render the system prompt template
1902type systemPromptData struct {
1903 EditPrompt string
1904 ClientGOOS string
1905 ClientGOARCH string
1906 WorkingDir string
1907 RepoRoot string
1908 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001909 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001910}
1911
1912// renderSystemPrompt renders the system prompt template.
1913func (a *Agent) renderSystemPrompt() string {
1914 // Determine the appropriate edit prompt based on config
1915 var editPrompt string
1916 if a.config.UseAnthropicEdit {
1917 editPrompt = "Then use the str_replace_editor tool to make those edits. For short complete file replacements, you may use the bash tool with cat and heredoc stdin."
1918 } else {
1919 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
1920 }
1921
1922 data := systemPromptData{
1923 EditPrompt: editPrompt,
1924 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}