blob: c786477ba309e222fa175a19fbdceb06e6bc15a7 [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 Zeyliger18532b22025-04-23 21:11:46 +0000747 // Outside information
748 OutsideHostname string
749 OutsideOS string
750 OutsideWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -0700751}
752
753// NewAgent creates a new Agent.
754// It is not usable until Init() is called.
755func NewAgent(config AgentConfig) *Agent {
756 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000757 config: config,
758 ready: make(chan struct{}),
759 inbox: make(chan string, 100),
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700760 subscribers: make([]chan *AgentMessage, 0),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000761 startedAt: time.Now(),
762 originalBudget: config.Budget,
763 seenCommits: make(map[string]bool),
764 outsideHostname: config.OutsideHostname,
765 outsideOS: config.OutsideOS,
766 outsideWorkingDir: config.OutsideWorkingDir,
767 outstandingLLMCalls: make(map[string]struct{}),
768 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700769 stateMachine: NewStateMachine(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700770 }
771 return agent
772}
773
774type AgentInit struct {
775 WorkingDir string
776 NoGit bool // only for testing
777
778 InDocker bool
779 Commit string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000780 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700781 GitRemoteAddr string
782 HostAddr string
783}
784
785func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700786 if a.convo != nil {
787 return fmt.Errorf("Agent.Init: already initialized")
788 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700789 ctx := a.config.Context
David Crawshawa8322202025-05-17 06:54:34 -0700790 if ini.InDocker && ini.Commit != "" {
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +0000791 if err := setupGitHooks(ini.WorkingDir); err != nil {
792 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
793 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700794 cmd := exec.CommandContext(ctx, "git", "stash")
795 cmd.Dir = ini.WorkingDir
796 if out, err := cmd.CombinedOutput(); err != nil {
797 return fmt.Errorf("git stash: %s: %v", out, err)
798 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700799 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
800 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
801 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
802 // origin/main on outtie sketch, which should make it easier to rebase.
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700803 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", ini.GitRemoteAddr)
804 cmd.Dir = ini.WorkingDir
805 if out, err := cmd.CombinedOutput(); err != nil {
806 return fmt.Errorf("git remote add: %s: %v", out, err)
807 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700808 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
809 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
810 cmd.Dir = ini.WorkingDir
811 if out, err := cmd.CombinedOutput(); err != nil {
812 return fmt.Errorf("git config --add: %s: %v", out, err)
813 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000814 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Earl Lee2e463fb2025-04-17 11:22:22 -0700815 cmd.Dir = ini.WorkingDir
816 if out, err := cmd.CombinedOutput(); err != nil {
817 return fmt.Errorf("git fetch: %s: %w", out, err)
818 }
819 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
820 cmd.Dir = ini.WorkingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100821 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
822 // Remove git hooks if they exist and retry
823 // Only try removing hooks if we haven't already removed them during fetch
824 hookPath := filepath.Join(ini.WorkingDir, ".git", "hooks")
825 if _, statErr := os.Stat(hookPath); statErr == nil {
826 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
827 slog.String("error", err.Error()),
828 slog.String("output", string(checkoutOut)))
829 if removeErr := removeGitHooks(ctx, ini.WorkingDir); removeErr != nil {
830 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
831 }
832
833 // Retry the checkout operation
834 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
835 cmd.Dir = ini.WorkingDir
836 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
837 return fmt.Errorf("git checkout %s failed even after removing hooks: %s: %w", ini.Commit, retryOut, retryErr)
838 }
839 } else {
840 return fmt.Errorf("git checkout %s: %s: %w", ini.Commit, checkoutOut, err)
841 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700842 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700843 a.gitRemoteAddr = ini.GitRemoteAddr
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000844 a.outsideHTTP = ini.OutsideHTTP
Earl Lee2e463fb2025-04-17 11:22:22 -0700845 if ini.HostAddr != "" {
846 a.url = "http://" + ini.HostAddr
847 }
848 }
849 a.workingDir = ini.WorkingDir
850
851 if !ini.NoGit {
852 repoRoot, err := repoRoot(ctx, a.workingDir)
853 if err != nil {
854 return fmt.Errorf("repoRoot: %w", err)
855 }
856 a.repoRoot = repoRoot
857
Earl Lee2e463fb2025-04-17 11:22:22 -0700858 if err != nil {
859 return fmt.Errorf("resolveRef: %w", err)
860 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700861
862 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
863 cmd.Dir = repoRoot
864 if out, err := cmd.CombinedOutput(); err != nil {
865 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
866 }
867 a.lastHEAD = ini.Commit
Earl Lee2e463fb2025-04-17 11:22:22 -0700868
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000869 slog.Info("running codebase analysis")
870 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
871 if err != nil {
872 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000873 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +0000874 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000875
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +0000876 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -0700877 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000878 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700879 }
880 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000881
882 a.gitOrigin = getGitOrigin(ctx, ini.WorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700883 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700884 a.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700885 a.convo = a.initConvo()
886 close(a.ready)
887 return nil
888}
889
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700890//go:embed agent_system_prompt.txt
891var agentSystemPrompt string
892
Earl Lee2e463fb2025-04-17 11:22:22 -0700893// initConvo initializes the conversation.
894// It must not be called until all agent fields are initialized,
895// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700896func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700897 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700898 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700899 convo.PromptCaching = true
900 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000901 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000902 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700903
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000904 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
905 bashPermissionCheck := func(command string) error {
906 // Check if branch name is set
907 a.mu.Lock()
908 branchSet := a.branchName != ""
909 a.mu.Unlock()
910
911 // If branch is set, all commands are allowed
912 if branchSet {
913 return nil
914 }
915
916 // If branch is not set, check if this is a git commit command
917 willCommit, err := bashkit.WillRunGitCommit(command)
918 if err != nil {
919 // If there's an error checking, we should allow the command to proceed
920 return nil
921 }
922
923 // If it's a git commit and branch is not set, return an error
924 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000925 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000926 }
927
928 return nil
929 }
930
931 // Create a custom bash tool with the permission check
932 bashTool := claudetool.NewBashTool(bashPermissionCheck)
933
Earl Lee2e463fb2025-04-17 11:22:22 -0700934 // Register all tools with the conversation
935 // When adding, removing, or modifying tools here, double-check that the termui tool display
936 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000937
938 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700939 _, supportsScreenshots := a.config.Service.(*ant.Service)
940 var bTools []*llm.Tool
941 var browserCleanup func()
942
943 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
944 // Add cleanup function to context cancel
945 go func() {
946 <-a.config.Context.Done()
947 browserCleanup()
948 }()
949 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000950
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700951 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000952 bashTool, claudetool.Keyword,
Josh Bleecher Snyder93202652025-05-08 02:05:57 +0000953 claudetool.Think, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -0700954 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000955 }
956
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000957 // One-shot mode is non-interactive, multiple choice requires human response
958 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700959 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -0700960 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000961
962 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700963 if a.config.UseAnthropicEdit {
964 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
965 } else {
966 convo.Tools = append(convo.Tools, claudetool.Patch)
967 }
968 convo.Listener = a
969 return convo
970}
971
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700972var multipleChoiceTool = &llm.Tool{
973 Name: "multiplechoice",
974 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.",
975 EndsTurn: true,
976 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -0700977 "type": "object",
978 "description": "The question and a list of answers you would expect the user to choose from.",
979 "properties": {
980 "question": {
981 "type": "string",
982 "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?'"
983 },
984 "responseOptions": {
985 "type": "array",
986 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
987 "items": {
988 "type": "object",
989 "properties": {
990 "caption": {
991 "type": "string",
992 "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'"
993 },
994 "responseText": {
995 "type": "string",
996 "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'"
997 }
998 },
999 "required": ["caption", "responseText"]
1000 }
1001 }
1002 },
1003 "required": ["question", "responseOptions"]
1004}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001005 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1006 // The Run logic for "multiplechoice" tool is a no-op on the server.
1007 // The UI will present a list of options for the user to select from,
1008 // and that's it as far as "executing" the tool_use goes.
1009 // When the user *does* select one of the presented options, that
1010 // responseText gets sent as a chat message on behalf of the user.
1011 return llm.TextContent("end your turn and wait for the user to respond"), nil
1012 },
Sean McCullough485afc62025-04-28 14:28:39 -07001013}
1014
1015type MultipleChoiceOption struct {
1016 Caption string `json:"caption"`
1017 ResponseText string `json:"responseText"`
1018}
1019
1020type MultipleChoiceParams struct {
1021 Question string `json:"question"`
1022 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1023}
1024
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001025// branchExists reports whether branchName exists, either locally or in well-known remotes.
1026func branchExists(dir, branchName string) bool {
1027 refs := []string{
1028 "refs/heads/",
1029 "refs/remotes/origin/",
1030 "refs/remotes/sketch-host/",
1031 }
1032 for _, ref := range refs {
1033 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1034 cmd.Dir = dir
1035 if cmd.Run() == nil { // exit code 0 means branch exists
1036 return true
1037 }
1038 }
1039 return false
1040}
1041
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001042func (a *Agent) titleTool() *llm.Tool {
1043 description := `Sets the conversation title.`
1044 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001045 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001046 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001047 InputSchema: json.RawMessage(`{
1048 "type": "object",
1049 "properties": {
1050 "title": {
1051 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001052 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001053 }
1054 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001055 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001056}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001057 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001058 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001059 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001060 }
1061 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001062 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001063 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001064
1065 // We don't allow changing the title once set to be consistent with the previous behavior
1066 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001067 t := a.Title()
1068 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001069 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001070 }
1071
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001072 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001073 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001074 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001075
1076 a.SetTitle(params.Title)
1077 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001078 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001079 },
1080 }
1081 return titleTool
1082}
1083
1084func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001085 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 +00001086 preCommit := &llm.Tool{
1087 Name: "precommit",
1088 Description: description,
1089 InputSchema: json.RawMessage(`{
1090 "type": "object",
1091 "properties": {
1092 "branch_name": {
1093 "type": "string",
1094 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1095 }
1096 },
1097 "required": ["branch_name"]
1098}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001099 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001100 var params struct {
1101 BranchName string `json:"branch_name"`
1102 }
1103 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001104 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001105 }
1106
1107 b := a.BranchName()
1108 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001109 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001110 }
1111
1112 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001113 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001114 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001115 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001116 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001117 }
1118 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001119 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001120 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001121 }
1122
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001123 a.SetBranch(branchName)
Josh Bleecher Snyderf7bebdd2025-05-14 15:22:24 -07001124 response := fmt.Sprintf("switched to branch sketch/%q - DO NOT change branches unless explicitly requested", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001125
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001126 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1127 if err != nil {
1128 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1129 }
1130 if len(styleHint) > 0 {
1131 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001132 }
1133
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001134 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001135 },
1136 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001137 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001138}
1139
1140func (a *Agent) Ready() <-chan struct{} {
1141 return a.ready
1142}
1143
1144func (a *Agent) UserMessage(ctx context.Context, msg string) {
1145 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1146 a.inbox <- msg
1147}
1148
Earl Lee2e463fb2025-04-17 11:22:22 -07001149func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1150 return a.convo.CancelToolUse(toolUseID, cause)
1151}
1152
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001153func (a *Agent) CancelTurn(cause error) {
1154 a.cancelTurnMu.Lock()
1155 defer a.cancelTurnMu.Unlock()
1156 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001157 // Force state transition to cancelled state
1158 ctx := a.config.Context
1159 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001160 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001161 }
1162}
1163
1164func (a *Agent) Loop(ctxOuter context.Context) {
1165 for {
1166 select {
1167 case <-ctxOuter.Done():
1168 return
1169 default:
1170 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001171 a.cancelTurnMu.Lock()
1172 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001173 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001174 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001175 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001176 a.cancelTurn = cancel
1177 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001178 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1179 if err != nil {
1180 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1181 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001182 cancel(nil)
1183 }
1184 }
1185}
1186
1187func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1188 if m.Timestamp.IsZero() {
1189 m.Timestamp = time.Now()
1190 }
1191
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001192 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1193 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1194 m.Content = m.ToolResult
1195 }
1196
Earl Lee2e463fb2025-04-17 11:22:22 -07001197 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1198 if m.EndOfTurn && m.Type == AgentMessageType {
1199 turnDuration := time.Since(a.startOfTurn)
1200 m.TurnDuration = &turnDuration
1201 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1202 }
1203
Earl Lee2e463fb2025-04-17 11:22:22 -07001204 a.mu.Lock()
1205 defer a.mu.Unlock()
1206 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001207 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001208 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001209
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001210 // Notify all subscribers
1211 for _, ch := range a.subscribers {
1212 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001213 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001214}
1215
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001216func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1217 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001218 if block {
1219 select {
1220 case <-ctx.Done():
1221 return m, ctx.Err()
1222 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001223 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001224 }
1225 }
1226 for {
1227 select {
1228 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001229 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001230 default:
1231 return m, nil
1232 }
1233 }
1234}
1235
Sean McCullough885a16a2025-04-30 02:49:25 +00001236// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001237func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001238 // Reset the start of turn time
1239 a.startOfTurn = time.Now()
1240
Sean McCullough96b60dd2025-04-30 09:49:10 -07001241 // Transition to waiting for user input state
1242 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1243
Sean McCullough885a16a2025-04-30 02:49:25 +00001244 // Process initial user message
1245 initialResp, err := a.processUserMessage(ctx)
1246 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001247 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001248 return err
1249 }
1250
1251 // Handle edge case where both initialResp and err are nil
1252 if initialResp == nil {
1253 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001254 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1255
Sean McCullough9f4b8082025-04-30 17:34:07 +00001256 a.pushToOutbox(ctx, errorMessage(err))
1257 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001258 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001259
Earl Lee2e463fb2025-04-17 11:22:22 -07001260 // We do this as we go, but let's also do it at the end of the turn
1261 defer func() {
1262 if _, err := a.handleGitCommits(ctx); err != nil {
1263 // Just log the error, don't stop execution
1264 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1265 }
1266 }()
1267
Sean McCullougha1e0e492025-05-01 10:51:08 -07001268 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001269 resp := initialResp
1270 for {
1271 // Check if we are over budget
1272 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001273 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001274 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001275 }
1276
1277 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001278 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001279 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001280 break
1281 }
1282
Sean McCullough96b60dd2025-04-30 09:49:10 -07001283 // Transition to tool use requested state
1284 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1285
Sean McCullough885a16a2025-04-30 02:49:25 +00001286 // Handle tool execution
1287 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1288 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001289 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001290 }
1291
Sean McCullougha1e0e492025-05-01 10:51:08 -07001292 if toolResp == nil {
1293 return fmt.Errorf("cannot continue conversation with a nil tool response")
1294 }
1295
Sean McCullough885a16a2025-04-30 02:49:25 +00001296 // Set the response for the next iteration
1297 resp = toolResp
1298 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001299
1300 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001301}
1302
1303// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001304func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001305 // Wait for at least one message from the user
1306 msgs, err := a.GatherMessages(ctx, true)
1307 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001308 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001309 return nil, err
1310 }
1311
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001312 userMessage := llm.Message{
1313 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001314 Content: msgs,
1315 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001316
Sean McCullough96b60dd2025-04-30 09:49:10 -07001317 // Transition to sending to LLM state
1318 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1319
Sean McCullough885a16a2025-04-30 02:49:25 +00001320 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001321 resp, err := a.convo.SendMessage(userMessage)
1322 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001323 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001324 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001325 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001326 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001327
Sean McCullough96b60dd2025-04-30 09:49:10 -07001328 // Transition to processing LLM response state
1329 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1330
Sean McCullough885a16a2025-04-30 02:49:25 +00001331 return resp, nil
1332}
1333
1334// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001335func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1336 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001337 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001338 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001339
Sean McCullough96b60dd2025-04-30 09:49:10 -07001340 // Transition to checking for cancellation state
1341 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1342
Sean McCullough885a16a2025-04-30 02:49:25 +00001343 // Check if the operation was cancelled by the user
1344 select {
1345 case <-ctx.Done():
1346 // Don't actually run any of the tools, but rather build a response
1347 // for each tool_use message letting the LLM know that user canceled it.
1348 var err error
1349 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001350 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001351 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001352 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001353 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001354 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001355 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001356 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001357 // Transition to running tool state
1358 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1359
Sean McCullough885a16a2025-04-30 02:49:25 +00001360 // Add working directory to context for tool execution
1361 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1362
1363 // Execute the tools
1364 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001365 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001366 if ctx.Err() != nil { // e.g. the user canceled the operation
1367 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001368 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001369 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001370 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001371 a.pushToOutbox(ctx, errorMessage(err))
1372 }
1373 }
1374
1375 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001376 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001377 autoqualityMessages := a.processGitChanges(ctx)
1378
1379 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001380 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001381 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001382 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001383 return false, nil
1384 }
1385
1386 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001387 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1388 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001389}
1390
1391// processGitChanges checks for new git commits and runs autoformatters if needed
1392func (a *Agent) processGitChanges(ctx context.Context) []string {
1393 // Check for git commits after tool execution
1394 newCommits, err := a.handleGitCommits(ctx)
1395 if err != nil {
1396 // Just log the error, don't stop execution
1397 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1398 return nil
1399 }
1400
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001401 // Run mechanical checks if there was exactly one new commit.
1402 if len(newCommits) != 1 {
1403 return nil
1404 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001405 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001406 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1407 msg := a.codereview.RunMechanicalChecks(ctx)
1408 if msg != "" {
1409 a.pushToOutbox(ctx, AgentMessage{
1410 Type: AutoMessageType,
1411 Content: msg,
1412 Timestamp: time.Now(),
1413 })
1414 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001415 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001416
1417 return autoqualityMessages
1418}
1419
1420// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001421func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001422 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001423 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001424 msgs, err := a.GatherMessages(ctx, false)
1425 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001426 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001427 return false, nil
1428 }
1429
1430 // Inject any auto-generated messages from quality checks
1431 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001432 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001433 }
1434
1435 // Handle cancellation by appending a message about it
1436 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001437 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001438 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001439 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001440 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1441 } else if err := a.convo.OverBudget(); err != nil {
1442 // Handle budget issues by appending a message about it
1443 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 -07001444 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001445 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1446 }
1447
1448 // Combine tool results with user messages
1449 results = append(results, msgs...)
1450
1451 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001452 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001453 resp, err := a.convo.SendMessage(llm.Message{
1454 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001455 Content: results,
1456 })
1457 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001458 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001459 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1460 return true, nil // Return true to continue the conversation, but with no response
1461 }
1462
Sean McCullough96b60dd2025-04-30 09:49:10 -07001463 // Transition back to processing LLM response
1464 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1465
Sean McCullough885a16a2025-04-30 02:49:25 +00001466 if cancelled {
1467 return false, nil
1468 }
1469
1470 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001471}
1472
1473func (a *Agent) overBudget(ctx context.Context) error {
1474 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001475 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001476 m := budgetMessage(err)
1477 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001478 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001479 a.convo.ResetBudget(a.originalBudget)
1480 return err
1481 }
1482 return nil
1483}
1484
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001485func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001486 // Collect all text content
1487 var allText strings.Builder
1488 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001489 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001490 if allText.Len() > 0 {
1491 allText.WriteString("\n\n")
1492 }
1493 allText.WriteString(content.Text)
1494 }
1495 }
1496 return allText.String()
1497}
1498
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001499func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001500 a.mu.Lock()
1501 defer a.mu.Unlock()
1502 return a.convo.CumulativeUsage()
1503}
1504
Earl Lee2e463fb2025-04-17 11:22:22 -07001505// Diff returns a unified diff of changes made since the agent was instantiated.
1506func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001507 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001508 return "", fmt.Errorf("no initial commit reference available")
1509 }
1510
1511 // Find the repository root
1512 ctx := context.Background()
1513
1514 // If a specific commit hash is provided, show just that commit's changes
1515 if commit != nil && *commit != "" {
1516 // Validate that the commit looks like a valid git SHA
1517 if !isValidGitSHA(*commit) {
1518 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1519 }
1520
1521 // Get the diff for just this commit
1522 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1523 cmd.Dir = a.repoRoot
1524 output, err := cmd.CombinedOutput()
1525 if err != nil {
1526 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1527 }
1528 return string(output), nil
1529 }
1530
1531 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001532 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001533 cmd.Dir = a.repoRoot
1534 output, err := cmd.CombinedOutput()
1535 if err != nil {
1536 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1537 }
1538
1539 return string(output), nil
1540}
1541
Philip Zeyliger49edc922025-05-14 09:45:45 -07001542// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1543// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1544func (a *Agent) SketchGitBaseRef() string {
1545 if a.IsInContainer() {
1546 return "sketch-base"
1547 } else {
1548 return "sketch-base-" + a.SessionID()
1549 }
1550}
1551
1552// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1553func (a *Agent) SketchGitBase() string {
1554 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1555 cmd.Dir = a.repoRoot
1556 output, err := cmd.CombinedOutput()
1557 if err != nil {
1558 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1559 return "HEAD"
1560 }
1561 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001562}
1563
Pokey Rule7a113622025-05-12 10:58:45 +01001564// removeGitHooks removes the Git hooks directory from the repository
1565func removeGitHooks(_ context.Context, repoPath string) error {
1566 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1567
1568 // Check if hooks directory exists
1569 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1570 // Directory doesn't exist, nothing to do
1571 return nil
1572 }
1573
1574 // Remove the hooks directory
1575 err := os.RemoveAll(hooksDir)
1576 if err != nil {
1577 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1578 }
1579
1580 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001581 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001582 if err != nil {
1583 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1584 }
1585
1586 return nil
1587}
1588
Earl Lee2e463fb2025-04-17 11:22:22 -07001589// handleGitCommits() highlights new commits to the user. When running
1590// under docker, new HEADs are pushed to a branch according to the title.
1591func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1592 if a.repoRoot == "" {
1593 return nil, nil
1594 }
1595
1596 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1597 if err != nil {
1598 return nil, err
1599 }
1600 if head == a.lastHEAD {
1601 return nil, nil // nothing to do
1602 }
1603 defer func() {
1604 a.lastHEAD = head
1605 }()
1606
1607 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1608 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1609 // to the last 100 commits.
1610 var commits []*GitCommit
1611
1612 // Get commits since the initial commit
1613 // Format: <hash>\0<subject>\0<body>\0
1614 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1615 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyliger49edc922025-05-14 09:45:45 -07001616 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 -07001617 cmd.Dir = a.repoRoot
1618 output, err := cmd.Output()
1619 if err != nil {
1620 return nil, fmt.Errorf("failed to get git log: %w", err)
1621 }
1622
1623 // Parse git log output and filter out already seen commits
1624 parsedCommits := parseGitLog(string(output))
1625
1626 var headCommit *GitCommit
1627
1628 // Filter out commits we've already seen
1629 for _, commit := range parsedCommits {
1630 if commit.Hash == head {
1631 headCommit = &commit
1632 }
1633
1634 // Skip if we've seen this commit before. If our head has changed, always include that.
1635 if a.seenCommits[commit.Hash] && commit.Hash != head {
1636 continue
1637 }
1638
1639 // Mark this commit as seen
1640 a.seenCommits[commit.Hash] = true
1641
1642 // Add to our list of new commits
1643 commits = append(commits, &commit)
1644 }
1645
1646 if a.gitRemoteAddr != "" {
1647 if headCommit == nil {
1648 // I think this can only happen if we have a bug or if there's a race.
1649 headCommit = &GitCommit{}
1650 headCommit.Hash = head
1651 headCommit.Subject = "unknown"
1652 commits = append(commits, headCommit)
1653 }
1654
Philip Zeyliger113e2052025-05-09 21:59:40 +00001655 originalBranch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
1656 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001657
1658 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1659 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1660 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001661
1662 // Try up to 10 times with different branch names if the branch is checked out on the remote
1663 var out []byte
1664 var err error
1665 for retries := range 10 {
1666 if retries > 0 {
1667 // Add a numeric suffix to the branch name
1668 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1669 }
1670
1671 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1672 cmd.Dir = a.workingDir
1673 out, err = cmd.CombinedOutput()
1674
1675 if err == nil {
1676 // Success! Break out of the retry loop
1677 break
1678 }
1679
1680 // Check if this is the "refusing to update checked out branch" error
1681 if !strings.Contains(string(out), "refusing to update checked out branch") {
1682 // This is a different error, so don't retry
1683 break
1684 }
1685
1686 // If we're on the last retry, we'll report the error
1687 if retries == 9 {
1688 break
1689 }
1690 }
1691
1692 if err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07001693 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1694 } else {
1695 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001696 // Update the agent's branch name if we ended up using a different one
1697 if branch != originalBranch {
1698 a.branchName = branch
1699 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001700 }
1701 }
1702
1703 // If we found new commits, create a message
1704 if len(commits) > 0 {
1705 msg := AgentMessage{
1706 Type: CommitMessageType,
1707 Timestamp: time.Now(),
1708 Commits: commits,
1709 }
1710 a.pushToOutbox(ctx, msg)
1711 }
1712 return commits, nil
1713}
1714
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001715func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001716 return strings.Map(func(r rune) rune {
1717 // lowercase
1718 if r >= 'A' && r <= 'Z' {
1719 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001720 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001721 // replace spaces with dashes
1722 if r == ' ' {
1723 return '-'
1724 }
1725 // allow alphanumerics and dashes
1726 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1727 return r
1728 }
1729 return -1
1730 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001731}
1732
1733// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1734// and returns an array of GitCommit structs.
1735func parseGitLog(output string) []GitCommit {
1736 var commits []GitCommit
1737
1738 // No output means no commits
1739 if len(output) == 0 {
1740 return commits
1741 }
1742
1743 // Split by NULL byte
1744 parts := strings.Split(output, "\x00")
1745
1746 // Process in triplets (hash, subject, body)
1747 for i := 0; i < len(parts); i++ {
1748 // Skip empty parts
1749 if parts[i] == "" {
1750 continue
1751 }
1752
1753 // This should be a hash
1754 hash := strings.TrimSpace(parts[i])
1755
1756 // Make sure we have at least a subject part available
1757 if i+1 >= len(parts) {
1758 break // No more parts available
1759 }
1760
1761 // Get the subject
1762 subject := strings.TrimSpace(parts[i+1])
1763
1764 // Get the body if available
1765 body := ""
1766 if i+2 < len(parts) {
1767 body = strings.TrimSpace(parts[i+2])
1768 }
1769
1770 // Skip to the next triplet
1771 i += 2
1772
1773 commits = append(commits, GitCommit{
1774 Hash: hash,
1775 Subject: subject,
1776 Body: body,
1777 })
1778 }
1779
1780 return commits
1781}
1782
1783func repoRoot(ctx context.Context, dir string) (string, error) {
1784 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1785 stderr := new(strings.Builder)
1786 cmd.Stderr = stderr
1787 cmd.Dir = dir
1788 out, err := cmd.Output()
1789 if err != nil {
1790 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1791 }
1792 return strings.TrimSpace(string(out)), nil
1793}
1794
1795func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1796 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1797 stderr := new(strings.Builder)
1798 cmd.Stderr = stderr
1799 cmd.Dir = dir
1800 out, err := cmd.Output()
1801 if err != nil {
1802 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1803 }
1804 // TODO: validate that out is valid hex
1805 return strings.TrimSpace(string(out)), nil
1806}
1807
1808// isValidGitSHA validates if a string looks like a valid git SHA hash.
1809// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1810func isValidGitSHA(sha string) bool {
1811 // Git SHA must be a hexadecimal string with at least 4 characters
1812 if len(sha) < 4 || len(sha) > 40 {
1813 return false
1814 }
1815
1816 // Check if the string only contains hexadecimal characters
1817 for _, char := range sha {
1818 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1819 return false
1820 }
1821 }
1822
1823 return true
1824}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001825
1826// getGitOrigin returns the URL of the git remote 'origin' if it exists
1827func getGitOrigin(ctx context.Context, dir string) string {
1828 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1829 cmd.Dir = dir
1830 stderr := new(strings.Builder)
1831 cmd.Stderr = stderr
1832 out, err := cmd.Output()
1833 if err != nil {
1834 return ""
1835 }
1836 return strings.TrimSpace(string(out))
1837}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001838
1839func (a *Agent) initGitRevision(ctx context.Context, workingDir, revision string) error {
1840 cmd := exec.CommandContext(ctx, "git", "stash")
1841 cmd.Dir = workingDir
1842 if out, err := cmd.CombinedOutput(); err != nil {
1843 return fmt.Errorf("git stash: %s: %v", out, err)
1844 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +00001845 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001846 cmd.Dir = workingDir
1847 if out, err := cmd.CombinedOutput(); err != nil {
1848 return fmt.Errorf("git fetch: %s: %w", out, err)
1849 }
1850 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", revision)
1851 cmd.Dir = workingDir
1852 if out, err := cmd.CombinedOutput(); err != nil {
1853 return fmt.Errorf("git checkout %s: %s: %w", revision, out, err)
1854 }
1855 a.lastHEAD = revision
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001856 return nil
1857}
1858
1859func (a *Agent) RestartConversation(ctx context.Context, rev string, initialPrompt string) error {
1860 a.mu.Lock()
1861 a.title = ""
1862 a.firstMessageIndex = len(a.history)
1863 a.convo = a.initConvo()
1864 gitReset := func() error {
1865 if a.config.InDocker && rev != "" {
1866 err := a.initGitRevision(ctx, a.workingDir, rev)
1867 if err != nil {
1868 return err
1869 }
1870 } else if !a.config.InDocker && rev != "" {
1871 return fmt.Errorf("Not resetting git repo when working outside of a container.")
1872 }
1873 return nil
1874 }
1875 err := gitReset()
1876 a.mu.Unlock()
1877 if err != nil {
1878 a.pushToOutbox(a.config.Context, errorMessage(err))
1879 }
1880
1881 a.pushToOutbox(a.config.Context, AgentMessage{
1882 Type: AgentMessageType, Content: "Conversation restarted.",
1883 })
1884 if initialPrompt != "" {
1885 a.UserMessage(ctx, initialPrompt)
1886 }
1887 return nil
1888}
1889
1890func (a *Agent) SuggestReprompt(ctx context.Context) (string, error) {
1891 msg := `The user has requested a suggestion for a re-prompt.
1892
1893 Given the current conversation thus far, suggest a re-prompt that would
1894 capture the instructions and feedback so far, as well as any
1895 research or other information that would be helpful in implementing
1896 the task.
1897
1898 Reply with ONLY the reprompt text.
1899 `
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001900 userMessage := llm.UserStringMessage(msg)
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001901 // By doing this in a subconversation, the agent doesn't call tools (because
1902 // there aren't any), and there's not a concurrency risk with on-going other
1903 // outstanding conversations.
1904 convo := a.convo.SubConvoWithHistory()
1905 resp, err := convo.SendMessage(userMessage)
1906 if err != nil {
1907 a.pushToOutbox(ctx, errorMessage(err))
1908 return "", err
1909 }
1910 textContent := collectTextContent(resp)
1911 return textContent, nil
1912}
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001913
1914// systemPromptData contains the data used to render the system prompt template
1915type systemPromptData struct {
1916 EditPrompt string
1917 ClientGOOS string
1918 ClientGOARCH string
1919 WorkingDir string
1920 RepoRoot string
1921 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001922 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001923}
1924
1925// renderSystemPrompt renders the system prompt template.
1926func (a *Agent) renderSystemPrompt() string {
1927 // Determine the appropriate edit prompt based on config
1928 var editPrompt string
1929 if a.config.UseAnthropicEdit {
1930 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."
1931 } else {
1932 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
1933 }
1934
1935 data := systemPromptData{
1936 EditPrompt: editPrompt,
1937 ClientGOOS: a.config.ClientGOOS,
1938 ClientGOARCH: a.config.ClientGOARCH,
1939 WorkingDir: a.workingDir,
1940 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07001941 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001942 Codebase: a.codebase,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001943 }
1944
1945 tmpl, err := template.New("system").Parse(agentSystemPrompt)
1946 if err != nil {
1947 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
1948 }
1949 buf := new(strings.Builder)
1950 err = tmpl.Execute(buf, data)
1951 if err != nil {
1952 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
1953 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001954 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001955 return buf.String()
1956}
Philip Zeyligereab12de2025-05-14 02:35:53 +00001957
1958// StateTransitionIterator provides an iterator over state transitions.
1959type StateTransitionIterator interface {
1960 // Next blocks until a new state transition is available or context is done.
1961 // Returns nil if the context is cancelled.
1962 Next() *StateTransition
1963 // Close removes the listener and cleans up resources.
1964 Close()
1965}
1966
1967// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
1968type StateTransitionIteratorImpl struct {
1969 agent *Agent
1970 ctx context.Context
1971 ch chan StateTransition
1972 unsubscribe func()
1973}
1974
1975// Next blocks until a new state transition is available or the context is cancelled.
1976func (s *StateTransitionIteratorImpl) Next() *StateTransition {
1977 select {
1978 case <-s.ctx.Done():
1979 return nil
1980 case transition, ok := <-s.ch:
1981 if !ok {
1982 return nil
1983 }
1984 transitionCopy := transition
1985 return &transitionCopy
1986 }
1987}
1988
1989// Close removes the listener and cleans up resources.
1990func (s *StateTransitionIteratorImpl) Close() {
1991 if s.unsubscribe != nil {
1992 s.unsubscribe()
1993 s.unsubscribe = nil
1994 }
1995}
1996
1997// NewStateTransitionIterator returns an iterator that receives state transitions.
1998func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
1999 a.mu.Lock()
2000 defer a.mu.Unlock()
2001
2002 // Create channel to receive state transitions
2003 ch := make(chan StateTransition, 10)
2004
2005 // Add a listener to the state machine
2006 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2007
2008 return &StateTransitionIteratorImpl{
2009 agent: a,
2010 ctx: ctx,
2011 ch: ch,
2012 unsubscribe: unsubscribe,
2013 }
2014}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002015
2016// setupGitHooks creates or updates git hooks in the specified working directory.
2017func setupGitHooks(workingDir string) error {
2018 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2019
2020 _, err := os.Stat(hooksDir)
2021 if os.IsNotExist(err) {
2022 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2023 }
2024 if err != nil {
2025 return fmt.Errorf("error checking git hooks directory: %w", err)
2026 }
2027
2028 // Define the post-commit hook content
2029 postCommitHook := `#!/bin/bash
2030echo "<post_commit_hook>"
2031echo "Please review this commit message and fix it if it is incorrect."
2032echo "This hook only echos the commit message; it does not modify it."
2033echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2034echo "<last_commit_message>"
2035git log -1 --pretty=%B
2036echo "</last_commit_message>"
2037echo "</post_commit_hook>"
2038`
2039
2040 // Define the prepare-commit-msg hook content
2041 prepareCommitMsgHook := `#!/bin/bash
2042# Add Co-Authored-By and Change-ID trailers to commit messages
2043# Check if these trailers already exist before adding them
2044
2045commit_file="$1"
2046COMMIT_SOURCE="$2"
2047
2048# Skip for merges, squashes, or when using a commit template
2049if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2050 [ "$COMMIT_SOURCE" = "squash" ]; then
2051 exit 0
2052fi
2053
2054commit_msg=$(cat "$commit_file")
2055
2056needs_co_author=true
2057needs_change_id=true
2058
2059# Check if commit message already has Co-Authored-By trailer
2060if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2061 needs_co_author=false
2062fi
2063
2064# Check if commit message already has Change-ID trailer
2065if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2066 needs_change_id=false
2067fi
2068
2069# Only modify if at least one trailer needs to be added
2070if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
2071 # Ensure there's a blank line before trailers
2072 if [ -s "$commit_file" ] && [ "$(tail -1 "$commit_file" | tr -d '\n')" != "" ]; then
2073 echo "" >> "$commit_file"
2074 fi
2075
2076 # Add trailers if needed
2077 if [ "$needs_co_author" = true ]; then
2078 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2079 fi
2080
2081 if [ "$needs_change_id" = true ]; then
2082 change_id=$(openssl rand -hex 8)
2083 echo "Change-ID: s${change_id}k" >> "$commit_file"
2084 fi
2085fi
2086`
2087
2088 // Update or create the post-commit hook
2089 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2090 if err != nil {
2091 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2092 }
2093
2094 // Update or create the prepare-commit-msg hook
2095 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2096 if err != nil {
2097 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2098 }
2099
2100 return nil
2101}
2102
2103// updateOrCreateHook creates a new hook file or updates an existing one
2104// by appending the new content if it doesn't already contain it.
2105func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2106 // Check if the hook already exists
2107 buf, err := os.ReadFile(hookPath)
2108 if os.IsNotExist(err) {
2109 // Hook doesn't exist, create it
2110 err = os.WriteFile(hookPath, []byte(content), 0o755)
2111 if err != nil {
2112 return fmt.Errorf("failed to create hook: %w", err)
2113 }
2114 return nil
2115 }
2116 if err != nil {
2117 return fmt.Errorf("error reading existing hook: %w", err)
2118 }
2119
2120 // Hook exists, check if our content is already in it by looking for a distinctive line
2121 code := string(buf)
2122 if strings.Contains(code, distinctiveLine) {
2123 // Already contains our content, nothing to do
2124 return nil
2125 }
2126
2127 // Append our content to the existing hook
2128 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2129 if err != nil {
2130 return fmt.Errorf("failed to open hook for appending: %w", err)
2131 }
2132 defer f.Close()
2133
2134 // Ensure there's a newline at the end of the existing content if needed
2135 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2136 _, err = f.WriteString("\n")
2137 if err != nil {
2138 return fmt.Errorf("failed to add newline to hook: %w", err)
2139 }
2140 }
2141
2142 // Add a separator before our content
2143 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2144 if err != nil {
2145 return fmt.Errorf("failed to append to hook: %w", err)
2146 }
2147
2148 return nil
2149}