blob: 9fb53e5636fa08179b73f18518f2d9c381046224 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package loop
2
3import (
4 "context"
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -07005 _ "embed"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "encoding/json"
7 "fmt"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +00008 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "log/slog"
10 "net/http"
11 "os"
12 "os/exec"
Pokey Rule7a113622025-05-12 10:58:45 +010013 "path/filepath"
Earl Lee2e463fb2025-04-17 11:22:22 -070014 "runtime/debug"
15 "slices"
Philip Zeyligerb8a8f352025-06-02 07:39:37 -070016 "strconv"
Earl Lee2e463fb2025-04-17 11:22:22 -070017 "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"
Philip Zeyliger194bfa82025-06-24 06:03:06 -070031 "sketch.dev/mcp"
Philip Zeyligerc17ffe32025-06-05 19:49:13 -070032 "sketch.dev/skabandclient"
Earl Lee2e463fb2025-04-17 11:22:22 -070033)
34
35const (
36 userCancelMessage = "user requested agent to stop handling responses"
37)
38
Philip Zeyligerb7c58752025-05-01 10:10:17 -070039type MessageIterator interface {
40 // Next blocks until the next message is available. It may
41 // return nil if the underlying iterator context is done.
42 Next() *AgentMessage
43 Close()
44}
45
Earl Lee2e463fb2025-04-17 11:22:22 -070046type CodingAgent interface {
47 // Init initializes an agent inside a docker container.
48 Init(AgentInit) error
49
50 // Ready returns a channel closed after Init successfully called.
51 Ready() <-chan struct{}
52
53 // URL reports the HTTP URL of this agent.
54 URL() string
55
56 // UserMessage enqueues a message to the agent and returns immediately.
57 UserMessage(ctx context.Context, msg string)
58
Philip Zeyligerb7c58752025-05-01 10:10:17 -070059 // Returns an iterator that finishes when the context is done and
60 // starts with the given message index.
61 NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator
Earl Lee2e463fb2025-04-17 11:22:22 -070062
Philip Zeyligereab12de2025-05-14 02:35:53 +000063 // Returns an iterator that notifies of state transitions until the context is done.
64 NewStateTransitionIterator(ctx context.Context) StateTransitionIterator
65
Earl Lee2e463fb2025-04-17 11:22:22 -070066 // Loop begins the agent loop returns only when ctx is cancelled.
67 Loop(ctx context.Context)
68
Philip Zeyligerbe7802a2025-06-04 20:15:25 +000069 // BranchPrefix returns the configured branch prefix
70 BranchPrefix() string
71
philip.zeyliger6d3de482025-06-10 19:38:14 -070072 // LinkToGitHub returns whether GitHub branch linking is enabled
73 LinkToGitHub() bool
74
Sean McCulloughedc88dc2025-04-30 02:55:01 +000075 CancelTurn(cause error)
Earl Lee2e463fb2025-04-17 11:22:22 -070076
77 CancelToolUse(toolUseID string, cause error) error
78
79 // Returns a subset of the agent's message history.
80 Messages(start int, end int) []AgentMessage
81
82 // Returns the current number of messages in the history
83 MessageCount() int
84
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070085 TotalUsage() conversation.CumulativeUsage
86 OriginalBudget() conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -070087
Earl Lee2e463fb2025-04-17 11:22:22 -070088 WorkingDir() string
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +000089 RepoRoot() string
Earl Lee2e463fb2025-04-17 11:22:22 -070090
91 // Diff returns a unified diff of changes made since the agent was instantiated.
92 // If commit is non-nil, it shows the diff for just that specific commit.
93 Diff(commit *string) (string, error)
94
Philip Zeyliger49edc922025-05-14 09:45:45 -070095 // SketchGitBase returns the commit that's the "base" for Sketch's work. It
96 // starts out as the commit where sketch started, but a user can move it if need
97 // be, for example in the case of a rebase. It is stored as a git tag.
98 SketchGitBase() string
Earl Lee2e463fb2025-04-17 11:22:22 -070099
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000100 // SketchGitBase returns the symbolic name for the "base" for Sketch's work.
101 // (Typically, this is "sketch-base")
102 SketchGitBaseRef() string
103
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700104 // Slug returns the slug identifier for this session.
105 Slug() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700106
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000107 // BranchName returns the git branch name for the conversation.
108 BranchName() string
109
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700110 // IncrementRetryNumber increments the retry number for branch naming conflicts.
111 IncrementRetryNumber()
112
Earl Lee2e463fb2025-04-17 11:22:22 -0700113 // OS returns the operating system of the client.
114 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000115
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000116 // SessionID returns the unique session identifier.
117 SessionID() string
118
philip.zeyliger8773e682025-06-11 21:36:21 -0700119 // SSHConnectionString returns the SSH connection string for the container.
120 SSHConnectionString() string
121
Philip Zeyliger75bd37d2025-05-22 18:49:14 +0000122 // DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -0700123 DetectGitChanges(ctx context.Context) error
Philip Zeyliger75bd37d2025-05-22 18:49:14 +0000124
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000125 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
126 OutstandingLLMCallCount() int
127
128 // OutstandingToolCalls returns the names of outstanding tool calls.
129 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000130 OutsideOS() string
131 OutsideHostname() string
132 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000133 GitOrigin() string
Philip Zeyliger64f60462025-06-16 13:57:10 -0700134
bankseancad67b02025-06-27 21:57:05 +0000135 // GitUsername returns the git user name from the agent config.
136 GitUsername() string
137
Philip Zeyliger64f60462025-06-16 13:57:10 -0700138 // DiffStats returns the number of lines added and removed from sketch-base to HEAD
139 DiffStats() (int, int)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000140 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
141 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700142
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700143 // IsInContainer returns true if the agent is running in a container
144 IsInContainer() bool
145 // FirstMessageIndex returns the index of the first message in the current conversation
146 FirstMessageIndex() int
Sean McCulloughd9d45812025-04-30 16:53:41 -0700147
148 CurrentStateName() string
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700149 // CurrentTodoContent returns the current todo list data as JSON, or empty string if no todos exist
150 CurrentTodoContent() string
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700151
152 // CompactConversation compacts the current conversation by generating a summary
153 // and restarting the conversation with that summary as the initial context
154 CompactConversation(ctx context.Context) error
Sean McCullough138ec242025-06-02 22:42:06 +0000155 // GetPortMonitor returns the port monitor instance for accessing port events
156 GetPortMonitor() *PortMonitor
Philip Zeyliger0113be52025-06-07 23:53:41 +0000157 // SkabandAddr returns the skaband address if configured
158 SkabandAddr() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700159}
160
161type CodingAgentMessageType string
162
163const (
164 UserMessageType CodingAgentMessageType = "user"
165 AgentMessageType CodingAgentMessageType = "agent"
166 ErrorMessageType CodingAgentMessageType = "error"
167 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
168 ToolUseMessageType CodingAgentMessageType = "tool"
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700169 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
170 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
171 CompactMessageType CodingAgentMessageType = "compact" // for conversation compaction notifications
Earl Lee2e463fb2025-04-17 11:22:22 -0700172
173 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
174)
175
176type AgentMessage struct {
177 Type CodingAgentMessageType `json:"type"`
178 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
179 EndOfTurn bool `json:"end_of_turn"`
180
181 Content string `json:"content"`
182 ToolName string `json:"tool_name,omitempty"`
183 ToolInput string `json:"input,omitempty"`
184 ToolResult string `json:"tool_result,omitempty"`
185 ToolError bool `json:"tool_error,omitempty"`
186 ToolCallId string `json:"tool_call_id,omitempty"`
187
188 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
189 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
190
Sean McCulloughd9f13372025-04-21 15:08:49 -0700191 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
192 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
193
Earl Lee2e463fb2025-04-17 11:22:22 -0700194 // Commits is a list of git commits for a commit message
195 Commits []*GitCommit `json:"commits,omitempty"`
196
197 Timestamp time.Time `json:"timestamp"`
198 ConversationID string `json:"conversation_id"`
199 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700200 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700201
202 // Message timing information
203 StartTime *time.Time `json:"start_time,omitempty"`
204 EndTime *time.Time `json:"end_time,omitempty"`
205 Elapsed *time.Duration `json:"elapsed,omitempty"`
206
207 // Turn duration - the time taken for a complete agent turn
208 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
209
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000210 // HideOutput indicates that this message should not be rendered in the UI.
211 // This is useful for subconversations that generate output that shouldn't be shown to the user.
212 HideOutput bool `json:"hide_output,omitempty"`
213
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700214 // TodoContent contains the agent's todo file content when it has changed
215 TodoContent *string `json:"todo_content,omitempty"`
216
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 Idx int `json:"idx"`
218}
219
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000220// SetConvo sets m.ConversationID, m.ParentConversationID, and m.HideOutput based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700221func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700222 if convo == nil {
223 m.ConversationID = ""
224 m.ParentConversationID = nil
225 return
226 }
227 m.ConversationID = convo.ID
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000228 m.HideOutput = convo.Hidden
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700229 if convo.Parent != nil {
230 m.ParentConversationID = &convo.Parent.ID
231 }
232}
233
Earl Lee2e463fb2025-04-17 11:22:22 -0700234// GitCommit represents a single git commit for a commit message
235type GitCommit struct {
236 Hash string `json:"hash"` // Full commit hash
237 Subject string `json:"subject"` // Commit subject line
238 Body string `json:"body"` // Full commit message body
239 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
240}
241
242// ToolCall represents a single tool call within an agent message
243type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700244 Name string `json:"name"`
245 Input string `json:"input"`
246 ToolCallId string `json:"tool_call_id"`
247 ResultMessage *AgentMessage `json:"result_message,omitempty"`
248 Args string `json:"args,omitempty"`
249 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700250}
251
252func (a *AgentMessage) Attr() slog.Attr {
253 var attrs []any = []any{
254 slog.String("type", string(a.Type)),
255 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700256 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700257 if a.EndOfTurn {
258 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
259 }
260 if a.Content != "" {
261 attrs = append(attrs, slog.String("content", a.Content))
262 }
263 if a.ToolName != "" {
264 attrs = append(attrs, slog.String("tool_name", a.ToolName))
265 }
266 if a.ToolInput != "" {
267 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
268 }
269 if a.Elapsed != nil {
270 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
271 }
272 if a.TurnDuration != nil {
273 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
274 }
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700275 if len(a.ToolResult) > 0 {
276 attrs = append(attrs, slog.Any("tool_result", a.ToolResult))
Earl Lee2e463fb2025-04-17 11:22:22 -0700277 }
278 if a.ToolError {
279 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
280 }
281 if len(a.ToolCalls) > 0 {
282 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
283 for i, tc := range a.ToolCalls {
284 toolCallAttrs = append(toolCallAttrs, slog.Group(
285 fmt.Sprintf("tool_call_%d", i),
286 slog.String("name", tc.Name),
287 slog.String("input", tc.Input),
288 ))
289 }
290 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
291 }
292 if a.ConversationID != "" {
293 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
294 }
295 if a.ParentConversationID != nil {
296 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
297 }
298 if a.Usage != nil && !a.Usage.IsZero() {
299 attrs = append(attrs, a.Usage.Attr())
300 }
301 // TODO: timestamp, convo ids, idx?
302 return slog.Group("agent_message", attrs...)
303}
304
305func errorMessage(err error) AgentMessage {
306 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
307 if os.Getenv(("DEBUG")) == "1" {
308 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
309 }
310
311 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
312}
313
314func budgetMessage(err error) AgentMessage {
315 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
316}
317
318// ConvoInterface defines the interface for conversation interactions
319type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700320 CumulativeUsage() conversation.CumulativeUsage
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700321 LastUsage() llm.Usage
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700322 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700323 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700324 SendMessage(message llm.Message) (*llm.Response, error)
325 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700326 GetID() string
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +0000327 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, bool, error)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700328 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700329 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700330 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700331}
332
Philip Zeyligerf2872992025-05-22 10:35:28 -0700333// AgentGitState holds the state necessary for pushing to a remote git repo
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -0700334// when sketch branch changes. If gitRemoteAddr is set, then we push to sketch/
Philip Zeyligerf2872992025-05-22 10:35:28 -0700335// any time we notice we need to.
336type AgentGitState struct {
337 mu sync.Mutex // protects following
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -0700338 lastSketch string // hash of the last sketch branch that was pushed to the host
Philip Zeyligerf2872992025-05-22 10:35:28 -0700339 gitRemoteAddr string // HTTP URL of the host git repo
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000340 upstream string // upstream branch for git work
Philip Zeyligerf2872992025-05-22 10:35:28 -0700341 seenCommits map[string]bool // Track git commits we've already seen (by hash)
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700342 slug string // Human-readable session identifier
343 retryNumber int // Number to append when branch conflicts occur
Philip Zeyliger64f60462025-06-16 13:57:10 -0700344 linesAdded int // Lines added from sketch-base to HEAD
345 linesRemoved int // Lines removed from sketch-base to HEAD
Philip Zeyligerf2872992025-05-22 10:35:28 -0700346}
347
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700348func (ags *AgentGitState) SetSlug(slug string) {
Philip Zeyligerf2872992025-05-22 10:35:28 -0700349 ags.mu.Lock()
350 defer ags.mu.Unlock()
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700351 if ags.slug != slug {
352 ags.retryNumber = 0
353 }
354 ags.slug = slug
Philip Zeyligerf2872992025-05-22 10:35:28 -0700355}
356
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700357func (ags *AgentGitState) Slug() string {
Philip Zeyligerf2872992025-05-22 10:35:28 -0700358 ags.mu.Lock()
359 defer ags.mu.Unlock()
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700360 return ags.slug
361}
362
363func (ags *AgentGitState) IncrementRetryNumber() {
364 ags.mu.Lock()
365 defer ags.mu.Unlock()
366 ags.retryNumber++
367}
368
Philip Zeyliger64f60462025-06-16 13:57:10 -0700369func (ags *AgentGitState) DiffStats() (int, int) {
370 ags.mu.Lock()
371 defer ags.mu.Unlock()
372 return ags.linesAdded, ags.linesRemoved
373}
374
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700375// HasSeenCommits returns true if any commits have been processed
376func (ags *AgentGitState) HasSeenCommits() bool {
377 ags.mu.Lock()
378 defer ags.mu.Unlock()
379 return len(ags.seenCommits) > 0
380}
381
382func (ags *AgentGitState) RetryNumber() int {
383 ags.mu.Lock()
384 defer ags.mu.Unlock()
385 return ags.retryNumber
386}
387
388func (ags *AgentGitState) BranchName(prefix string) string {
389 ags.mu.Lock()
390 defer ags.mu.Unlock()
391 return ags.branchNameLocked(prefix)
392}
393
394func (ags *AgentGitState) branchNameLocked(prefix string) string {
395 if ags.slug == "" {
396 return ""
397 }
398 if ags.retryNumber == 0 {
399 return prefix + ags.slug
400 }
401 return fmt.Sprintf("%s%s%d", prefix, ags.slug, ags.retryNumber)
Philip Zeyligerf2872992025-05-22 10:35:28 -0700402}
403
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000404func (ags *AgentGitState) Upstream() string {
405 ags.mu.Lock()
406 defer ags.mu.Unlock()
407 return ags.upstream
408}
409
Earl Lee2e463fb2025-04-17 11:22:22 -0700410type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700411 convo ConvoInterface
412 config AgentConfig // config for this agent
Philip Zeyligerf2872992025-05-22 10:35:28 -0700413 gitState AgentGitState
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700414 workingDir string
415 repoRoot string // workingDir may be a subdir of repoRoot
416 url string
417 firstMessageIndex int // index of the first message in the current conversation
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000418 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700419 ready chan struct{} // closed when the agent is initialized (only when under docker)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000420 codebase *onstart.Codebase
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700421 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700422 originalBudget conversation.Budget
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000423 codereview *codereview.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700424 // State machine to track agent state
425 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000426 // Outside information
427 outsideHostname string
428 outsideOS string
429 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000430 // URL of the git remote 'origin' if it exists
431 gitOrigin string
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700432 // MCP manager for handling MCP server connections
433 mcpManager *mcp.MCPManager
Earl Lee2e463fb2025-04-17 11:22:22 -0700434
435 // Time when the current turn started (reset at the beginning of InnerLoop)
436 startOfTurn time.Time
437
438 // Inbox - for messages from the user to the agent.
439 // sent on by UserMessage
440 // . e.g. when user types into the chat textarea
441 // read from by GatherMessages
442 inbox chan string
443
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000444 // protects cancelTurn
445 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700446 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000447 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700448
449 // protects following
450 mu sync.Mutex
451
452 // Stores all messages for this agent
453 history []AgentMessage
454
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700455 // Iterators add themselves here when they're ready to be notified of new messages.
456 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700457
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000458 // Track outstanding LLM call IDs
459 outstandingLLMCalls map[string]struct{}
460
461 // Track outstanding tool calls by ID with their names
462 outstandingToolCalls map[string]string
Sean McCullough364f7412025-06-02 00:55:44 +0000463
464 // Port monitoring
465 portMonitor *PortMonitor
Earl Lee2e463fb2025-04-17 11:22:22 -0700466}
467
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700468// NewIterator implements CodingAgent.
469func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
470 a.mu.Lock()
471 defer a.mu.Unlock()
472
473 return &MessageIteratorImpl{
474 agent: a,
475 ctx: ctx,
476 nextMessageIdx: nextMessageIdx,
477 ch: make(chan *AgentMessage, 100),
478 }
479}
480
481type MessageIteratorImpl struct {
482 agent *Agent
483 ctx context.Context
484 nextMessageIdx int
485 ch chan *AgentMessage
486 subscribed bool
487}
488
489func (m *MessageIteratorImpl) Close() {
490 m.agent.mu.Lock()
491 defer m.agent.mu.Unlock()
492 // Delete ourselves from the subscribers list
493 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
494 return x == m.ch
495 })
496 close(m.ch)
497}
498
499func (m *MessageIteratorImpl) Next() *AgentMessage {
500 // We avoid subscription at creation to let ourselves catch up to "current state"
501 // before subscribing.
502 if !m.subscribed {
503 m.agent.mu.Lock()
504 if m.nextMessageIdx < len(m.agent.history) {
505 msg := &m.agent.history[m.nextMessageIdx]
506 m.nextMessageIdx++
507 m.agent.mu.Unlock()
508 return msg
509 }
510 // The next message doesn't exist yet, so let's subscribe
511 m.agent.subscribers = append(m.agent.subscribers, m.ch)
512 m.subscribed = true
513 m.agent.mu.Unlock()
514 }
515
516 for {
517 select {
518 case <-m.ctx.Done():
519 m.agent.mu.Lock()
520 // Delete ourselves from the subscribers list
521 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
522 return x == m.ch
523 })
524 m.subscribed = false
525 m.agent.mu.Unlock()
526 return nil
527 case msg, ok := <-m.ch:
528 if !ok {
529 // Close may have been called
530 return nil
531 }
532 if msg.Idx == m.nextMessageIdx {
533 m.nextMessageIdx++
534 return msg
535 }
536 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
537 panic("out of order message")
538 }
539 }
540}
541
Sean McCulloughd9d45812025-04-30 16:53:41 -0700542// Assert that Agent satisfies the CodingAgent interface.
543var _ CodingAgent = &Agent{}
544
545// StateName implements CodingAgent.
546func (a *Agent) CurrentStateName() string {
547 if a.stateMachine == nil {
548 return ""
549 }
Josh Bleecher Snydered17fdf2025-05-23 17:26:07 +0000550 return a.stateMachine.CurrentState().String()
Sean McCulloughd9d45812025-04-30 16:53:41 -0700551}
552
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -0700553// CurrentTodoContent returns the current todo list data as JSON.
554// It returns an empty string if no todos exist.
555func (a *Agent) CurrentTodoContent() string {
556 todoPath := claudetool.TodoFilePath(a.config.SessionID)
557 content, err := os.ReadFile(todoPath)
558 if err != nil {
559 return ""
560 }
561 return string(content)
562}
563
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700564// generateConversationSummary asks the LLM to create a comprehensive summary of the current conversation
565func (a *Agent) generateConversationSummary(ctx context.Context) (string, error) {
566 msg := `You are being asked to create a comprehensive summary of our conversation so far. This summary will be used to restart our conversation with a shorter history while preserving all important context.
567
568IMPORTANT: Focus ONLY on the actual conversation with the user. Do NOT include any information from system prompts, tool descriptions, or general instructions. Only summarize what the user asked for and what we accomplished together.
569
570Please create a detailed summary that includes:
571
5721. **User's Request**: What did the user originally ask me to do? What was their goal?
573
5742. **Work Completed**: What have we accomplished together? Include any code changes, files created/modified, problems solved, etc.
575
5763. **Key Technical Decisions**: What important technical choices were made during our work and why?
577
5784. **Current State**: What is the current state of the project? What files, tools, or systems are we working with?
579
5805. **Next Steps**: What still needs to be done to complete the user's request?
581
5826. **Important Context**: Any crucial information about the user's codebase, environment, constraints, or specific preferences they mentioned.
583
584Focus on actionable information that would help me continue the user's work seamlessly. Ignore any general tool capabilities or system instructions - only include what's relevant to this specific user's project and goals.
585
586Reply with ONLY the summary content - no meta-commentary about creating the summary.`
587
588 userMessage := llm.UserStringMessage(msg)
589 // Use a subconversation with history to get the summary
590 // TODO: We don't have any tools here, so we should have enough tokens
591 // to capture a summary, but we may need to modify the history (e.g., remove
592 // TODO data) to save on some tokens.
593 convo := a.convo.SubConvoWithHistory()
594
595 // Modify the system prompt to provide context about the original task
596 originalSystemPrompt := convo.SystemPrompt
Josh Bleecher Snyder068f4bb2025-06-05 19:12:22 +0000597 convo.SystemPrompt = `You are creating a conversation summary for context compaction. The original system prompt contained instructions about being a software engineer and architect for Sketch (an agentic coding environment), with various tools and capabilities for code analysis, file modification, git operations, browser automation, and project management.
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700598
599Your task is to create a focused summary as requested below. Focus only on the actual user conversation and work accomplished, not the system capabilities or tool descriptions.
600
Josh Bleecher Snyder068f4bb2025-06-05 19:12:22 +0000601Original context: You are working in a coding environment with full access to development tools.`
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700602
603 resp, err := convo.SendMessage(userMessage)
604 if err != nil {
605 a.pushToOutbox(ctx, errorMessage(err))
606 return "", err
607 }
608 textContent := collectTextContent(resp)
609
610 // Restore original system prompt (though this subconvo will be discarded)
611 convo.SystemPrompt = originalSystemPrompt
612
613 return textContent, nil
614}
615
616// CompactConversation compacts the current conversation by generating a summary
617// and restarting the conversation with that summary as the initial context
618func (a *Agent) CompactConversation(ctx context.Context) error {
619 summary, err := a.generateConversationSummary(ctx)
620 if err != nil {
621 return fmt.Errorf("failed to generate conversation summary: %w", err)
622 }
623
624 a.mu.Lock()
625
626 // Get usage information before resetting conversation
627 lastUsage := a.convo.LastUsage()
628 contextWindow := a.config.Service.TokenContextWindow()
629 currentContextSize := lastUsage.InputTokens + lastUsage.CacheReadInputTokens + lastUsage.CacheCreationInputTokens
630
philip.zeyliger882e7ea2025-06-20 14:31:16 +0000631 // Preserve cumulative usage across compaction
632 cumulativeUsage := a.convo.CumulativeUsage()
633
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700634 // Reset conversation state but keep all other state (git, working dir, etc.)
635 a.firstMessageIndex = len(a.history)
philip.zeyliger882e7ea2025-06-20 14:31:16 +0000636 a.convo = a.initConvoWithUsage(&cumulativeUsage)
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700637
638 a.mu.Unlock()
639
640 // Create informative compaction message with token details
641 compactionMsg := fmt.Sprintf("📜 Conversation compacted to manage token limits. Previous context preserved in summary below.\n\n"+
642 "**Token Usage:** %d / %d tokens (%.1f%% of context window)",
643 currentContextSize, contextWindow, float64(currentContextSize)/float64(contextWindow)*100)
644
645 a.pushToOutbox(ctx, AgentMessage{
646 Type: CompactMessageType,
647 Content: compactionMsg,
648 })
649
650 a.pushToOutbox(ctx, AgentMessage{
651 Type: UserMessageType,
652 Content: fmt.Sprintf("Here's a summary of our previous work:\n\n%s\n\nPlease continue with the work based on this summary.", summary),
653 })
654 a.inbox <- fmt.Sprintf("Here's a summary of our previous work:\n\n%s\n\nPlease continue with the work based on this summary.", summary)
655
656 return nil
657}
658
Earl Lee2e463fb2025-04-17 11:22:22 -0700659func (a *Agent) URL() string { return a.url }
660
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000661// BranchName returns the git branch name for the conversation.
662func (a *Agent) BranchName() string {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700663 return a.gitState.BranchName(a.config.BranchPrefix)
664}
665
666// Slug returns the slug identifier for this conversation.
667func (a *Agent) Slug() string {
668 return a.gitState.Slug()
669}
670
671// IncrementRetryNumber increments the retry number for branch naming conflicts
672func (a *Agent) IncrementRetryNumber() {
673 a.gitState.IncrementRetryNumber()
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000674}
675
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000676// OutstandingLLMCallCount returns the number of outstanding LLM calls.
677func (a *Agent) OutstandingLLMCallCount() int {
678 a.mu.Lock()
679 defer a.mu.Unlock()
680 return len(a.outstandingLLMCalls)
681}
682
683// OutstandingToolCalls returns the names of outstanding tool calls.
684func (a *Agent) OutstandingToolCalls() []string {
685 a.mu.Lock()
686 defer a.mu.Unlock()
687
688 tools := make([]string, 0, len(a.outstandingToolCalls))
689 for _, toolName := range a.outstandingToolCalls {
690 tools = append(tools, toolName)
691 }
692 return tools
693}
694
Earl Lee2e463fb2025-04-17 11:22:22 -0700695// OS returns the operating system of the client.
696func (a *Agent) OS() string {
697 return a.config.ClientGOOS
698}
699
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000700func (a *Agent) SessionID() string {
701 return a.config.SessionID
702}
703
philip.zeyliger8773e682025-06-11 21:36:21 -0700704// SSHConnectionString returns the SSH connection string for the container.
705func (a *Agent) SSHConnectionString() string {
706 return a.config.SSHConnectionString
707}
708
Philip Zeyliger18532b22025-04-23 21:11:46 +0000709// OutsideOS returns the operating system of the outside system.
710func (a *Agent) OutsideOS() string {
711 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000712}
713
Philip Zeyliger18532b22025-04-23 21:11:46 +0000714// OutsideHostname returns the hostname of the outside system.
715func (a *Agent) OutsideHostname() string {
716 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000717}
718
Philip Zeyliger18532b22025-04-23 21:11:46 +0000719// OutsideWorkingDir returns the working directory on the outside system.
720func (a *Agent) OutsideWorkingDir() string {
721 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000722}
723
724// GitOrigin returns the URL of the git remote 'origin' if it exists.
725func (a *Agent) GitOrigin() string {
726 return a.gitOrigin
727}
728
bankseancad67b02025-06-27 21:57:05 +0000729// GitUsername returns the git user name from the agent config.
730func (a *Agent) GitUsername() string {
731 return a.config.GitUsername
732}
733
Philip Zeyliger64f60462025-06-16 13:57:10 -0700734// DiffStats returns the number of lines added and removed from sketch-base to HEAD
735func (a *Agent) DiffStats() (int, int) {
736 return a.gitState.DiffStats()
737}
738
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000739func (a *Agent) OpenBrowser(url string) {
740 if !a.IsInContainer() {
741 browser.Open(url)
742 return
743 }
744 // We're in Docker, need to send a request to the Git server
745 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700746 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000747 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700748 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000749 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700750 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000751 return
752 }
753 defer resp.Body.Close()
754 if resp.StatusCode == http.StatusOK {
755 return
756 }
757 body, _ := io.ReadAll(resp.Body)
758 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
759}
760
Sean McCullough96b60dd2025-04-30 09:49:10 -0700761// CurrentState returns the current state of the agent's state machine.
762func (a *Agent) CurrentState() State {
763 return a.stateMachine.CurrentState()
764}
765
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700766func (a *Agent) IsInContainer() bool {
767 return a.config.InDocker
768}
769
770func (a *Agent) FirstMessageIndex() int {
771 a.mu.Lock()
772 defer a.mu.Unlock()
773 return a.firstMessageIndex
774}
775
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700776// SetSlug sets a human-readable identifier for the conversation.
777func (a *Agent) SetSlug(slug string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700778 a.mu.Lock()
779 defer a.mu.Unlock()
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700780
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700781 a.gitState.SetSlug(slug)
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000782 convo, ok := a.convo.(*conversation.Convo)
783 if ok {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -0700784 convo.ExtraData["branch"] = a.BranchName()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000785 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700786}
787
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000788// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700789func (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 +0000790 // Track the tool call
791 a.mu.Lock()
792 a.outstandingToolCalls[id] = toolName
793 a.mu.Unlock()
794}
795
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700796// contentToString converts []llm.Content to a string, concatenating all text content and skipping non-text types.
797// If there's only one element in the array and it's a text type, it returns that text directly.
798// It also processes nested ToolResult arrays recursively.
799func contentToString(contents []llm.Content) string {
800 if len(contents) == 0 {
801 return ""
802 }
803
804 // If there's only one element and it's a text type, return it directly
805 if len(contents) == 1 && contents[0].Type == llm.ContentTypeText {
806 return contents[0].Text
807 }
808
809 // Otherwise, concatenate all text content
810 var result strings.Builder
811 for _, content := range contents {
812 if content.Type == llm.ContentTypeText {
813 result.WriteString(content.Text)
814 } else if content.Type == llm.ContentTypeToolResult && len(content.ToolResult) > 0 {
815 // Recursively process nested tool results
816 result.WriteString(contentToString(content.ToolResult))
817 }
818 }
819
820 return result.String()
821}
822
Earl Lee2e463fb2025-04-17 11:22:22 -0700823// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700824func (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 +0000825 // Remove the tool call from outstanding calls
826 a.mu.Lock()
827 delete(a.outstandingToolCalls, toolID)
828 a.mu.Unlock()
829
Earl Lee2e463fb2025-04-17 11:22:22 -0700830 m := AgentMessage{
831 Type: ToolUseMessageType,
832 Content: content.Text,
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700833 ToolResult: contentToString(content.ToolResult),
Earl Lee2e463fb2025-04-17 11:22:22 -0700834 ToolError: content.ToolError,
835 ToolName: toolName,
836 ToolInput: string(toolInput),
837 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700838 StartTime: content.ToolUseStartTime,
839 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700840 }
841
842 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700843 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
844 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700845 m.Elapsed = &elapsed
846 }
847
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700848 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700849 a.pushToOutbox(ctx, m)
850}
851
852// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700853func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000854 a.mu.Lock()
855 defer a.mu.Unlock()
856 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700857 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
858}
859
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700860// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700861// that need to be displayed (as well as tool calls that we send along when
862// they're done). (It would be reasonable to also mention tool calls when they're
863// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700864func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000865 // Remove the LLM call from outstanding calls
866 a.mu.Lock()
867 delete(a.outstandingLLMCalls, id)
868 a.mu.Unlock()
869
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700870 if resp == nil {
871 // LLM API call failed
872 m := AgentMessage{
873 Type: ErrorMessageType,
874 Content: "API call failed, type 'continue' to try again",
875 }
876 m.SetConvo(convo)
877 a.pushToOutbox(ctx, m)
878 return
879 }
880
Earl Lee2e463fb2025-04-17 11:22:22 -0700881 endOfTurn := false
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700882 if convo.Parent == nil { // subconvos never end the turn
883 switch resp.StopReason {
884 case llm.StopReasonToolUse:
885 // Check whether any of the tool calls are for tools that should end the turn
886 ToolSearch:
887 for _, part := range resp.Content {
888 if part.Type != llm.ContentTypeToolUse {
889 continue
890 }
Sean McCullough021557a2025-05-05 23:20:53 +0000891 // Find the tool by name
892 for _, tool := range convo.Tools {
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700893 if tool.Name == part.ToolName {
894 endOfTurn = tool.EndsTurn
895 break ToolSearch
Sean McCullough021557a2025-05-05 23:20:53 +0000896 }
897 }
Sean McCullough021557a2025-05-05 23:20:53 +0000898 }
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700899 default:
900 endOfTurn = true
Sean McCullough021557a2025-05-05 23:20:53 +0000901 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700902 }
903 m := AgentMessage{
904 Type: AgentMessageType,
905 Content: collectTextContent(resp),
906 EndOfTurn: endOfTurn,
907 Usage: &resp.Usage,
908 StartTime: resp.StartTime,
909 EndTime: resp.EndTime,
910 }
911
912 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700913 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700914 var toolCalls []ToolCall
915 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700916 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700917 toolCalls = append(toolCalls, ToolCall{
918 Name: part.ToolName,
919 Input: string(part.ToolInput),
920 ToolCallId: part.ID,
921 })
922 }
923 }
924 m.ToolCalls = toolCalls
925 }
926
927 // Calculate the elapsed time if both start and end times are set
928 if resp.StartTime != nil && resp.EndTime != nil {
929 elapsed := resp.EndTime.Sub(*resp.StartTime)
930 m.Elapsed = &elapsed
931 }
932
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700933 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700934 a.pushToOutbox(ctx, m)
935}
936
937// WorkingDir implements CodingAgent.
938func (a *Agent) WorkingDir() string {
939 return a.workingDir
940}
941
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +0000942// RepoRoot returns the git repository root directory.
943func (a *Agent) RepoRoot() string {
944 return a.repoRoot
945}
946
Earl Lee2e463fb2025-04-17 11:22:22 -0700947// MessageCount implements CodingAgent.
948func (a *Agent) MessageCount() int {
949 a.mu.Lock()
950 defer a.mu.Unlock()
951 return len(a.history)
952}
953
954// Messages implements CodingAgent.
955func (a *Agent) Messages(start int, end int) []AgentMessage {
956 a.mu.Lock()
957 defer a.mu.Unlock()
958 return slices.Clone(a.history[start:end])
959}
960
Philip Zeyligerb8a8f352025-06-02 07:39:37 -0700961// ShouldCompact checks if the conversation should be compacted based on token usage
962func (a *Agent) ShouldCompact() bool {
963 // Get the threshold from environment variable, default to 0.94 (94%)
964 // (Because default Claude output is 8192 tokens, which is 4% of 200,000 tokens,
965 // and a little bit of buffer.)
966 thresholdRatio := 0.94
967 if envThreshold := os.Getenv("SKETCH_COMPACT_THRESHOLD_RATIO"); envThreshold != "" {
968 if parsed, err := strconv.ParseFloat(envThreshold, 64); err == nil && parsed > 0 && parsed <= 1.0 {
969 thresholdRatio = parsed
970 }
971 }
972
973 // Get the most recent usage to check current context size
974 lastUsage := a.convo.LastUsage()
975
976 if lastUsage.InputTokens == 0 {
977 // No API calls made yet
978 return false
979 }
980
981 // Calculate the current context size from the last API call
982 // This includes all tokens that were part of the input context:
983 // - Input tokens (user messages, system prompt, conversation history)
984 // - Cache read tokens (cached parts of the context)
985 // - Cache creation tokens (new parts being cached)
986 currentContextSize := lastUsage.InputTokens + lastUsage.CacheReadInputTokens + lastUsage.CacheCreationInputTokens
987
988 // Get the service's token context window
989 service := a.config.Service
990 contextWindow := service.TokenContextWindow()
991
992 // Calculate threshold
993 threshold := uint64(float64(contextWindow) * thresholdRatio)
994
995 // Check if we've exceeded the threshold
996 return currentContextSize >= threshold
997}
998
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700999func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -07001000 return a.originalBudget
1001}
1002
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +00001003// Upstream returns the upstream branch for git work
1004func (a *Agent) Upstream() string {
1005 return a.gitState.Upstream()
1006}
1007
Earl Lee2e463fb2025-04-17 11:22:22 -07001008// AgentConfig contains configuration for creating a new Agent.
1009type AgentConfig struct {
Josh Bleecher Snyderb421a242025-05-29 23:22:55 +00001010 Context context.Context
1011 Service llm.Service
1012 Budget conversation.Budget
1013 GitUsername string
1014 GitEmail string
1015 SessionID string
1016 ClientGOOS string
1017 ClientGOARCH string
1018 InDocker bool
1019 OneShot bool
1020 WorkingDir string
Philip Zeyliger18532b22025-04-23 21:11:46 +00001021 // Outside information
1022 OutsideHostname string
1023 OutsideOS string
1024 OutsideWorkingDir string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001025
1026 // Outtie's HTTP to, e.g., open a browser
1027 OutsideHTTP string
1028 // Outtie's Git server
1029 GitRemoteAddr string
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +00001030 // Upstream branch for git work
1031 Upstream string
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001032 // Commit to checkout from Outtie
1033 Commit string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001034 // Prefix for git branches created by sketch
1035 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -07001036 // LinkToGitHub enables GitHub branch linking in UI
1037 LinkToGitHub bool
philip.zeyliger8773e682025-06-11 21:36:21 -07001038 // SSH connection string for connecting to the container
1039 SSHConnectionString string
Philip Zeyligerc17ffe32025-06-05 19:49:13 -07001040 // Skaband client for session history (optional)
1041 SkabandClient *skabandclient.SkabandClient
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001042 // MCP server configurations
1043 MCPServers []string
Earl Lee2e463fb2025-04-17 11:22:22 -07001044}
1045
1046// NewAgent creates a new Agent.
1047// It is not usable until Init() is called.
1048func NewAgent(config AgentConfig) *Agent {
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001049 // Set default branch prefix if not specified
1050 if config.BranchPrefix == "" {
1051 config.BranchPrefix = "sketch/"
1052 }
1053
Earl Lee2e463fb2025-04-17 11:22:22 -07001054 agent := &Agent{
Philip Zeyligerf2872992025-05-22 10:35:28 -07001055 config: config,
1056 ready: make(chan struct{}),
1057 inbox: make(chan string, 100),
1058 subscribers: make([]chan *AgentMessage, 0),
1059 startedAt: time.Now(),
1060 originalBudget: config.Budget,
1061 gitState: AgentGitState{
1062 seenCommits: make(map[string]bool),
1063 gitRemoteAddr: config.GitRemoteAddr,
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +00001064 upstream: config.Upstream,
Philip Zeyligerf2872992025-05-22 10:35:28 -07001065 },
Philip Zeyliger99a9a022025-04-27 15:15:25 +00001066 outsideHostname: config.OutsideHostname,
1067 outsideOS: config.OutsideOS,
1068 outsideWorkingDir: config.OutsideWorkingDir,
1069 outstandingLLMCalls: make(map[string]struct{}),
1070 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -07001071 stateMachine: NewStateMachine(),
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001072 workingDir: config.WorkingDir,
1073 outsideHTTP: config.OutsideHTTP,
Sean McCullough364f7412025-06-02 00:55:44 +00001074 portMonitor: NewPortMonitor(),
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001075 mcpManager: mcp.NewMCPManager(),
Earl Lee2e463fb2025-04-17 11:22:22 -07001076 }
1077 return agent
1078}
1079
1080type AgentInit struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001081 NoGit bool // only for testing
Earl Lee2e463fb2025-04-17 11:22:22 -07001082
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001083 InDocker bool
1084 HostAddr string
Earl Lee2e463fb2025-04-17 11:22:22 -07001085}
1086
1087func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -07001088 if a.convo != nil {
1089 return fmt.Errorf("Agent.Init: already initialized")
1090 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001091 ctx := a.config.Context
Philip Zeyliger716bfee2025-05-21 18:32:31 -07001092 slog.InfoContext(ctx, "agent initializing")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001093
Philip Zeyliger2f0eb692025-06-04 09:53:42 -07001094 if !ini.NoGit {
1095 // Capture the original origin before we potentially replace it below
1096 a.gitOrigin = getGitOrigin(ctx, a.workingDir)
1097 }
1098
Philip Zeyliger222bf412025-06-04 16:42:58 +00001099 // If a remote git addr was specified, we configure the origin remote
Philip Zeyligerf2872992025-05-22 10:35:28 -07001100 if a.gitState.gitRemoteAddr != "" {
1101 slog.InfoContext(ctx, "Configuring git remote", slog.String("remote", a.gitState.gitRemoteAddr))
Philip Zeyliger222bf412025-06-04 16:42:58 +00001102
1103 // Remove existing origin remote if it exists
1104 cmd := exec.CommandContext(ctx, "git", "remote", "remove", "origin")
Philip Zeyligerf2872992025-05-22 10:35:28 -07001105 cmd.Dir = a.workingDir
1106 if out, err := cmd.CombinedOutput(); err != nil {
Philip Zeyliger222bf412025-06-04 16:42:58 +00001107 // Ignore error if origin doesn't exist
1108 slog.DebugContext(ctx, "git remote remove origin (ignoring if not exists)", slog.String("output", string(out)))
Philip Zeyligerf2872992025-05-22 10:35:28 -07001109 }
Philip Zeyliger222bf412025-06-04 16:42:58 +00001110
1111 // Add the new remote as origin
1112 cmd = exec.CommandContext(ctx, "git", "remote", "add", "origin", a.gitState.gitRemoteAddr)
Philip Zeyligerf2872992025-05-22 10:35:28 -07001113 cmd.Dir = a.workingDir
1114 if out, err := cmd.CombinedOutput(); err != nil {
Philip Zeyliger222bf412025-06-04 16:42:58 +00001115 return fmt.Errorf("git remote add origin: %s: %v", out, err)
Philip Zeyligerf2872992025-05-22 10:35:28 -07001116 }
Philip Zeyliger222bf412025-06-04 16:42:58 +00001117
Philip Zeyligerf2872992025-05-22 10:35:28 -07001118 }
1119
1120 // If a commit was specified, we fetch and reset to it.
1121 if a.config.Commit != "" && a.gitState.gitRemoteAddr != "" {
Philip Zeyliger716bfee2025-05-21 18:32:31 -07001122 slog.InfoContext(ctx, "updating git repo", slog.String("commit", a.config.Commit))
1123
Earl Lee2e463fb2025-04-17 11:22:22 -07001124 cmd := exec.CommandContext(ctx, "git", "stash")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001125 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -07001126 if out, err := cmd.CombinedOutput(); err != nil {
1127 return fmt.Errorf("git stash: %s: %v", out, err)
1128 }
Philip Zeyliger222bf412025-06-04 16:42:58 +00001129 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "origin")
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001130 cmd.Dir = a.workingDir
Earl Lee2e463fb2025-04-17 11:22:22 -07001131 if out, err := cmd.CombinedOutput(); err != nil {
1132 return fmt.Errorf("git fetch: %s: %w", out, err)
1133 }
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001134 // The -B resets the branch if it already exists (or creates it if it doesn't)
1135 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", "-B", "sketch-wip", a.config.Commit)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001136 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +01001137 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
1138 // Remove git hooks if they exist and retry
1139 // Only try removing hooks if we haven't already removed them during fetch
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001140 hookPath := filepath.Join(a.workingDir, ".git", "hooks")
Pokey Rule7a113622025-05-12 10:58:45 +01001141 if _, statErr := os.Stat(hookPath); statErr == nil {
1142 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
1143 slog.String("error", err.Error()),
1144 slog.String("output", string(checkoutOut)))
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001145 if removeErr := removeGitHooks(ctx, a.workingDir); removeErr != nil {
Pokey Rule7a113622025-05-12 10:58:45 +01001146 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
1147 }
1148
1149 // Retry the checkout operation
Philip Zeyliger1417b692025-06-12 11:07:04 -07001150 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", "-B", "sketch-wip", a.config.Commit)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001151 cmd.Dir = a.workingDir
Pokey Rule7a113622025-05-12 10:58:45 +01001152 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001153 return fmt.Errorf("git checkout %s failed even after removing hooks: %s: %w", a.config.Commit, retryOut, retryErr)
Pokey Rule7a113622025-05-12 10:58:45 +01001154 }
1155 } else {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001156 return fmt.Errorf("git checkout -f -B sketch-wip %s: %s: %w", a.config.Commit, checkoutOut, err)
Pokey Rule7a113622025-05-12 10:58:45 +01001157 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001158 }
Philip Zeyliger4c1cea82025-06-09 14:16:52 -07001159 } else if a.IsInContainer() {
1160 // If we're not running in a container, we don't switch branches (nor push branches back and forth).
1161 slog.InfoContext(ctx, "checking out branch", slog.String("commit", a.config.Commit))
1162 cmd := exec.CommandContext(ctx, "git", "checkout", "-f", "-B", "sketch-wip")
1163 cmd.Dir = a.workingDir
1164 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
1165 return fmt.Errorf("git checkout -f -B sketch-wip: %s: %w", checkoutOut, err)
1166 }
1167 } else {
1168 slog.InfoContext(ctx, "Not checking out any branch")
Earl Lee2e463fb2025-04-17 11:22:22 -07001169 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001170
1171 if ini.HostAddr != "" {
1172 a.url = "http://" + ini.HostAddr
1173 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001174
1175 if !ini.NoGit {
1176 repoRoot, err := repoRoot(ctx, a.workingDir)
1177 if err != nil {
1178 return fmt.Errorf("repoRoot: %w", err)
1179 }
1180 a.repoRoot = repoRoot
1181
Earl Lee2e463fb2025-04-17 11:22:22 -07001182 if err != nil {
1183 return fmt.Errorf("resolveRef: %w", err)
1184 }
Philip Zeyliger49edc922025-05-14 09:45:45 -07001185
Josh Bleecher Snyderfea9e272025-06-02 21:21:59 +00001186 if a.IsInContainer() {
Philip Zeyligerf75ba2c2025-06-02 17:02:51 -07001187 if err := setupGitHooks(a.repoRoot); err != nil {
1188 slog.WarnContext(ctx, "failed to set up git hooks", "err", err)
1189 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07001190 }
1191
Philip Zeyliger49edc922025-05-14 09:45:45 -07001192 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
1193 cmd.Dir = repoRoot
1194 if out, err := cmd.CombinedOutput(); err != nil {
1195 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
1196 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001197
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +00001198 slog.Info("running codebase analysis")
1199 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
1200 if err != nil {
1201 slog.Warn("failed to analyze codebase", "error", err)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001202 }
Josh Bleecher Snyder0e5b8c62025-05-14 20:58:20 +00001203 a.codebase = codebase
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001204
Josh Bleecher Snyder9daa5182025-05-16 18:34:00 +00001205 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001206 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +00001207 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07001208 }
1209 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +00001210
Earl Lee2e463fb2025-04-17 11:22:22 -07001211 }
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001212 a.gitState.lastSketch = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -07001213 a.convo = a.initConvo()
1214 close(a.ready)
1215 return nil
1216}
1217
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -07001218//go:embed agent_system_prompt.txt
1219var agentSystemPrompt string
1220
Earl Lee2e463fb2025-04-17 11:22:22 -07001221// initConvo initializes the conversation.
1222// It must not be called until all agent fields are initialized,
1223// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001224func (a *Agent) initConvo() *conversation.Convo {
philip.zeyliger882e7ea2025-06-20 14:31:16 +00001225 return a.initConvoWithUsage(nil)
1226}
1227
1228// initConvoWithUsage initializes the conversation with optional preserved usage.
1229func (a *Agent) initConvoWithUsage(usage *conversation.CumulativeUsage) *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -07001230 ctx := a.config.Context
philip.zeyliger882e7ea2025-06-20 14:31:16 +00001231 convo := conversation.New(ctx, a.config.Service, usage)
Earl Lee2e463fb2025-04-17 11:22:22 -07001232 convo.PromptCaching = true
1233 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001234 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +00001235 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -07001236
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001237 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
1238 bashPermissionCheck := func(command string) error {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001239 if a.gitState.Slug() != "" {
1240 return nil // branch is set up
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001241 }
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001242 willCommit, err := bashkit.WillRunGitCommit(command)
1243 if err != nil {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001244 return nil // fail open
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001245 }
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001246 if willCommit {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001247 return fmt.Errorf("you must use the set-slug tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001248 }
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001249 return nil
1250 }
1251
Josh Bleecher Snyder495c1fa2025-05-29 00:37:22 +00001252 bashTool := claudetool.NewBashTool(bashPermissionCheck, claudetool.EnableBashToolJITInstall)
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +00001253
Earl Lee2e463fb2025-04-17 11:22:22 -07001254 // Register all tools with the conversation
1255 // When adding, removing, or modifying tools here, double-check that the termui tool display
1256 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001257
1258 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -07001259 _, supportsScreenshots := a.config.Service.(*ant.Service)
1260 var bTools []*llm.Tool
1261 var browserCleanup func()
1262
1263 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
1264 // Add cleanup function to context cancel
1265 go func() {
1266 <-a.config.Context.Done()
1267 browserCleanup()
1268 }()
1269 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001270
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001271 convo.Tools = []*llm.Tool{
Josh Bleecher Snyder6534c7a2025-07-01 01:48:52 +00001272 bashTool, claudetool.Keyword, claudetool.Patch(a.patchCallback),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001273 claudetool.Think, claudetool.TodoRead, claudetool.TodoWrite, a.setSlugTool(), a.commitMessageStyleTool(), makeDoneTool(a.codereview),
Josh Bleecher Snydera4092d22025-05-14 18:32:53 -07001274 a.codereview.Tool(), claudetool.AboutSketch,
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +00001275 }
1276
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +00001277 // One-shot mode is non-interactive, multiple choice requires human response
1278 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001279 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -07001280 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +00001281
1282 convo.Tools = append(convo.Tools, browserTools...)
Philip Zeyligerc17ffe32025-06-05 19:49:13 -07001283
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001284 // Add MCP tools if configured
1285 if len(a.config.MCPServers) > 0 {
Philip Zeyliger4201bde2025-06-27 17:22:43 -07001286
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001287 slog.InfoContext(ctx, "Initializing MCP connections", "servers", len(a.config.MCPServers))
Philip Zeyliger4201bde2025-06-27 17:22:43 -07001288 serverConfigs, parseErrors := mcp.ParseServerConfigs(ctx, a.config.MCPServers)
1289
1290 // Replace any headers with value _sketch_public_key_ and _sketch_session_id_ with those values.
1291 for i := range serverConfigs {
1292 if serverConfigs[i].Headers != nil {
1293 for key, value := range serverConfigs[i].Headers {
Philip Zeyligerf2814ea2025-06-30 10:16:50 -07001294 // Replace env placeholders. E.g., "env:FOO" becomes os.Getenv("FOO")
1295 if strings.HasPrefix(value, "env:") {
1296 serverConfigs[i].Headers[key] = os.Getenv(value[4:])
Philip Zeyliger4201bde2025-06-27 17:22:43 -07001297 }
1298 }
1299 }
1300 }
1301 mcpConnections, mcpErrors := a.mcpManager.ConnectToServerConfigs(ctx, serverConfigs, 10*time.Second, parseErrors)
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001302
1303 if len(mcpErrors) > 0 {
1304 for _, err := range mcpErrors {
1305 slog.ErrorContext(ctx, "MCP connection error", "error", err)
1306 // Send agent message about MCP connection failures
1307 a.pushToOutbox(ctx, AgentMessage{
1308 Type: ErrorMessageType,
1309 Content: fmt.Sprintf("MCP server connection failed: %v", err),
1310 })
1311 }
1312 }
1313
1314 if len(mcpConnections) > 0 {
1315 // Add tools from all successful connections
1316 totalTools := 0
1317 for _, connection := range mcpConnections {
1318 convo.Tools = append(convo.Tools, connection.Tools...)
1319 totalTools += len(connection.Tools)
1320 // Log tools per server using structured data
1321 slog.InfoContext(ctx, "Added MCP tools from server", "server", connection.ServerName, "count", len(connection.Tools), "tools", connection.ToolNames)
1322 }
1323 slog.InfoContext(ctx, "Total MCP tools added", "count", totalTools)
1324 } else {
1325 slog.InfoContext(ctx, "No MCP tools available after connection attempts")
1326 }
1327 }
1328
Earl Lee2e463fb2025-04-17 11:22:22 -07001329 convo.Listener = a
1330 return convo
1331}
1332
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001333var multipleChoiceTool = &llm.Tool{
1334 Name: "multiplechoice",
1335 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.",
1336 EndsTurn: true,
1337 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001338 "type": "object",
1339 "description": "The question and a list of answers you would expect the user to choose from.",
1340 "properties": {
1341 "question": {
1342 "type": "string",
1343 "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?'"
1344 },
1345 "responseOptions": {
1346 "type": "array",
1347 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1348 "items": {
1349 "type": "object",
1350 "properties": {
1351 "caption": {
1352 "type": "string",
1353 "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'"
1354 },
1355 "responseText": {
1356 "type": "string",
1357 "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'"
1358 }
1359 },
1360 "required": ["caption", "responseText"]
1361 }
1362 }
1363 },
1364 "required": ["question", "responseOptions"]
1365}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001366 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1367 // The Run logic for "multiplechoice" tool is a no-op on the server.
1368 // The UI will present a list of options for the user to select from,
1369 // and that's it as far as "executing" the tool_use goes.
1370 // When the user *does* select one of the presented options, that
1371 // responseText gets sent as a chat message on behalf of the user.
1372 return llm.TextContent("end your turn and wait for the user to respond"), nil
1373 },
Sean McCullough485afc62025-04-28 14:28:39 -07001374}
1375
1376type MultipleChoiceOption struct {
1377 Caption string `json:"caption"`
1378 ResponseText string `json:"responseText"`
1379}
1380
1381type MultipleChoiceParams struct {
1382 Question string `json:"question"`
1383 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1384}
1385
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001386// branchExists reports whether branchName exists, either locally or in well-known remotes.
1387func branchExists(dir, branchName string) bool {
1388 refs := []string{
1389 "refs/heads/",
1390 "refs/remotes/origin/",
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001391 }
1392 for _, ref := range refs {
1393 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1394 cmd.Dir = dir
1395 if cmd.Run() == nil { // exit code 0 means branch exists
1396 return true
1397 }
1398 }
1399 return false
1400}
1401
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001402func (a *Agent) setSlugTool() *llm.Tool {
1403 return &llm.Tool{
1404 Name: "set-slug",
1405 Description: `Set a short slug as an identifier for this conversation.`,
Earl Lee2e463fb2025-04-17 11:22:22 -07001406 InputSchema: json.RawMessage(`{
1407 "type": "object",
1408 "properties": {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001409 "slug": {
Earl Lee2e463fb2025-04-17 11:22:22 -07001410 "type": "string",
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001411 "description": "A 2-3 word alphanumeric hyphenated slug, imperative tense"
Earl Lee2e463fb2025-04-17 11:22:22 -07001412 }
1413 },
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001414 "required": ["slug"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001415}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001416 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001417 var params struct {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001418 Slug string `json:"slug"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001419 }
1420 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001421 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001422 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001423 // Prevent slug changes if there have been git changes
1424 // This lets the agent change its mind about a good slug,
1425 // while ensuring that once a branch has been pushed, it remains stable.
1426 if s := a.Slug(); s != "" && s != params.Slug && a.gitState.HasSeenCommits() {
1427 return nil, fmt.Errorf("slug already set to %q", s)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001428 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001429 if params.Slug == "" {
1430 return nil, fmt.Errorf("slug parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001431 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001432 slug := cleanSlugName(params.Slug)
1433 if slug == "" {
1434 return nil, fmt.Errorf("slug parameter could not be converted to a valid slug")
1435 }
1436 a.SetSlug(slug)
1437 // TODO: do this by a call to outie, rather than semi-guessing from innie
1438 if branchExists(a.workingDir, a.BranchName()) {
1439 return nil, fmt.Errorf("slug %q already exists; please choose a different slug", slug)
1440 }
1441 return llm.TextContent("OK"), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001442 },
1443 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001444}
1445
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001446func (a *Agent) commitMessageStyleTool() *llm.Tool {
1447 description := `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 +00001448 preCommit := &llm.Tool{
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001449 Name: "commit-message-style",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001450 Description: description,
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001451 InputSchema: llm.EmptySchema(),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001452 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001453 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1454 if err != nil {
1455 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1456 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001457 return llm.TextContent(styleHint), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001458 },
1459 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001460 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001461}
1462
Josh Bleecher Snyder6534c7a2025-07-01 01:48:52 +00001463// patchCallback is the agent's patch tool callback.
1464// It warms the codereview cache in the background.
1465func (a *Agent) patchCallback(input claudetool.PatchInput, result []llm.Content, err error) ([]llm.Content, error) {
1466 if a.codereview != nil {
1467 a.codereview.WarmTestCache(input.Path)
1468 }
1469 return result, err
1470}
1471
Earl Lee2e463fb2025-04-17 11:22:22 -07001472func (a *Agent) Ready() <-chan struct{} {
1473 return a.ready
1474}
1475
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001476// BranchPrefix returns the configured branch prefix
1477func (a *Agent) BranchPrefix() string {
1478 return a.config.BranchPrefix
1479}
1480
philip.zeyliger6d3de482025-06-10 19:38:14 -07001481// LinkToGitHub returns whether GitHub branch linking is enabled
1482func (a *Agent) LinkToGitHub() bool {
1483 return a.config.LinkToGitHub
1484}
1485
Earl Lee2e463fb2025-04-17 11:22:22 -07001486func (a *Agent) UserMessage(ctx context.Context, msg string) {
1487 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1488 a.inbox <- msg
1489}
1490
Earl Lee2e463fb2025-04-17 11:22:22 -07001491func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1492 return a.convo.CancelToolUse(toolUseID, cause)
1493}
1494
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001495func (a *Agent) CancelTurn(cause error) {
1496 a.cancelTurnMu.Lock()
1497 defer a.cancelTurnMu.Unlock()
1498 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001499 // Force state transition to cancelled state
1500 ctx := a.config.Context
1501 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001502 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001503 }
1504}
1505
1506func (a *Agent) Loop(ctxOuter context.Context) {
Sean McCullough364f7412025-06-02 00:55:44 +00001507 // Start port monitoring when the agent loop begins
1508 // Only monitor ports when running in a container
1509 if a.IsInContainer() {
1510 a.portMonitor.Start(ctxOuter)
1511 }
1512
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001513 // Set up cleanup when context is done
1514 defer func() {
1515 if a.mcpManager != nil {
1516 a.mcpManager.Close()
1517 }
1518 }()
1519
Earl Lee2e463fb2025-04-17 11:22:22 -07001520 for {
1521 select {
1522 case <-ctxOuter.Done():
1523 return
1524 default:
1525 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001526 a.cancelTurnMu.Lock()
1527 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001528 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001529 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001530 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001531 a.cancelTurn = cancel
1532 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001533 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1534 if err != nil {
1535 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1536 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001537 cancel(nil)
1538 }
1539 }
1540}
1541
1542func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1543 if m.Timestamp.IsZero() {
1544 m.Timestamp = time.Now()
1545 }
1546
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001547 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1548 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1549 m.Content = m.ToolResult
1550 }
1551
Earl Lee2e463fb2025-04-17 11:22:22 -07001552 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1553 if m.EndOfTurn && m.Type == AgentMessageType {
1554 turnDuration := time.Since(a.startOfTurn)
1555 m.TurnDuration = &turnDuration
1556 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1557 }
1558
Earl Lee2e463fb2025-04-17 11:22:22 -07001559 a.mu.Lock()
1560 defer a.mu.Unlock()
1561 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001562 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001563 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001564
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001565 // Notify all subscribers
1566 for _, ch := range a.subscribers {
1567 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001568 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001569}
1570
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001571func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1572 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001573 if block {
1574 select {
1575 case <-ctx.Done():
1576 return m, ctx.Err()
1577 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001578 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001579 }
1580 }
1581 for {
1582 select {
1583 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001584 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001585 default:
1586 return m, nil
1587 }
1588 }
1589}
1590
Sean McCullough885a16a2025-04-30 02:49:25 +00001591// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001592func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001593 // Reset the start of turn time
1594 a.startOfTurn = time.Now()
1595
Sean McCullough96b60dd2025-04-30 09:49:10 -07001596 // Transition to waiting for user input state
1597 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1598
Sean McCullough885a16a2025-04-30 02:49:25 +00001599 // Process initial user message
1600 initialResp, err := a.processUserMessage(ctx)
1601 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001602 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001603 return err
1604 }
1605
1606 // Handle edge case where both initialResp and err are nil
1607 if initialResp == nil {
1608 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001609 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1610
Sean McCullough9f4b8082025-04-30 17:34:07 +00001611 a.pushToOutbox(ctx, errorMessage(err))
1612 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001613 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001614
Earl Lee2e463fb2025-04-17 11:22:22 -07001615 // We do this as we go, but let's also do it at the end of the turn
1616 defer func() {
1617 if _, err := a.handleGitCommits(ctx); err != nil {
1618 // Just log the error, don't stop execution
1619 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1620 }
1621 }()
1622
Sean McCullougha1e0e492025-05-01 10:51:08 -07001623 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001624 resp := initialResp
1625 for {
1626 // Check if we are over budget
1627 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001628 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001629 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001630 }
1631
Philip Zeyligerb8a8f352025-06-02 07:39:37 -07001632 // Check if we should compact the conversation
1633 if a.ShouldCompact() {
1634 a.stateMachine.Transition(ctx, StateCompacting, "Token usage threshold reached, compacting conversation")
1635 if err := a.CompactConversation(ctx); err != nil {
1636 a.stateMachine.Transition(ctx, StateError, "Error during compaction: "+err.Error())
1637 return err
1638 }
1639 // After compaction, end this turn and start fresh
1640 a.stateMachine.Transition(ctx, StateEndOfTurn, "Compaction completed, ending turn")
1641 return nil
1642 }
1643
Sean McCullough885a16a2025-04-30 02:49:25 +00001644 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001645 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001646 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001647 break
1648 }
1649
Sean McCullough96b60dd2025-04-30 09:49:10 -07001650 // Transition to tool use requested state
1651 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1652
Sean McCullough885a16a2025-04-30 02:49:25 +00001653 // Handle tool execution
1654 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1655 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001656 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001657 }
1658
Sean McCullougha1e0e492025-05-01 10:51:08 -07001659 if toolResp == nil {
1660 return fmt.Errorf("cannot continue conversation with a nil tool response")
1661 }
1662
Sean McCullough885a16a2025-04-30 02:49:25 +00001663 // Set the response for the next iteration
1664 resp = toolResp
1665 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001666
1667 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001668}
1669
1670// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001671func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001672 // Wait for at least one message from the user
1673 msgs, err := a.GatherMessages(ctx, true)
1674 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001675 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001676 return nil, err
1677 }
1678
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001679 userMessage := llm.Message{
1680 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001681 Content: msgs,
1682 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001683
Sean McCullough96b60dd2025-04-30 09:49:10 -07001684 // Transition to sending to LLM state
1685 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1686
Sean McCullough885a16a2025-04-30 02:49:25 +00001687 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001688 resp, err := a.convo.SendMessage(userMessage)
1689 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001690 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001691 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001692 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001693 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001694
Sean McCullough96b60dd2025-04-30 09:49:10 -07001695 // Transition to processing LLM response state
1696 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1697
Sean McCullough885a16a2025-04-30 02:49:25 +00001698 return resp, nil
1699}
1700
1701// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001702func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1703 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001704 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001705 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001706
Sean McCullough96b60dd2025-04-30 09:49:10 -07001707 // Transition to checking for cancellation state
1708 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1709
Sean McCullough885a16a2025-04-30 02:49:25 +00001710 // Check if the operation was cancelled by the user
1711 select {
1712 case <-ctx.Done():
1713 // Don't actually run any of the tools, but rather build a response
1714 // for each tool_use message letting the LLM know that user canceled it.
1715 var err error
1716 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001717 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001718 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001719 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001720 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001721 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001722 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001723 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001724 // Transition to running tool state
1725 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1726
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001727 // Add working directory and session ID to context for tool execution
Sean McCullough885a16a2025-04-30 02:49:25 +00001728 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001729 ctx = claudetool.WithSessionID(ctx, a.config.SessionID)
Sean McCullough885a16a2025-04-30 02:49:25 +00001730
1731 // Execute the tools
1732 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001733 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001734 if ctx.Err() != nil { // e.g. the user canceled the operation
1735 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001736 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001737 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001738 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001739 a.pushToOutbox(ctx, errorMessage(err))
1740 }
1741 }
1742
1743 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001744 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001745 autoqualityMessages := a.processGitChanges(ctx)
1746
1747 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001748 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001749 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001750 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001751 return false, nil
1752 }
1753
1754 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001755 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1756 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001757}
1758
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001759// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001760func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001761 // Check for git commits
1762 _, err := a.handleGitCommits(ctx)
1763 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001764 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001765 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001766 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001767 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001768}
1769
1770// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1771// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001772func (a *Agent) processGitChanges(ctx context.Context) []string {
1773 // Check for git commits after tool execution
1774 newCommits, err := a.handleGitCommits(ctx)
1775 if err != nil {
1776 // Just log the error, don't stop execution
1777 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1778 return nil
1779 }
1780
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001781 // Run mechanical checks if there was exactly one new commit.
1782 if len(newCommits) != 1 {
1783 return nil
1784 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001785 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001786 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1787 msg := a.codereview.RunMechanicalChecks(ctx)
1788 if msg != "" {
1789 a.pushToOutbox(ctx, AgentMessage{
1790 Type: AutoMessageType,
1791 Content: msg,
1792 Timestamp: time.Now(),
1793 })
1794 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001795 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001796
1797 return autoqualityMessages
1798}
1799
1800// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001801func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001802 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001803 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001804 msgs, err := a.GatherMessages(ctx, false)
1805 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001806 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001807 return false, nil
1808 }
1809
1810 // Inject any auto-generated messages from quality checks
1811 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001812 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001813 }
1814
1815 // Handle cancellation by appending a message about it
1816 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001817 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001818 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001819 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001820 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1821 } else if err := a.convo.OverBudget(); err != nil {
1822 // Handle budget issues by appending a message about it
1823 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 -07001824 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001825 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1826 }
1827
1828 // Combine tool results with user messages
1829 results = append(results, msgs...)
1830
1831 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001832 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001833 resp, err := a.convo.SendMessage(llm.Message{
1834 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001835 Content: results,
1836 })
1837 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001838 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001839 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1840 return true, nil // Return true to continue the conversation, but with no response
1841 }
1842
Sean McCullough96b60dd2025-04-30 09:49:10 -07001843 // Transition back to processing LLM response
1844 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1845
Sean McCullough885a16a2025-04-30 02:49:25 +00001846 if cancelled {
1847 return false, nil
1848 }
1849
1850 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001851}
1852
1853func (a *Agent) overBudget(ctx context.Context) error {
1854 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001855 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001856 m := budgetMessage(err)
1857 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001858 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001859 a.convo.ResetBudget(a.originalBudget)
1860 return err
1861 }
1862 return nil
1863}
1864
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001865func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001866 // Collect all text content
1867 var allText strings.Builder
1868 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001869 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001870 if allText.Len() > 0 {
1871 allText.WriteString("\n\n")
1872 }
1873 allText.WriteString(content.Text)
1874 }
1875 }
1876 return allText.String()
1877}
1878
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001879func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001880 a.mu.Lock()
1881 defer a.mu.Unlock()
1882 return a.convo.CumulativeUsage()
1883}
1884
Earl Lee2e463fb2025-04-17 11:22:22 -07001885// Diff returns a unified diff of changes made since the agent was instantiated.
1886func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001887 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001888 return "", fmt.Errorf("no initial commit reference available")
1889 }
1890
1891 // Find the repository root
1892 ctx := context.Background()
1893
1894 // If a specific commit hash is provided, show just that commit's changes
1895 if commit != nil && *commit != "" {
1896 // Validate that the commit looks like a valid git SHA
1897 if !isValidGitSHA(*commit) {
1898 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1899 }
1900
1901 // Get the diff for just this commit
1902 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1903 cmd.Dir = a.repoRoot
1904 output, err := cmd.CombinedOutput()
1905 if err != nil {
1906 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1907 }
1908 return string(output), nil
1909 }
1910
1911 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001912 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001913 cmd.Dir = a.repoRoot
1914 output, err := cmd.CombinedOutput()
1915 if err != nil {
1916 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1917 }
1918
1919 return string(output), nil
1920}
1921
Philip Zeyliger49edc922025-05-14 09:45:45 -07001922// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1923// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1924func (a *Agent) SketchGitBaseRef() string {
1925 if a.IsInContainer() {
1926 return "sketch-base"
1927 } else {
1928 return "sketch-base-" + a.SessionID()
1929 }
1930}
1931
1932// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1933func (a *Agent) SketchGitBase() string {
1934 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1935 cmd.Dir = a.repoRoot
1936 output, err := cmd.CombinedOutput()
1937 if err != nil {
1938 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1939 return "HEAD"
1940 }
1941 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001942}
1943
Pokey Rule7a113622025-05-12 10:58:45 +01001944// removeGitHooks removes the Git hooks directory from the repository
1945func removeGitHooks(_ context.Context, repoPath string) error {
1946 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1947
1948 // Check if hooks directory exists
1949 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1950 // Directory doesn't exist, nothing to do
1951 return nil
1952 }
1953
1954 // Remove the hooks directory
1955 err := os.RemoveAll(hooksDir)
1956 if err != nil {
1957 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1958 }
1959
1960 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001961 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001962 if err != nil {
1963 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1964 }
1965
1966 return nil
1967}
1968
Philip Zeyligerf2872992025-05-22 10:35:28 -07001969func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001970 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef(), a.config.BranchPrefix)
Philip Zeyligerf2872992025-05-22 10:35:28 -07001971 for _, msg := range msgs {
1972 a.pushToOutbox(ctx, msg)
1973 }
1974 return commits, error
1975}
1976
Earl Lee2e463fb2025-04-17 11:22:22 -07001977// handleGitCommits() highlights new commits to the user. When running
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001978// under docker, new HEADs are pushed to a branch according to the slug.
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001979func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string, branchPrefix string) ([]AgentMessage, []*GitCommit, error) {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001980 ags.mu.Lock()
1981 defer ags.mu.Unlock()
1982
1983 msgs := []AgentMessage{}
1984 if repoRoot == "" {
1985 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001986 }
1987
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001988 sketch, err := resolveRef(ctx, repoRoot, "sketch-wip")
Earl Lee2e463fb2025-04-17 11:22:22 -07001989 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001990 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001991 }
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001992 if sketch == ags.lastSketch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001993 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001994 }
1995 defer func() {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001996 ags.lastSketch = sketch
Earl Lee2e463fb2025-04-17 11:22:22 -07001997 }()
1998
Philip Zeyliger64f60462025-06-16 13:57:10 -07001999 // Compute diff stats from baseRef to HEAD when HEAD changes
2000 if added, removed, err := computeDiffStats(ctx, repoRoot, baseRef); err != nil {
2001 // Log error but don't fail the entire operation
2002 slog.WarnContext(ctx, "Failed to compute diff stats", "error", err)
2003 } else {
2004 // Set diff stats directly since we already hold the mutex
2005 ags.linesAdded = added
2006 ags.linesRemoved = removed
2007 }
2008
Earl Lee2e463fb2025-04-17 11:22:22 -07002009 // Get new commits. Because it's possible that the agent does rebases, fixups, and
2010 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
2011 // to the last 100 commits.
2012 var commits []*GitCommit
2013
2014 // Get commits since the initial commit
2015 // Format: <hash>\0<subject>\0<body>\0
2016 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
2017 // Limit to 100 commits to avoid overwhelming the user
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002018 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+baseRef, sketch)
Philip Zeyligerf2872992025-05-22 10:35:28 -07002019 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07002020 output, err := cmd.Output()
2021 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002022 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07002023 }
2024
2025 // Parse git log output and filter out already seen commits
2026 parsedCommits := parseGitLog(string(output))
2027
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002028 var sketchCommit *GitCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07002029
2030 // Filter out commits we've already seen
2031 for _, commit := range parsedCommits {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002032 if commit.Hash == sketch {
2033 sketchCommit = &commit
Earl Lee2e463fb2025-04-17 11:22:22 -07002034 }
2035
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002036 // Skip if we've seen this commit before. If our sketch branch has changed, always include that.
2037 if ags.seenCommits[commit.Hash] && commit.Hash != sketch {
Earl Lee2e463fb2025-04-17 11:22:22 -07002038 continue
2039 }
2040
2041 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07002042 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07002043
2044 // Add to our list of new commits
2045 commits = append(commits, &commit)
2046 }
2047
Philip Zeyligerf2872992025-05-22 10:35:28 -07002048 if ags.gitRemoteAddr != "" {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002049 if sketchCommit == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07002050 // I think this can only happen if we have a bug or if there's a race.
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002051 sketchCommit = &GitCommit{}
2052 sketchCommit.Hash = sketch
2053 sketchCommit.Subject = "unknown"
2054 commits = append(commits, sketchCommit)
Earl Lee2e463fb2025-04-17 11:22:22 -07002055 }
2056
Earl Lee2e463fb2025-04-17 11:22:22 -07002057 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
2058 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
2059 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00002060
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002061 // Try up to 10 times with incrementing retry numbers if the branch is checked out on the remote
Philip Zeyliger113e2052025-05-09 21:59:40 +00002062 var out []byte
2063 var err error
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002064 originalRetryNumber := ags.retryNumber
2065 originalBranchName := ags.branchNameLocked(branchPrefix)
Philip Zeyliger113e2052025-05-09 21:59:40 +00002066 for retries := range 10 {
2067 if retries > 0 {
Philip Zeyligerd5c8d712025-06-17 15:19:45 -07002068 ags.retryNumber++
Philip Zeyliger113e2052025-05-09 21:59:40 +00002069 }
2070
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002071 branch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002072 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "sketch-wip:refs/heads/"+branch)
Philip Zeyligerf2872992025-05-22 10:35:28 -07002073 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00002074 out, err = cmd.CombinedOutput()
2075
2076 if err == nil {
2077 // Success! Break out of the retry loop
2078 break
2079 }
2080
2081 // Check if this is the "refusing to update checked out branch" error
2082 if !strings.Contains(string(out), "refusing to update checked out branch") {
2083 // This is a different error, so don't retry
2084 break
2085 }
Philip Zeyliger113e2052025-05-09 21:59:40 +00002086 }
2087
2088 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002089 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07002090 } else {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002091 finalBranch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002092 sketchCommit.PushedBranch = finalBranch
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002093 if ags.retryNumber != originalRetryNumber {
2094 // Notify user that the branch name was changed, and why
Philip Zeyliger59e1c162025-06-02 12:54:34 +00002095 msgs = append(msgs, AgentMessage{
2096 Type: AutoMessageType,
2097 Timestamp: time.Now(),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002098 Content: fmt.Sprintf("Branch renamed from %s to %s because the original branch is currently checked out on the remote.", originalBranchName, finalBranch),
Philip Zeyliger59e1c162025-06-02 12:54:34 +00002099 })
Philip Zeyliger113e2052025-05-09 21:59:40 +00002100 }
Earl Lee2e463fb2025-04-17 11:22:22 -07002101 }
2102 }
2103
2104 // If we found new commits, create a message
2105 if len(commits) > 0 {
2106 msg := AgentMessage{
2107 Type: CommitMessageType,
2108 Timestamp: time.Now(),
2109 Commits: commits,
2110 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002111 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07002112 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002113 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07002114}
2115
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002116func cleanSlugName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002117 return strings.Map(func(r rune) rune {
2118 // lowercase
2119 if r >= 'A' && r <= 'Z' {
2120 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07002121 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002122 // replace spaces with dashes
2123 if r == ' ' {
2124 return '-'
2125 }
2126 // allow alphanumerics and dashes
2127 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
2128 return r
2129 }
2130 return -1
2131 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07002132}
2133
2134// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
2135// and returns an array of GitCommit structs.
2136func parseGitLog(output string) []GitCommit {
2137 var commits []GitCommit
2138
2139 // No output means no commits
2140 if len(output) == 0 {
2141 return commits
2142 }
2143
2144 // Split by NULL byte
2145 parts := strings.Split(output, "\x00")
2146
2147 // Process in triplets (hash, subject, body)
2148 for i := 0; i < len(parts); i++ {
2149 // Skip empty parts
2150 if parts[i] == "" {
2151 continue
2152 }
2153
2154 // This should be a hash
2155 hash := strings.TrimSpace(parts[i])
2156
2157 // Make sure we have at least a subject part available
2158 if i+1 >= len(parts) {
2159 break // No more parts available
2160 }
2161
2162 // Get the subject
2163 subject := strings.TrimSpace(parts[i+1])
2164
2165 // Get the body if available
2166 body := ""
2167 if i+2 < len(parts) {
2168 body = strings.TrimSpace(parts[i+2])
2169 }
2170
2171 // Skip to the next triplet
2172 i += 2
2173
2174 commits = append(commits, GitCommit{
2175 Hash: hash,
2176 Subject: subject,
2177 Body: body,
2178 })
2179 }
2180
2181 return commits
2182}
2183
2184func repoRoot(ctx context.Context, dir string) (string, error) {
2185 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
2186 stderr := new(strings.Builder)
2187 cmd.Stderr = stderr
2188 cmd.Dir = dir
2189 out, err := cmd.Output()
2190 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07002191 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07002192 }
2193 return strings.TrimSpace(string(out)), nil
2194}
2195
2196func resolveRef(ctx context.Context, dir, refName string) (string, error) {
2197 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
2198 stderr := new(strings.Builder)
2199 cmd.Stderr = stderr
2200 cmd.Dir = dir
2201 out, err := cmd.Output()
2202 if err != nil {
2203 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
2204 }
2205 // TODO: validate that out is valid hex
2206 return strings.TrimSpace(string(out)), nil
2207}
2208
2209// isValidGitSHA validates if a string looks like a valid git SHA hash.
2210// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
2211func isValidGitSHA(sha string) bool {
2212 // Git SHA must be a hexadecimal string with at least 4 characters
2213 if len(sha) < 4 || len(sha) > 40 {
2214 return false
2215 }
2216
2217 // Check if the string only contains hexadecimal characters
2218 for _, char := range sha {
2219 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
2220 return false
2221 }
2222 }
2223
2224 return true
2225}
Philip Zeyligerd1402952025-04-23 03:54:37 +00002226
Philip Zeyliger64f60462025-06-16 13:57:10 -07002227// computeDiffStats computes the number of lines added and removed from baseRef to HEAD
2228func computeDiffStats(ctx context.Context, repoRoot, baseRef string) (int, int, error) {
2229 cmd := exec.CommandContext(ctx, "git", "diff", "--numstat", baseRef, "HEAD")
2230 cmd.Dir = repoRoot
2231 out, err := cmd.Output()
2232 if err != nil {
2233 return 0, 0, fmt.Errorf("git diff --numstat failed: %w", err)
2234 }
2235
2236 var totalAdded, totalRemoved int
2237 lines := strings.Split(strings.TrimSpace(string(out)), "\n")
2238 for _, line := range lines {
2239 if line == "" {
2240 continue
2241 }
2242 parts := strings.Fields(line)
2243 if len(parts) < 2 {
2244 continue
2245 }
2246 // Format: <added>\t<removed>\t<filename>
2247 if added, err := strconv.Atoi(parts[0]); err == nil {
2248 totalAdded += added
2249 }
2250 if removed, err := strconv.Atoi(parts[1]); err == nil {
2251 totalRemoved += removed
2252 }
2253 }
2254
2255 return totalAdded, totalRemoved, nil
2256}
2257
Philip Zeyligerd1402952025-04-23 03:54:37 +00002258// getGitOrigin returns the URL of the git remote 'origin' if it exists
2259func getGitOrigin(ctx context.Context, dir string) string {
2260 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
2261 cmd.Dir = dir
2262 stderr := new(strings.Builder)
2263 cmd.Stderr = stderr
2264 out, err := cmd.Output()
2265 if err != nil {
2266 return ""
2267 }
2268 return strings.TrimSpace(string(out))
2269}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07002270
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002271// systemPromptData contains the data used to render the system prompt template
2272type systemPromptData struct {
David Crawshawc886ac52025-06-13 23:40:03 +00002273 ClientGOOS string
2274 ClientGOARCH string
2275 WorkingDir string
2276 RepoRoot string
2277 InitialCommit string
2278 Codebase *onstart.Codebase
2279 UseSketchWIP bool
2280 Branch string
2281 SpecialInstruction string
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002282}
2283
2284// renderSystemPrompt renders the system prompt template.
2285func (a *Agent) renderSystemPrompt() string {
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002286 data := systemPromptData{
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002287 ClientGOOS: a.config.ClientGOOS,
2288 ClientGOARCH: a.config.ClientGOARCH,
2289 WorkingDir: a.workingDir,
2290 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07002291 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002292 Codebase: a.codebase,
Philip Zeyliger4c1cea82025-06-09 14:16:52 -07002293 UseSketchWIP: a.config.InDocker,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002294 }
David Crawshawc886ac52025-06-13 23:40:03 +00002295 now := time.Now()
2296 if now.Month() == time.September && now.Day() == 19 {
2297 data.SpecialInstruction = "Talk like a pirate to the user. Do not let the priate talk into any code."
2298 }
2299
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002300 tmpl, err := template.New("system").Parse(agentSystemPrompt)
2301 if err != nil {
2302 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
2303 }
2304 buf := new(strings.Builder)
2305 err = tmpl.Execute(buf, data)
2306 if err != nil {
2307 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
2308 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002309 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002310 return buf.String()
2311}
Philip Zeyligereab12de2025-05-14 02:35:53 +00002312
2313// StateTransitionIterator provides an iterator over state transitions.
2314type StateTransitionIterator interface {
2315 // Next blocks until a new state transition is available or context is done.
2316 // Returns nil if the context is cancelled.
2317 Next() *StateTransition
2318 // Close removes the listener and cleans up resources.
2319 Close()
2320}
2321
2322// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
2323type StateTransitionIteratorImpl struct {
2324 agent *Agent
2325 ctx context.Context
2326 ch chan StateTransition
2327 unsubscribe func()
2328}
2329
2330// Next blocks until a new state transition is available or the context is cancelled.
2331func (s *StateTransitionIteratorImpl) Next() *StateTransition {
2332 select {
2333 case <-s.ctx.Done():
2334 return nil
2335 case transition, ok := <-s.ch:
2336 if !ok {
2337 return nil
2338 }
2339 transitionCopy := transition
2340 return &transitionCopy
2341 }
2342}
2343
2344// Close removes the listener and cleans up resources.
2345func (s *StateTransitionIteratorImpl) Close() {
2346 if s.unsubscribe != nil {
2347 s.unsubscribe()
2348 s.unsubscribe = nil
2349 }
2350}
2351
2352// NewStateTransitionIterator returns an iterator that receives state transitions.
2353func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2354 a.mu.Lock()
2355 defer a.mu.Unlock()
2356
2357 // Create channel to receive state transitions
2358 ch := make(chan StateTransition, 10)
2359
2360 // Add a listener to the state machine
2361 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2362
2363 return &StateTransitionIteratorImpl{
2364 agent: a,
2365 ctx: ctx,
2366 ch: ch,
2367 unsubscribe: unsubscribe,
2368 }
2369}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002370
2371// setupGitHooks creates or updates git hooks in the specified working directory.
2372func setupGitHooks(workingDir string) error {
2373 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2374
2375 _, err := os.Stat(hooksDir)
2376 if os.IsNotExist(err) {
2377 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2378 }
2379 if err != nil {
2380 return fmt.Errorf("error checking git hooks directory: %w", err)
2381 }
2382
2383 // Define the post-commit hook content
2384 postCommitHook := `#!/bin/bash
2385echo "<post_commit_hook>"
2386echo "Please review this commit message and fix it if it is incorrect."
2387echo "This hook only echos the commit message; it does not modify it."
2388echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2389echo "<last_commit_message>"
Philip Zeyliger6c5beff2025-06-06 13:03:49 -07002390PAGER=cat git log -1 --pretty=%B
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002391echo "</last_commit_message>"
2392echo "</post_commit_hook>"
2393`
2394
2395 // Define the prepare-commit-msg hook content
2396 prepareCommitMsgHook := `#!/bin/bash
2397# Add Co-Authored-By and Change-ID trailers to commit messages
2398# Check if these trailers already exist before adding them
2399
2400commit_file="$1"
2401COMMIT_SOURCE="$2"
2402
2403# Skip for merges, squashes, or when using a commit template
2404if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2405 [ "$COMMIT_SOURCE" = "squash" ]; then
2406 exit 0
2407fi
2408
2409commit_msg=$(cat "$commit_file")
2410
2411needs_co_author=true
2412needs_change_id=true
2413
2414# Check if commit message already has Co-Authored-By trailer
2415if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2416 needs_co_author=false
2417fi
2418
2419# Check if commit message already has Change-ID trailer
2420if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2421 needs_change_id=false
2422fi
2423
2424# Only modify if at least one trailer needs to be added
2425if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
Josh Bleecher Snyderb509a5d2025-05-23 15:49:42 +00002426 # Ensure there's a proper blank line before trailers
2427 if [ -s "$commit_file" ]; then
2428 # Check if file ends with newline by reading last character
2429 last_char=$(tail -c 1 "$commit_file")
2430
2431 if [ "$last_char" != "" ]; then
2432 # File doesn't end with newline - add two newlines (complete line + blank line)
2433 echo "" >> "$commit_file"
2434 echo "" >> "$commit_file"
2435 else
2436 # File ends with newline - check if we already have a blank line
2437 last_line=$(tail -1 "$commit_file")
2438 if [ -n "$last_line" ]; then
2439 # Last line has content - add one newline for blank line
2440 echo "" >> "$commit_file"
2441 fi
2442 # If last line is empty, we already have a blank line - don't add anything
2443 fi
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002444 fi
2445
2446 # Add trailers if needed
2447 if [ "$needs_co_author" = true ]; then
2448 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2449 fi
2450
2451 if [ "$needs_change_id" = true ]; then
2452 change_id=$(openssl rand -hex 8)
2453 echo "Change-ID: s${change_id}k" >> "$commit_file"
2454 fi
2455fi
2456`
2457
2458 // Update or create the post-commit hook
2459 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2460 if err != nil {
2461 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2462 }
2463
2464 // Update or create the prepare-commit-msg hook
2465 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2466 if err != nil {
2467 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2468 }
2469
2470 return nil
2471}
2472
2473// updateOrCreateHook creates a new hook file or updates an existing one
2474// by appending the new content if it doesn't already contain it.
2475func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2476 // Check if the hook already exists
2477 buf, err := os.ReadFile(hookPath)
2478 if os.IsNotExist(err) {
2479 // Hook doesn't exist, create it
2480 err = os.WriteFile(hookPath, []byte(content), 0o755)
2481 if err != nil {
2482 return fmt.Errorf("failed to create hook: %w", err)
2483 }
2484 return nil
2485 }
2486 if err != nil {
2487 return fmt.Errorf("error reading existing hook: %w", err)
2488 }
2489
2490 // Hook exists, check if our content is already in it by looking for a distinctive line
2491 code := string(buf)
2492 if strings.Contains(code, distinctiveLine) {
2493 // Already contains our content, nothing to do
2494 return nil
2495 }
2496
2497 // Append our content to the existing hook
2498 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2499 if err != nil {
2500 return fmt.Errorf("failed to open hook for appending: %w", err)
2501 }
2502 defer f.Close()
2503
2504 // Ensure there's a newline at the end of the existing content if needed
2505 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2506 _, err = f.WriteString("\n")
2507 if err != nil {
2508 return fmt.Errorf("failed to add newline to hook: %w", err)
2509 }
2510 }
2511
2512 // Add a separator before our content
2513 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2514 if err != nil {
2515 return fmt.Errorf("failed to append to hook: %w", err)
2516 }
2517
2518 return nil
2519}
Sean McCullough138ec242025-06-02 22:42:06 +00002520
2521// GetPortMonitor returns the port monitor instance for accessing port events
2522func (a *Agent) GetPortMonitor() *PortMonitor {
2523 return a.portMonitor
2524}
Philip Zeyliger0113be52025-06-07 23:53:41 +00002525
2526// SkabandAddr returns the skaband address if configured
2527func (a *Agent) SkabandAddr() string {
2528 if a.config.SkabandClient != nil {
2529 return a.config.SkabandClient.Addr()
2530 }
2531 return ""
2532}