blob: e26bad0ba3d5ac554b1cc9ec999b6dcdd61bafdd [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
81
82 // Diff returns a unified diff of changes made since the agent was instantiated.
83 // If commit is non-nil, it shows the diff for just that specific commit.
84 Diff(commit *string) (string, error)
85
Philip Zeyliger49edc922025-05-14 09:45:45 -070086 // SketchGitBase returns the commit that's the "base" for Sketch's work. It
87 // starts out as the commit where sketch started, but a user can move it if need
88 // be, for example in the case of a rebase. It is stored as a git tag.
89 SketchGitBase() string
Earl Lee2e463fb2025-04-17 11:22:22 -070090
Philip Zeyligerd3ac1122025-05-14 02:54:18 +000091 // SketchGitBase returns the symbolic name for the "base" for Sketch's work.
92 // (Typically, this is "sketch-base")
93 SketchGitBaseRef() string
94
Earl Lee2e463fb2025-04-17 11:22:22 -070095 // Title returns the current title of the conversation.
96 Title() string
97
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000098 // BranchName returns the git branch name for the conversation.
99 BranchName() string
100
Earl Lee2e463fb2025-04-17 11:22:22 -0700101 // OS returns the operating system of the client.
102 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000103
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000104 // SessionID returns the unique session identifier.
105 SessionID() string
106
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000107 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
108 OutstandingLLMCallCount() int
109
110 // OutstandingToolCalls returns the names of outstanding tool calls.
111 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000112 OutsideOS() string
113 OutsideHostname() string
114 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000115 GitOrigin() string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000116 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
117 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700118
119 // RestartConversation resets the conversation history
120 RestartConversation(ctx context.Context, rev string, initialPrompt string) error
121 // SuggestReprompt suggests a re-prompt based on the current conversation.
122 SuggestReprompt(ctx context.Context) (string, error)
123 // 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
298type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700299 convo ConvoInterface
300 config AgentConfig // config for this agent
301 workingDir string
302 repoRoot string // workingDir may be a subdir of repoRoot
303 url string
304 firstMessageIndex int // index of the first message in the current conversation
305 lastHEAD string // hash of the last HEAD that was pushed to the host (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700306 gitRemoteAddr string // HTTP URL of the host git repo (only when under docker)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000307 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700308 ready chan struct{} // closed when the agent is initialized (only when under docker)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000309 codebase *onstart.Codebase
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700310 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700311 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700312 title string
313 branchName string
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000314 codereview *codereview.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700315 // State machine to track agent state
316 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000317 // Outside information
318 outsideHostname string
319 outsideOS string
320 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000321 // URL of the git remote 'origin' if it exists
322 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700323
324 // Time when the current turn started (reset at the beginning of InnerLoop)
325 startOfTurn time.Time
326
327 // Inbox - for messages from the user to the agent.
328 // sent on by UserMessage
329 // . e.g. when user types into the chat textarea
330 // read from by GatherMessages
331 inbox chan string
332
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000333 // protects cancelTurn
334 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700335 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000336 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700337
338 // protects following
339 mu sync.Mutex
340
341 // Stores all messages for this agent
342 history []AgentMessage
343
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700344 // Iterators add themselves here when they're ready to be notified of new messages.
345 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700346
347 // Track git commits we've already seen (by hash)
348 seenCommits map[string]bool
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000349
350 // Track outstanding LLM call IDs
351 outstandingLLMCalls map[string]struct{}
352
353 // Track outstanding tool calls by ID with their names
354 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700355}
356
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700357// NewIterator implements CodingAgent.
358func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
359 a.mu.Lock()
360 defer a.mu.Unlock()
361
362 return &MessageIteratorImpl{
363 agent: a,
364 ctx: ctx,
365 nextMessageIdx: nextMessageIdx,
366 ch: make(chan *AgentMessage, 100),
367 }
368}
369
370type MessageIteratorImpl struct {
371 agent *Agent
372 ctx context.Context
373 nextMessageIdx int
374 ch chan *AgentMessage
375 subscribed bool
376}
377
378func (m *MessageIteratorImpl) Close() {
379 m.agent.mu.Lock()
380 defer m.agent.mu.Unlock()
381 // Delete ourselves from the subscribers list
382 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
383 return x == m.ch
384 })
385 close(m.ch)
386}
387
388func (m *MessageIteratorImpl) Next() *AgentMessage {
389 // We avoid subscription at creation to let ourselves catch up to "current state"
390 // before subscribing.
391 if !m.subscribed {
392 m.agent.mu.Lock()
393 if m.nextMessageIdx < len(m.agent.history) {
394 msg := &m.agent.history[m.nextMessageIdx]
395 m.nextMessageIdx++
396 m.agent.mu.Unlock()
397 return msg
398 }
399 // The next message doesn't exist yet, so let's subscribe
400 m.agent.subscribers = append(m.agent.subscribers, m.ch)
401 m.subscribed = true
402 m.agent.mu.Unlock()
403 }
404
405 for {
406 select {
407 case <-m.ctx.Done():
408 m.agent.mu.Lock()
409 // Delete ourselves from the subscribers list
410 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
411 return x == m.ch
412 })
413 m.subscribed = false
414 m.agent.mu.Unlock()
415 return nil
416 case msg, ok := <-m.ch:
417 if !ok {
418 // Close may have been called
419 return nil
420 }
421 if msg.Idx == m.nextMessageIdx {
422 m.nextMessageIdx++
423 return msg
424 }
425 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
426 panic("out of order message")
427 }
428 }
429}
430
Sean McCulloughd9d45812025-04-30 16:53:41 -0700431// Assert that Agent satisfies the CodingAgent interface.
432var _ CodingAgent = &Agent{}
433
434// StateName implements CodingAgent.
435func (a *Agent) CurrentStateName() string {
436 if a.stateMachine == nil {
437 return ""
438 }
439 return a.stateMachine.currentState.String()
440}
441
Earl Lee2e463fb2025-04-17 11:22:22 -0700442func (a *Agent) URL() string { return a.url }
443
444// Title returns the current title of the conversation.
445// If no title has been set, returns an empty string.
446func (a *Agent) Title() string {
447 a.mu.Lock()
448 defer a.mu.Unlock()
449 return a.title
450}
451
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000452// BranchName returns the git branch name for the conversation.
453func (a *Agent) BranchName() string {
454 a.mu.Lock()
455 defer a.mu.Unlock()
456 return a.branchName
457}
458
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000459// OutstandingLLMCallCount returns the number of outstanding LLM calls.
460func (a *Agent) OutstandingLLMCallCount() int {
461 a.mu.Lock()
462 defer a.mu.Unlock()
463 return len(a.outstandingLLMCalls)
464}
465
466// OutstandingToolCalls returns the names of outstanding tool calls.
467func (a *Agent) OutstandingToolCalls() []string {
468 a.mu.Lock()
469 defer a.mu.Unlock()
470
471 tools := make([]string, 0, len(a.outstandingToolCalls))
472 for _, toolName := range a.outstandingToolCalls {
473 tools = append(tools, toolName)
474 }
475 return tools
476}
477
Earl Lee2e463fb2025-04-17 11:22:22 -0700478// OS returns the operating system of the client.
479func (a *Agent) OS() string {
480 return a.config.ClientGOOS
481}
482
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000483func (a *Agent) SessionID() string {
484 return a.config.SessionID
485}
486
Philip Zeyliger18532b22025-04-23 21:11:46 +0000487// OutsideOS returns the operating system of the outside system.
488func (a *Agent) OutsideOS() string {
489 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000490}
491
Philip Zeyliger18532b22025-04-23 21:11:46 +0000492// OutsideHostname returns the hostname of the outside system.
493func (a *Agent) OutsideHostname() string {
494 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000495}
496
Philip Zeyliger18532b22025-04-23 21:11:46 +0000497// OutsideWorkingDir returns the working directory on the outside system.
498func (a *Agent) OutsideWorkingDir() string {
499 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000500}
501
502// GitOrigin returns the URL of the git remote 'origin' if it exists.
503func (a *Agent) GitOrigin() string {
504 return a.gitOrigin
505}
506
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000507func (a *Agent) OpenBrowser(url string) {
508 if !a.IsInContainer() {
509 browser.Open(url)
510 return
511 }
512 // We're in Docker, need to send a request to the Git server
513 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700514 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000515 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700516 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000517 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700518 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000519 return
520 }
521 defer resp.Body.Close()
522 if resp.StatusCode == http.StatusOK {
523 return
524 }
525 body, _ := io.ReadAll(resp.Body)
526 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
527}
528
Sean McCullough96b60dd2025-04-30 09:49:10 -0700529// CurrentState returns the current state of the agent's state machine.
530func (a *Agent) CurrentState() State {
531 return a.stateMachine.CurrentState()
532}
533
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700534func (a *Agent) IsInContainer() bool {
535 return a.config.InDocker
536}
537
538func (a *Agent) FirstMessageIndex() int {
539 a.mu.Lock()
540 defer a.mu.Unlock()
541 return a.firstMessageIndex
542}
543
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000544// SetTitle sets the title of the conversation.
545func (a *Agent) SetTitle(title string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700546 a.mu.Lock()
547 defer a.mu.Unlock()
548 a.title = title
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000549}
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700550
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000551// SetBranch sets the branch name of the conversation.
552func (a *Agent) SetBranch(branchName string) {
553 a.mu.Lock()
554 defer a.mu.Unlock()
555 a.branchName = branchName
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000556 convo, ok := a.convo.(*conversation.Convo)
557 if ok {
558 convo.ExtraData["branch"] = branchName
559 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700560}
561
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000562// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700563func (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 +0000564 // Track the tool call
565 a.mu.Lock()
566 a.outstandingToolCalls[id] = toolName
567 a.mu.Unlock()
568}
569
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700570// contentToString converts []llm.Content to a string, concatenating all text content and skipping non-text types.
571// If there's only one element in the array and it's a text type, it returns that text directly.
572// It also processes nested ToolResult arrays recursively.
573func contentToString(contents []llm.Content) string {
574 if len(contents) == 0 {
575 return ""
576 }
577
578 // If there's only one element and it's a text type, return it directly
579 if len(contents) == 1 && contents[0].Type == llm.ContentTypeText {
580 return contents[0].Text
581 }
582
583 // Otherwise, concatenate all text content
584 var result strings.Builder
585 for _, content := range contents {
586 if content.Type == llm.ContentTypeText {
587 result.WriteString(content.Text)
588 } else if content.Type == llm.ContentTypeToolResult && len(content.ToolResult) > 0 {
589 // Recursively process nested tool results
590 result.WriteString(contentToString(content.ToolResult))
591 }
592 }
593
594 return result.String()
595}
596
Earl Lee2e463fb2025-04-17 11:22:22 -0700597// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700598func (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 +0000599 // Remove the tool call from outstanding calls
600 a.mu.Lock()
601 delete(a.outstandingToolCalls, toolID)
602 a.mu.Unlock()
603
Earl Lee2e463fb2025-04-17 11:22:22 -0700604 m := AgentMessage{
605 Type: ToolUseMessageType,
606 Content: content.Text,
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700607 ToolResult: contentToString(content.ToolResult),
Earl Lee2e463fb2025-04-17 11:22:22 -0700608 ToolError: content.ToolError,
609 ToolName: toolName,
610 ToolInput: string(toolInput),
611 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700612 StartTime: content.ToolUseStartTime,
613 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700614 }
615
616 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700617 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
618 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700619 m.Elapsed = &elapsed
620 }
621
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700622 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700623 a.pushToOutbox(ctx, m)
624}
625
626// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700627func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000628 a.mu.Lock()
629 defer a.mu.Unlock()
630 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700631 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
632}
633
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700634// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700635// that need to be displayed (as well as tool calls that we send along when
636// they're done). (It would be reasonable to also mention tool calls when they're
637// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700638func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000639 // Remove the LLM call from outstanding calls
640 a.mu.Lock()
641 delete(a.outstandingLLMCalls, id)
642 a.mu.Unlock()
643
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700644 if resp == nil {
645 // LLM API call failed
646 m := AgentMessage{
647 Type: ErrorMessageType,
648 Content: "API call failed, type 'continue' to try again",
649 }
650 m.SetConvo(convo)
651 a.pushToOutbox(ctx, m)
652 return
653 }
654
Earl Lee2e463fb2025-04-17 11:22:22 -0700655 endOfTurn := false
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700656 if convo.Parent == nil { // subconvos never end the turn
657 switch resp.StopReason {
658 case llm.StopReasonToolUse:
659 // Check whether any of the tool calls are for tools that should end the turn
660 ToolSearch:
661 for _, part := range resp.Content {
662 if part.Type != llm.ContentTypeToolUse {
663 continue
664 }
Sean McCullough021557a2025-05-05 23:20:53 +0000665 // Find the tool by name
666 for _, tool := range convo.Tools {
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700667 if tool.Name == part.ToolName {
668 endOfTurn = tool.EndsTurn
669 break ToolSearch
Sean McCullough021557a2025-05-05 23:20:53 +0000670 }
671 }
Sean McCullough021557a2025-05-05 23:20:53 +0000672 }
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700673 default:
674 endOfTurn = true
Sean McCullough021557a2025-05-05 23:20:53 +0000675 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700676 }
677 m := AgentMessage{
678 Type: AgentMessageType,
679 Content: collectTextContent(resp),
680 EndOfTurn: endOfTurn,
681 Usage: &resp.Usage,
682 StartTime: resp.StartTime,
683 EndTime: resp.EndTime,
684 }
685
686 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700687 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700688 var toolCalls []ToolCall
689 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700690 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700691 toolCalls = append(toolCalls, ToolCall{
692 Name: part.ToolName,
693 Input: string(part.ToolInput),
694 ToolCallId: part.ID,
695 })
696 }
697 }
698 m.ToolCalls = toolCalls
699 }
700
701 // Calculate the elapsed time if both start and end times are set
702 if resp.StartTime != nil && resp.EndTime != nil {
703 elapsed := resp.EndTime.Sub(*resp.StartTime)
704 m.Elapsed = &elapsed
705 }
706
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700707 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700708 a.pushToOutbox(ctx, m)
709}
710
711// WorkingDir implements CodingAgent.
712func (a *Agent) WorkingDir() string {
713 return a.workingDir
714}
715
716// MessageCount implements CodingAgent.
717func (a *Agent) MessageCount() int {
718 a.mu.Lock()
719 defer a.mu.Unlock()
720 return len(a.history)
721}
722
723// Messages implements CodingAgent.
724func (a *Agent) Messages(start int, end int) []AgentMessage {
725 a.mu.Lock()
726 defer a.mu.Unlock()
727 return slices.Clone(a.history[start:end])
728}
729
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700730func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700731 return a.originalBudget
732}
733
734// AgentConfig contains configuration for creating a new Agent.
735type AgentConfig struct {
736 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700737 Service llm.Service
738 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700739 GitUsername string
740 GitEmail string
741 SessionID string
742 ClientGOOS string
743 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700744 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700745 UseAnthropicEdit bool
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000746 OneShot bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700747 WorkingDir string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000748 // Outside information
749 OutsideHostname string
750 OutsideOS string
751 OutsideWorkingDir string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700752
753 // Outtie's HTTP to, e.g., open a browser
754 OutsideHTTP string
755 // Outtie's Git server
756 GitRemoteAddr string
757 // Commit to checkout from Outtie
758 Commit string
Earl Lee2e463fb2025-04-17 11:22:22 -0700759}
760
761// NewAgent creates a new Agent.
762// It is not usable until Init() is called.
763func NewAgent(config AgentConfig) *Agent {
764 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000765 config: config,
766 ready: make(chan struct{}),
767 inbox: make(chan string, 100),
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700768 subscribers: make([]chan *AgentMessage, 0),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000769 startedAt: time.Now(),
770 originalBudget: config.Budget,
771 seenCommits: make(map[string]bool),
772 outsideHostname: config.OutsideHostname,
773 outsideOS: config.OutsideOS,
774 outsideWorkingDir: config.OutsideWorkingDir,
775 outstandingLLMCalls: make(map[string]struct{}),
776 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700777 stateMachine: NewStateMachine(),
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700778 workingDir: config.WorkingDir,
779 outsideHTTP: config.OutsideHTTP,
780 gitRemoteAddr: config.GitRemoteAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700781 }
782 return agent
783}
784
785type AgentInit struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700786 NoGit bool // only for testing
Earl Lee2e463fb2025-04-17 11:22:22 -0700787
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700788 InDocker bool
789 HostAddr string
Earl Lee2e463fb2025-04-17 11:22:22 -0700790}
791
792func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700793 if a.convo != nil {
794 return fmt.Errorf("Agent.Init: already initialized")
795 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700796 ctx := a.config.Context
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700797
798 // Fetch, if so configured.
799 if ini.InDocker && a.config.Commit != "" && a.config.GitRemoteAddr != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -0700800 cmd := exec.CommandContext(ctx, "git", "stash")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700801 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700802 if out, err := cmd.CombinedOutput(); err != nil {
803 return fmt.Errorf("git stash: %s: %v", out, err)
804 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700805 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
806 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
807 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
808 // origin/main on outtie sketch, which should make it easier to rebase.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700809 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", a.gitRemoteAddr)
810 cmd.Dir = a.workingDir
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700811 if out, err := cmd.CombinedOutput(); err != nil {
812 return fmt.Errorf("git remote add: %s: %v", out, err)
813 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700814 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
815 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700816 cmd.Dir = a.workingDir
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700817 if out, err := cmd.CombinedOutput(); err != nil {
818 return fmt.Errorf("git config --add: %s: %v", out, err)
819 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000820 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700821 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -0700822 if out, err := cmd.CombinedOutput(); err != nil {
823 return fmt.Errorf("git fetch: %s: %w", out, err)
824 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700825 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
826 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100827 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
828 // Remove git hooks if they exist and retry
829 // Only try removing hooks if we haven't already removed them during fetch
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700830 hookPath := filepath.Join(a.workingDir, ".git", "hooks")
Pokey Rule7a113622025-05-12 10:58:45 +0100831 if _, statErr := os.Stat(hookPath); statErr == nil {
832 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
833 slog.String("error", err.Error()),
834 slog.String("output", string(checkoutOut)))
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700835 if removeErr := removeGitHooks(ctx, a.workingDir); removeErr != nil {
Pokey Rule7a113622025-05-12 10:58:45 +0100836 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
837 }
838
839 // Retry the checkout operation
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700840 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", a.config.Commit)
841 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100842 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700843 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 +0100844 }
845 } else {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700846 return fmt.Errorf("git checkout %s: %s: %w", a.config.Commit, checkoutOut, err)
Pokey Rule7a113622025-05-12 10:58:45 +0100847 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700848 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700849 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700850
851 if ini.HostAddr != "" {
852 a.url = "http://" + ini.HostAddr
853 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700854
855 if !ini.NoGit {
856 repoRoot, err := repoRoot(ctx, a.workingDir)
857 if err != nil {
858 return fmt.Errorf("repoRoot: %w", err)
859 }
860 a.repoRoot = repoRoot
861
Earl Lee2e463fb2025-04-17 11:22:22 -0700862 if err != nil {
863 return fmt.Errorf("resolveRef: %w", err)
864 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700865
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700866 if err := setupGitHooks(a.workingDir); err != nil {
867 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
868 }
869
Philip Zeyliger49edc922025-05-14 09:45:45 -0700870 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
871 cmd.Dir = repoRoot
872 if out, err := cmd.CombinedOutput(); err != nil {
873 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
874 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700875
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000876 slog.Info("running codebase analysis")
877 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
878 if err != nil {
879 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000880 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000881 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000882
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +0000883 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -0700884 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000885 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700886 }
887 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000888
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700889 a.gitOrigin = getGitOrigin(ctx, a.workingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700890 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700891 a.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700892 a.convo = a.initConvo()
893 close(a.ready)
894 return nil
895}
896
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700897//go:embed agent_system_prompt.txt
898var agentSystemPrompt string
899
Earl Lee2e463fb2025-04-17 11:22:22 -0700900// initConvo initializes the conversation.
901// It must not be called until all agent fields are initialized,
902// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700903func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700904 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700905 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700906 convo.PromptCaching = true
907 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000908 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000909 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700910
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000911 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
912 bashPermissionCheck := func(command string) error {
913 // Check if branch name is set
914 a.mu.Lock()
915 branchSet := a.branchName != ""
916 a.mu.Unlock()
917
918 // If branch is set, all commands are allowed
919 if branchSet {
920 return nil
921 }
922
923 // If branch is not set, check if this is a git commit command
924 willCommit, err := bashkit.WillRunGitCommit(command)
925 if err != nil {
926 // If there's an error checking, we should allow the command to proceed
927 return nil
928 }
929
930 // If it's a git commit and branch is not set, return an error
931 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000932 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000933 }
934
935 return nil
936 }
937
938 // Create a custom bash tool with the permission check
939 bashTool := claudetool.NewBashTool(bashPermissionCheck)
940
Earl Lee2e463fb2025-04-17 11:22:22 -0700941 // Register all tools with the conversation
942 // When adding, removing, or modifying tools here, double-check that the termui tool display
943 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000944
945 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700946 _, supportsScreenshots := a.config.Service.(*ant.Service)
947 var bTools []*llm.Tool
948 var browserCleanup func()
949
950 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
951 // Add cleanup function to context cancel
952 go func() {
953 <-a.config.Context.Done()
954 browserCleanup()
955 }()
956 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000957
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700958 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000959 bashTool, claudetool.Keyword,
Josh Bleecher Snyder93202652025-05-08 02:05:57 +0000960 claudetool.Think, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -0700961 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000962 }
963
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000964 // One-shot mode is non-interactive, multiple choice requires human response
965 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700966 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -0700967 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000968
969 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700970 if a.config.UseAnthropicEdit {
971 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
972 } else {
973 convo.Tools = append(convo.Tools, claudetool.Patch)
974 }
975 convo.Listener = a
976 return convo
977}
978
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700979var multipleChoiceTool = &llm.Tool{
980 Name: "multiplechoice",
981 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.",
982 EndsTurn: true,
983 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -0700984 "type": "object",
985 "description": "The question and a list of answers you would expect the user to choose from.",
986 "properties": {
987 "question": {
988 "type": "string",
989 "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?'"
990 },
991 "responseOptions": {
992 "type": "array",
993 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
994 "items": {
995 "type": "object",
996 "properties": {
997 "caption": {
998 "type": "string",
999 "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'"
1000 },
1001 "responseText": {
1002 "type": "string",
1003 "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'"
1004 }
1005 },
1006 "required": ["caption", "responseText"]
1007 }
1008 }
1009 },
1010 "required": ["question", "responseOptions"]
1011}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001012 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1013 // The Run logic for "multiplechoice" tool is a no-op on the server.
1014 // The UI will present a list of options for the user to select from,
1015 // and that's it as far as "executing" the tool_use goes.
1016 // When the user *does* select one of the presented options, that
1017 // responseText gets sent as a chat message on behalf of the user.
1018 return llm.TextContent("end your turn and wait for the user to respond"), nil
1019 },
Sean McCullough485afc62025-04-28 14:28:39 -07001020}
1021
1022type MultipleChoiceOption struct {
1023 Caption string `json:"caption"`
1024 ResponseText string `json:"responseText"`
1025}
1026
1027type MultipleChoiceParams struct {
1028 Question string `json:"question"`
1029 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1030}
1031
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001032// branchExists reports whether branchName exists, either locally or in well-known remotes.
1033func branchExists(dir, branchName string) bool {
1034 refs := []string{
1035 "refs/heads/",
1036 "refs/remotes/origin/",
1037 "refs/remotes/sketch-host/",
1038 }
1039 for _, ref := range refs {
1040 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1041 cmd.Dir = dir
1042 if cmd.Run() == nil { // exit code 0 means branch exists
1043 return true
1044 }
1045 }
1046 return false
1047}
1048
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001049func (a *Agent) titleTool() *llm.Tool {
1050 description := `Sets the conversation title.`
1051 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001052 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001053 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001054 InputSchema: json.RawMessage(`{
1055 "type": "object",
1056 "properties": {
1057 "title": {
1058 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001059 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001060 }
1061 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001062 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001063}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001064 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001065 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001066 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001067 }
1068 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001069 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001070 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001071
1072 // We don't allow changing the title once set to be consistent with the previous behavior
1073 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001074 t := a.Title()
1075 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001076 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001077 }
1078
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001079 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001080 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001081 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001082
1083 a.SetTitle(params.Title)
1084 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001085 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001086 },
1087 }
1088 return titleTool
1089}
1090
1091func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001092 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 +00001093 preCommit := &llm.Tool{
1094 Name: "precommit",
1095 Description: description,
1096 InputSchema: json.RawMessage(`{
1097 "type": "object",
1098 "properties": {
1099 "branch_name": {
1100 "type": "string",
1101 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1102 }
1103 },
1104 "required": ["branch_name"]
1105}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001106 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001107 var params struct {
1108 BranchName string `json:"branch_name"`
1109 }
1110 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001111 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001112 }
1113
1114 b := a.BranchName()
1115 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001116 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001117 }
1118
1119 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001120 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001121 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001122 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001123 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001124 }
1125 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001126 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001127 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001128 }
1129
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001130 a.SetBranch(branchName)
Josh Bleecher Snyderf7bebdd2025-05-14 15:22:24 -07001131 response := fmt.Sprintf("switched to branch sketch/%q - DO NOT change branches unless explicitly requested", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001132
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001133 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1134 if err != nil {
1135 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1136 }
1137 if len(styleHint) > 0 {
1138 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001139 }
1140
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001141 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001142 },
1143 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001144 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001145}
1146
1147func (a *Agent) Ready() <-chan struct{} {
1148 return a.ready
1149}
1150
1151func (a *Agent) UserMessage(ctx context.Context, msg string) {
1152 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1153 a.inbox <- msg
1154}
1155
Earl Lee2e463fb2025-04-17 11:22:22 -07001156func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1157 return a.convo.CancelToolUse(toolUseID, cause)
1158}
1159
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001160func (a *Agent) CancelTurn(cause error) {
1161 a.cancelTurnMu.Lock()
1162 defer a.cancelTurnMu.Unlock()
1163 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001164 // Force state transition to cancelled state
1165 ctx := a.config.Context
1166 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001167 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001168 }
1169}
1170
1171func (a *Agent) Loop(ctxOuter context.Context) {
1172 for {
1173 select {
1174 case <-ctxOuter.Done():
1175 return
1176 default:
1177 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001178 a.cancelTurnMu.Lock()
1179 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001180 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001181 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001182 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001183 a.cancelTurn = cancel
1184 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001185 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1186 if err != nil {
1187 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1188 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001189 cancel(nil)
1190 }
1191 }
1192}
1193
1194func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1195 if m.Timestamp.IsZero() {
1196 m.Timestamp = time.Now()
1197 }
1198
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001199 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1200 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1201 m.Content = m.ToolResult
1202 }
1203
Earl Lee2e463fb2025-04-17 11:22:22 -07001204 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1205 if m.EndOfTurn && m.Type == AgentMessageType {
1206 turnDuration := time.Since(a.startOfTurn)
1207 m.TurnDuration = &turnDuration
1208 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1209 }
1210
Earl Lee2e463fb2025-04-17 11:22:22 -07001211 a.mu.Lock()
1212 defer a.mu.Unlock()
1213 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001214 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001215 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001216
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001217 // Notify all subscribers
1218 for _, ch := range a.subscribers {
1219 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001220 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001221}
1222
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001223func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1224 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001225 if block {
1226 select {
1227 case <-ctx.Done():
1228 return m, ctx.Err()
1229 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001230 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001231 }
1232 }
1233 for {
1234 select {
1235 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001236 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001237 default:
1238 return m, nil
1239 }
1240 }
1241}
1242
Sean McCullough885a16a2025-04-30 02:49:25 +00001243// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001244func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001245 // Reset the start of turn time
1246 a.startOfTurn = time.Now()
1247
Sean McCullough96b60dd2025-04-30 09:49:10 -07001248 // Transition to waiting for user input state
1249 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1250
Sean McCullough885a16a2025-04-30 02:49:25 +00001251 // Process initial user message
1252 initialResp, err := a.processUserMessage(ctx)
1253 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001254 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001255 return err
1256 }
1257
1258 // Handle edge case where both initialResp and err are nil
1259 if initialResp == nil {
1260 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001261 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1262
Sean McCullough9f4b8082025-04-30 17:34:07 +00001263 a.pushToOutbox(ctx, errorMessage(err))
1264 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001265 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001266
Earl Lee2e463fb2025-04-17 11:22:22 -07001267 // We do this as we go, but let's also do it at the end of the turn
1268 defer func() {
1269 if _, err := a.handleGitCommits(ctx); err != nil {
1270 // Just log the error, don't stop execution
1271 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1272 }
1273 }()
1274
Sean McCullougha1e0e492025-05-01 10:51:08 -07001275 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001276 resp := initialResp
1277 for {
1278 // Check if we are over budget
1279 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001280 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001281 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001282 }
1283
1284 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001285 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001286 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001287 break
1288 }
1289
Sean McCullough96b60dd2025-04-30 09:49:10 -07001290 // Transition to tool use requested state
1291 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1292
Sean McCullough885a16a2025-04-30 02:49:25 +00001293 // Handle tool execution
1294 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1295 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001296 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001297 }
1298
Sean McCullougha1e0e492025-05-01 10:51:08 -07001299 if toolResp == nil {
1300 return fmt.Errorf("cannot continue conversation with a nil tool response")
1301 }
1302
Sean McCullough885a16a2025-04-30 02:49:25 +00001303 // Set the response for the next iteration
1304 resp = toolResp
1305 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001306
1307 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001308}
1309
1310// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001311func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001312 // Wait for at least one message from the user
1313 msgs, err := a.GatherMessages(ctx, true)
1314 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001315 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001316 return nil, err
1317 }
1318
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001319 userMessage := llm.Message{
1320 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001321 Content: msgs,
1322 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001323
Sean McCullough96b60dd2025-04-30 09:49:10 -07001324 // Transition to sending to LLM state
1325 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1326
Sean McCullough885a16a2025-04-30 02:49:25 +00001327 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001328 resp, err := a.convo.SendMessage(userMessage)
1329 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001330 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001331 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001332 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001333 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001334
Sean McCullough96b60dd2025-04-30 09:49:10 -07001335 // Transition to processing LLM response state
1336 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1337
Sean McCullough885a16a2025-04-30 02:49:25 +00001338 return resp, nil
1339}
1340
1341// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001342func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1343 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001344 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001345 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001346
Sean McCullough96b60dd2025-04-30 09:49:10 -07001347 // Transition to checking for cancellation state
1348 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1349
Sean McCullough885a16a2025-04-30 02:49:25 +00001350 // Check if the operation was cancelled by the user
1351 select {
1352 case <-ctx.Done():
1353 // Don't actually run any of the tools, but rather build a response
1354 // for each tool_use message letting the LLM know that user canceled it.
1355 var err error
1356 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001357 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001358 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001359 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001360 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001361 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001362 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001363 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001364 // Transition to running tool state
1365 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1366
Sean McCullough885a16a2025-04-30 02:49:25 +00001367 // Add working directory to context for tool execution
1368 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1369
1370 // Execute the tools
1371 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001372 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001373 if ctx.Err() != nil { // e.g. the user canceled the operation
1374 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001375 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001376 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001377 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001378 a.pushToOutbox(ctx, errorMessage(err))
1379 }
1380 }
1381
1382 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001383 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001384 autoqualityMessages := a.processGitChanges(ctx)
1385
1386 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001387 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001388 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001389 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001390 return false, nil
1391 }
1392
1393 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001394 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1395 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001396}
1397
1398// processGitChanges checks for new git commits and runs autoformatters if needed
1399func (a *Agent) processGitChanges(ctx context.Context) []string {
1400 // Check for git commits after tool execution
1401 newCommits, err := a.handleGitCommits(ctx)
1402 if err != nil {
1403 // Just log the error, don't stop execution
1404 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1405 return nil
1406 }
1407
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001408 // Run mechanical checks if there was exactly one new commit.
1409 if len(newCommits) != 1 {
1410 return nil
1411 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001412 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001413 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1414 msg := a.codereview.RunMechanicalChecks(ctx)
1415 if msg != "" {
1416 a.pushToOutbox(ctx, AgentMessage{
1417 Type: AutoMessageType,
1418 Content: msg,
1419 Timestamp: time.Now(),
1420 })
1421 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001422 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001423
1424 return autoqualityMessages
1425}
1426
1427// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001428func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001429 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001430 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001431 msgs, err := a.GatherMessages(ctx, false)
1432 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001433 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001434 return false, nil
1435 }
1436
1437 // Inject any auto-generated messages from quality checks
1438 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001439 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001440 }
1441
1442 // Handle cancellation by appending a message about it
1443 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001444 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001445 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001446 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001447 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1448 } else if err := a.convo.OverBudget(); err != nil {
1449 // Handle budget issues by appending a message about it
1450 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 -07001451 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001452 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1453 }
1454
1455 // Combine tool results with user messages
1456 results = append(results, msgs...)
1457
1458 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001459 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001460 resp, err := a.convo.SendMessage(llm.Message{
1461 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001462 Content: results,
1463 })
1464 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001465 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001466 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1467 return true, nil // Return true to continue the conversation, but with no response
1468 }
1469
Sean McCullough96b60dd2025-04-30 09:49:10 -07001470 // Transition back to processing LLM response
1471 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1472
Sean McCullough885a16a2025-04-30 02:49:25 +00001473 if cancelled {
1474 return false, nil
1475 }
1476
1477 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001478}
1479
1480func (a *Agent) overBudget(ctx context.Context) error {
1481 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001482 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001483 m := budgetMessage(err)
1484 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001485 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001486 a.convo.ResetBudget(a.originalBudget)
1487 return err
1488 }
1489 return nil
1490}
1491
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001492func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001493 // Collect all text content
1494 var allText strings.Builder
1495 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001496 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001497 if allText.Len() > 0 {
1498 allText.WriteString("\n\n")
1499 }
1500 allText.WriteString(content.Text)
1501 }
1502 }
1503 return allText.String()
1504}
1505
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001506func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001507 a.mu.Lock()
1508 defer a.mu.Unlock()
1509 return a.convo.CumulativeUsage()
1510}
1511
Earl Lee2e463fb2025-04-17 11:22:22 -07001512// Diff returns a unified diff of changes made since the agent was instantiated.
1513func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001514 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001515 return "", fmt.Errorf("no initial commit reference available")
1516 }
1517
1518 // Find the repository root
1519 ctx := context.Background()
1520
1521 // If a specific commit hash is provided, show just that commit's changes
1522 if commit != nil && *commit != "" {
1523 // Validate that the commit looks like a valid git SHA
1524 if !isValidGitSHA(*commit) {
1525 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1526 }
1527
1528 // Get the diff for just this commit
1529 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1530 cmd.Dir = a.repoRoot
1531 output, err := cmd.CombinedOutput()
1532 if err != nil {
1533 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1534 }
1535 return string(output), nil
1536 }
1537
1538 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001539 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001540 cmd.Dir = a.repoRoot
1541 output, err := cmd.CombinedOutput()
1542 if err != nil {
1543 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1544 }
1545
1546 return string(output), nil
1547}
1548
Philip Zeyliger49edc922025-05-14 09:45:45 -07001549// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1550// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1551func (a *Agent) SketchGitBaseRef() string {
1552 if a.IsInContainer() {
1553 return "sketch-base"
1554 } else {
1555 return "sketch-base-" + a.SessionID()
1556 }
1557}
1558
1559// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1560func (a *Agent) SketchGitBase() string {
1561 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1562 cmd.Dir = a.repoRoot
1563 output, err := cmd.CombinedOutput()
1564 if err != nil {
1565 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1566 return "HEAD"
1567 }
1568 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001569}
1570
Pokey Rule7a113622025-05-12 10:58:45 +01001571// removeGitHooks removes the Git hooks directory from the repository
1572func removeGitHooks(_ context.Context, repoPath string) error {
1573 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1574
1575 // Check if hooks directory exists
1576 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1577 // Directory doesn't exist, nothing to do
1578 return nil
1579 }
1580
1581 // Remove the hooks directory
1582 err := os.RemoveAll(hooksDir)
1583 if err != nil {
1584 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1585 }
1586
1587 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001588 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001589 if err != nil {
1590 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1591 }
1592
1593 return nil
1594}
1595
Earl Lee2e463fb2025-04-17 11:22:22 -07001596// handleGitCommits() highlights new commits to the user. When running
1597// under docker, new HEADs are pushed to a branch according to the title.
1598func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1599 if a.repoRoot == "" {
1600 return nil, nil
1601 }
1602
1603 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1604 if err != nil {
1605 return nil, err
1606 }
1607 if head == a.lastHEAD {
1608 return nil, nil // nothing to do
1609 }
1610 defer func() {
1611 a.lastHEAD = head
1612 }()
1613
1614 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1615 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1616 // to the last 100 commits.
1617 var commits []*GitCommit
1618
1619 // Get commits since the initial commit
1620 // Format: <hash>\0<subject>\0<body>\0
1621 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1622 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyliger49edc922025-05-14 09:45:45 -07001623 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+a.SketchGitBaseRef(), head)
Earl Lee2e463fb2025-04-17 11:22:22 -07001624 cmd.Dir = a.repoRoot
1625 output, err := cmd.Output()
1626 if err != nil {
1627 return nil, fmt.Errorf("failed to get git log: %w", err)
1628 }
1629
1630 // Parse git log output and filter out already seen commits
1631 parsedCommits := parseGitLog(string(output))
1632
1633 var headCommit *GitCommit
1634
1635 // Filter out commits we've already seen
1636 for _, commit := range parsedCommits {
1637 if commit.Hash == head {
1638 headCommit = &commit
1639 }
1640
1641 // Skip if we've seen this commit before. If our head has changed, always include that.
1642 if a.seenCommits[commit.Hash] && commit.Hash != head {
1643 continue
1644 }
1645
1646 // Mark this commit as seen
1647 a.seenCommits[commit.Hash] = true
1648
1649 // Add to our list of new commits
1650 commits = append(commits, &commit)
1651 }
1652
1653 if a.gitRemoteAddr != "" {
1654 if headCommit == nil {
1655 // I think this can only happen if we have a bug or if there's a race.
1656 headCommit = &GitCommit{}
1657 headCommit.Hash = head
1658 headCommit.Subject = "unknown"
1659 commits = append(commits, headCommit)
1660 }
1661
Philip Zeyliger113e2052025-05-09 21:59:40 +00001662 originalBranch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
1663 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001664
1665 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1666 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1667 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001668
1669 // Try up to 10 times with different branch names if the branch is checked out on the remote
1670 var out []byte
1671 var err error
1672 for retries := range 10 {
1673 if retries > 0 {
1674 // Add a numeric suffix to the branch name
1675 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1676 }
1677
1678 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1679 cmd.Dir = a.workingDir
1680 out, err = cmd.CombinedOutput()
1681
1682 if err == nil {
1683 // Success! Break out of the retry loop
1684 break
1685 }
1686
1687 // Check if this is the "refusing to update checked out branch" error
1688 if !strings.Contains(string(out), "refusing to update checked out branch") {
1689 // This is a different error, so don't retry
1690 break
1691 }
1692
1693 // If we're on the last retry, we'll report the error
1694 if retries == 9 {
1695 break
1696 }
1697 }
1698
1699 if err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07001700 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1701 } else {
1702 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001703 // Update the agent's branch name if we ended up using a different one
1704 if branch != originalBranch {
1705 a.branchName = branch
1706 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001707 }
1708 }
1709
1710 // If we found new commits, create a message
1711 if len(commits) > 0 {
1712 msg := AgentMessage{
1713 Type: CommitMessageType,
1714 Timestamp: time.Now(),
1715 Commits: commits,
1716 }
1717 a.pushToOutbox(ctx, msg)
1718 }
1719 return commits, nil
1720}
1721
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001722func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001723 return strings.Map(func(r rune) rune {
1724 // lowercase
1725 if r >= 'A' && r <= 'Z' {
1726 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001727 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001728 // replace spaces with dashes
1729 if r == ' ' {
1730 return '-'
1731 }
1732 // allow alphanumerics and dashes
1733 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1734 return r
1735 }
1736 return -1
1737 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001738}
1739
1740// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1741// and returns an array of GitCommit structs.
1742func parseGitLog(output string) []GitCommit {
1743 var commits []GitCommit
1744
1745 // No output means no commits
1746 if len(output) == 0 {
1747 return commits
1748 }
1749
1750 // Split by NULL byte
1751 parts := strings.Split(output, "\x00")
1752
1753 // Process in triplets (hash, subject, body)
1754 for i := 0; i < len(parts); i++ {
1755 // Skip empty parts
1756 if parts[i] == "" {
1757 continue
1758 }
1759
1760 // This should be a hash
1761 hash := strings.TrimSpace(parts[i])
1762
1763 // Make sure we have at least a subject part available
1764 if i+1 >= len(parts) {
1765 break // No more parts available
1766 }
1767
1768 // Get the subject
1769 subject := strings.TrimSpace(parts[i+1])
1770
1771 // Get the body if available
1772 body := ""
1773 if i+2 < len(parts) {
1774 body = strings.TrimSpace(parts[i+2])
1775 }
1776
1777 // Skip to the next triplet
1778 i += 2
1779
1780 commits = append(commits, GitCommit{
1781 Hash: hash,
1782 Subject: subject,
1783 Body: body,
1784 })
1785 }
1786
1787 return commits
1788}
1789
1790func repoRoot(ctx context.Context, dir string) (string, error) {
1791 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1792 stderr := new(strings.Builder)
1793 cmd.Stderr = stderr
1794 cmd.Dir = dir
1795 out, err := cmd.Output()
1796 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001797 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07001798 }
1799 return strings.TrimSpace(string(out)), nil
1800}
1801
1802func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1803 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1804 stderr := new(strings.Builder)
1805 cmd.Stderr = stderr
1806 cmd.Dir = dir
1807 out, err := cmd.Output()
1808 if err != nil {
1809 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1810 }
1811 // TODO: validate that out is valid hex
1812 return strings.TrimSpace(string(out)), nil
1813}
1814
1815// isValidGitSHA validates if a string looks like a valid git SHA hash.
1816// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1817func isValidGitSHA(sha string) bool {
1818 // Git SHA must be a hexadecimal string with at least 4 characters
1819 if len(sha) < 4 || len(sha) > 40 {
1820 return false
1821 }
1822
1823 // Check if the string only contains hexadecimal characters
1824 for _, char := range sha {
1825 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1826 return false
1827 }
1828 }
1829
1830 return true
1831}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001832
1833// getGitOrigin returns the URL of the git remote 'origin' if it exists
1834func getGitOrigin(ctx context.Context, dir string) string {
1835 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1836 cmd.Dir = dir
1837 stderr := new(strings.Builder)
1838 cmd.Stderr = stderr
1839 out, err := cmd.Output()
1840 if err != nil {
1841 return ""
1842 }
1843 return strings.TrimSpace(string(out))
1844}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001845
1846func (a *Agent) initGitRevision(ctx context.Context, workingDir, revision string) error {
1847 cmd := exec.CommandContext(ctx, "git", "stash")
1848 cmd.Dir = workingDir
1849 if out, err := cmd.CombinedOutput(); err != nil {
1850 return fmt.Errorf("git stash: %s: %v", out, err)
1851 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +00001852 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001853 cmd.Dir = workingDir
1854 if out, err := cmd.CombinedOutput(); err != nil {
1855 return fmt.Errorf("git fetch: %s: %w", out, err)
1856 }
1857 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", revision)
1858 cmd.Dir = workingDir
1859 if out, err := cmd.CombinedOutput(); err != nil {
1860 return fmt.Errorf("git checkout %s: %s: %w", revision, out, err)
1861 }
1862 a.lastHEAD = revision
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001863 return nil
1864}
1865
1866func (a *Agent) RestartConversation(ctx context.Context, rev string, initialPrompt string) error {
1867 a.mu.Lock()
1868 a.title = ""
1869 a.firstMessageIndex = len(a.history)
1870 a.convo = a.initConvo()
1871 gitReset := func() error {
1872 if a.config.InDocker && rev != "" {
1873 err := a.initGitRevision(ctx, a.workingDir, rev)
1874 if err != nil {
1875 return err
1876 }
1877 } else if !a.config.InDocker && rev != "" {
1878 return fmt.Errorf("Not resetting git repo when working outside of a container.")
1879 }
1880 return nil
1881 }
1882 err := gitReset()
1883 a.mu.Unlock()
1884 if err != nil {
1885 a.pushToOutbox(a.config.Context, errorMessage(err))
1886 }
1887
1888 a.pushToOutbox(a.config.Context, AgentMessage{
1889 Type: AgentMessageType, Content: "Conversation restarted.",
1890 })
1891 if initialPrompt != "" {
1892 a.UserMessage(ctx, initialPrompt)
1893 }
1894 return nil
1895}
1896
1897func (a *Agent) SuggestReprompt(ctx context.Context) (string, error) {
1898 msg := `The user has requested a suggestion for a re-prompt.
1899
1900 Given the current conversation thus far, suggest a re-prompt that would
1901 capture the instructions and feedback so far, as well as any
1902 research or other information that would be helpful in implementing
1903 the task.
1904
1905 Reply with ONLY the reprompt text.
1906 `
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001907 userMessage := llm.UserStringMessage(msg)
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001908 // By doing this in a subconversation, the agent doesn't call tools (because
1909 // there aren't any), and there's not a concurrency risk with on-going other
1910 // outstanding conversations.
1911 convo := a.convo.SubConvoWithHistory()
1912 resp, err := convo.SendMessage(userMessage)
1913 if err != nil {
1914 a.pushToOutbox(ctx, errorMessage(err))
1915 return "", err
1916 }
1917 textContent := collectTextContent(resp)
1918 return textContent, nil
1919}
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001920
1921// systemPromptData contains the data used to render the system prompt template
1922type systemPromptData struct {
1923 EditPrompt string
1924 ClientGOOS string
1925 ClientGOARCH string
1926 WorkingDir string
1927 RepoRoot string
1928 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001929 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001930}
1931
1932// renderSystemPrompt renders the system prompt template.
1933func (a *Agent) renderSystemPrompt() string {
1934 // Determine the appropriate edit prompt based on config
1935 var editPrompt string
1936 if a.config.UseAnthropicEdit {
1937 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."
1938 } else {
1939 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
1940 }
1941
1942 data := systemPromptData{
1943 EditPrompt: editPrompt,
1944 ClientGOOS: a.config.ClientGOOS,
1945 ClientGOARCH: a.config.ClientGOARCH,
1946 WorkingDir: a.workingDir,
1947 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07001948 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001949 Codebase: a.codebase,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001950 }
1951
1952 tmpl, err := template.New("system").Parse(agentSystemPrompt)
1953 if err != nil {
1954 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
1955 }
1956 buf := new(strings.Builder)
1957 err = tmpl.Execute(buf, data)
1958 if err != nil {
1959 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
1960 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001961 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001962 return buf.String()
1963}
Philip Zeyligereab12de2025-05-14 02:35:53 +00001964
1965// StateTransitionIterator provides an iterator over state transitions.
1966type StateTransitionIterator interface {
1967 // Next blocks until a new state transition is available or context is done.
1968 // Returns nil if the context is cancelled.
1969 Next() *StateTransition
1970 // Close removes the listener and cleans up resources.
1971 Close()
1972}
1973
1974// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
1975type StateTransitionIteratorImpl struct {
1976 agent *Agent
1977 ctx context.Context
1978 ch chan StateTransition
1979 unsubscribe func()
1980}
1981
1982// Next blocks until a new state transition is available or the context is cancelled.
1983func (s *StateTransitionIteratorImpl) Next() *StateTransition {
1984 select {
1985 case <-s.ctx.Done():
1986 return nil
1987 case transition, ok := <-s.ch:
1988 if !ok {
1989 return nil
1990 }
1991 transitionCopy := transition
1992 return &transitionCopy
1993 }
1994}
1995
1996// Close removes the listener and cleans up resources.
1997func (s *StateTransitionIteratorImpl) Close() {
1998 if s.unsubscribe != nil {
1999 s.unsubscribe()
2000 s.unsubscribe = nil
2001 }
2002}
2003
2004// NewStateTransitionIterator returns an iterator that receives state transitions.
2005func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2006 a.mu.Lock()
2007 defer a.mu.Unlock()
2008
2009 // Create channel to receive state transitions
2010 ch := make(chan StateTransition, 10)
2011
2012 // Add a listener to the state machine
2013 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2014
2015 return &StateTransitionIteratorImpl{
2016 agent: a,
2017 ctx: ctx,
2018 ch: ch,
2019 unsubscribe: unsubscribe,
2020 }
2021}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002022
2023// setupGitHooks creates or updates git hooks in the specified working directory.
2024func setupGitHooks(workingDir string) error {
2025 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2026
2027 _, err := os.Stat(hooksDir)
2028 if os.IsNotExist(err) {
2029 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2030 }
2031 if err != nil {
2032 return fmt.Errorf("error checking git hooks directory: %w", err)
2033 }
2034
2035 // Define the post-commit hook content
2036 postCommitHook := `#!/bin/bash
2037echo "<post_commit_hook>"
2038echo "Please review this commit message and fix it if it is incorrect."
2039echo "This hook only echos the commit message; it does not modify it."
2040echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2041echo "<last_commit_message>"
2042git log -1 --pretty=%B
2043echo "</last_commit_message>"
2044echo "</post_commit_hook>"
2045`
2046
2047 // Define the prepare-commit-msg hook content
2048 prepareCommitMsgHook := `#!/bin/bash
2049# Add Co-Authored-By and Change-ID trailers to commit messages
2050# Check if these trailers already exist before adding them
2051
2052commit_file="$1"
2053COMMIT_SOURCE="$2"
2054
2055# Skip for merges, squashes, or when using a commit template
2056if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2057 [ "$COMMIT_SOURCE" = "squash" ]; then
2058 exit 0
2059fi
2060
2061commit_msg=$(cat "$commit_file")
2062
2063needs_co_author=true
2064needs_change_id=true
2065
2066# Check if commit message already has Co-Authored-By trailer
2067if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2068 needs_co_author=false
2069fi
2070
2071# Check if commit message already has Change-ID trailer
2072if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2073 needs_change_id=false
2074fi
2075
2076# Only modify if at least one trailer needs to be added
2077if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
2078 # Ensure there's a blank line before trailers
2079 if [ -s "$commit_file" ] && [ "$(tail -1 "$commit_file" | tr -d '\n')" != "" ]; then
2080 echo "" >> "$commit_file"
2081 fi
2082
2083 # Add trailers if needed
2084 if [ "$needs_co_author" = true ]; then
2085 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2086 fi
2087
2088 if [ "$needs_change_id" = true ]; then
2089 change_id=$(openssl rand -hex 8)
2090 echo "Change-ID: s${change_id}k" >> "$commit_file"
2091 fi
2092fi
2093`
2094
2095 // Update or create the post-commit hook
2096 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2097 if err != nil {
2098 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2099 }
2100
2101 // Update or create the prepare-commit-msg hook
2102 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2103 if err != nil {
2104 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2105 }
2106
2107 return nil
2108}
2109
2110// updateOrCreateHook creates a new hook file or updates an existing one
2111// by appending the new content if it doesn't already contain it.
2112func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2113 // Check if the hook already exists
2114 buf, err := os.ReadFile(hookPath)
2115 if os.IsNotExist(err) {
2116 // Hook doesn't exist, create it
2117 err = os.WriteFile(hookPath, []byte(content), 0o755)
2118 if err != nil {
2119 return fmt.Errorf("failed to create hook: %w", err)
2120 }
2121 return nil
2122 }
2123 if err != nil {
2124 return fmt.Errorf("error reading existing hook: %w", err)
2125 }
2126
2127 // Hook exists, check if our content is already in it by looking for a distinctive line
2128 code := string(buf)
2129 if strings.Contains(code, distinctiveLine) {
2130 // Already contains our content, nothing to do
2131 return nil
2132 }
2133
2134 // Append our content to the existing hook
2135 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2136 if err != nil {
2137 return fmt.Errorf("failed to open hook for appending: %w", err)
2138 }
2139 defer f.Close()
2140
2141 // Ensure there's a newline at the end of the existing content if needed
2142 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2143 _, err = f.WriteString("\n")
2144 if err != nil {
2145 return fmt.Errorf("failed to add newline to hook: %w", err)
2146 }
2147 }
2148
2149 // Add a separator before our content
2150 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2151 if err != nil {
2152 return fmt.Errorf("failed to append to hook: %w", err)
2153 }
2154
2155 return nil
2156}