blob: 24f3a70e52866c7f2ba5c08800375139bc05fc03 [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 Snyderb421a242025-05-29 23:22:55 +00001272 bashTool, claudetool.Keyword, claudetool.Patch,
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
1284 // Add session history tools if skaband client is available
1285 if a.config.SkabandClient != nil {
1286 sessionHistoryTools := claudetool.CreateSessionHistoryTools(a.config.SkabandClient, a.config.SessionID, a.gitOrigin)
1287 convo.Tools = append(convo.Tools, sessionHistoryTools...)
1288 }
1289
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001290 // Add MCP tools if configured
1291 if len(a.config.MCPServers) > 0 {
1292 slog.InfoContext(ctx, "Initializing MCP connections", "servers", len(a.config.MCPServers))
1293 mcpConnections, mcpErrors := a.mcpManager.ConnectToServers(ctx, a.config.MCPServers, 10*time.Second)
1294
1295 if len(mcpErrors) > 0 {
1296 for _, err := range mcpErrors {
1297 slog.ErrorContext(ctx, "MCP connection error", "error", err)
1298 // Send agent message about MCP connection failures
1299 a.pushToOutbox(ctx, AgentMessage{
1300 Type: ErrorMessageType,
1301 Content: fmt.Sprintf("MCP server connection failed: %v", err),
1302 })
1303 }
1304 }
1305
1306 if len(mcpConnections) > 0 {
1307 // Add tools from all successful connections
1308 totalTools := 0
1309 for _, connection := range mcpConnections {
1310 convo.Tools = append(convo.Tools, connection.Tools...)
1311 totalTools += len(connection.Tools)
1312 // Log tools per server using structured data
1313 slog.InfoContext(ctx, "Added MCP tools from server", "server", connection.ServerName, "count", len(connection.Tools), "tools", connection.ToolNames)
1314 }
1315 slog.InfoContext(ctx, "Total MCP tools added", "count", totalTools)
1316 } else {
1317 slog.InfoContext(ctx, "No MCP tools available after connection attempts")
1318 }
1319 }
1320
Earl Lee2e463fb2025-04-17 11:22:22 -07001321 convo.Listener = a
1322 return convo
1323}
1324
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001325var multipleChoiceTool = &llm.Tool{
1326 Name: "multiplechoice",
1327 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.",
1328 EndsTurn: true,
1329 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001330 "type": "object",
1331 "description": "The question and a list of answers you would expect the user to choose from.",
1332 "properties": {
1333 "question": {
1334 "type": "string",
1335 "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?'"
1336 },
1337 "responseOptions": {
1338 "type": "array",
1339 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1340 "items": {
1341 "type": "object",
1342 "properties": {
1343 "caption": {
1344 "type": "string",
1345 "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'"
1346 },
1347 "responseText": {
1348 "type": "string",
1349 "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'"
1350 }
1351 },
1352 "required": ["caption", "responseText"]
1353 }
1354 }
1355 },
1356 "required": ["question", "responseOptions"]
1357}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001358 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1359 // The Run logic for "multiplechoice" tool is a no-op on the server.
1360 // The UI will present a list of options for the user to select from,
1361 // and that's it as far as "executing" the tool_use goes.
1362 // When the user *does* select one of the presented options, that
1363 // responseText gets sent as a chat message on behalf of the user.
1364 return llm.TextContent("end your turn and wait for the user to respond"), nil
1365 },
Sean McCullough485afc62025-04-28 14:28:39 -07001366}
1367
1368type MultipleChoiceOption struct {
1369 Caption string `json:"caption"`
1370 ResponseText string `json:"responseText"`
1371}
1372
1373type MultipleChoiceParams struct {
1374 Question string `json:"question"`
1375 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1376}
1377
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001378// branchExists reports whether branchName exists, either locally or in well-known remotes.
1379func branchExists(dir, branchName string) bool {
1380 refs := []string{
1381 "refs/heads/",
1382 "refs/remotes/origin/",
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001383 }
1384 for _, ref := range refs {
1385 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1386 cmd.Dir = dir
1387 if cmd.Run() == nil { // exit code 0 means branch exists
1388 return true
1389 }
1390 }
1391 return false
1392}
1393
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001394func (a *Agent) setSlugTool() *llm.Tool {
1395 return &llm.Tool{
1396 Name: "set-slug",
1397 Description: `Set a short slug as an identifier for this conversation.`,
Earl Lee2e463fb2025-04-17 11:22:22 -07001398 InputSchema: json.RawMessage(`{
1399 "type": "object",
1400 "properties": {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001401 "slug": {
Earl Lee2e463fb2025-04-17 11:22:22 -07001402 "type": "string",
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001403 "description": "A 2-3 word alphanumeric hyphenated slug, imperative tense"
Earl Lee2e463fb2025-04-17 11:22:22 -07001404 }
1405 },
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001406 "required": ["slug"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001407}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001408 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001409 var params struct {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001410 Slug string `json:"slug"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001411 }
1412 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001413 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001414 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001415 // Prevent slug changes if there have been git changes
1416 // This lets the agent change its mind about a good slug,
1417 // while ensuring that once a branch has been pushed, it remains stable.
1418 if s := a.Slug(); s != "" && s != params.Slug && a.gitState.HasSeenCommits() {
1419 return nil, fmt.Errorf("slug already set to %q", s)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001420 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001421 if params.Slug == "" {
1422 return nil, fmt.Errorf("slug parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001423 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001424 slug := cleanSlugName(params.Slug)
1425 if slug == "" {
1426 return nil, fmt.Errorf("slug parameter could not be converted to a valid slug")
1427 }
1428 a.SetSlug(slug)
1429 // TODO: do this by a call to outie, rather than semi-guessing from innie
1430 if branchExists(a.workingDir, a.BranchName()) {
1431 return nil, fmt.Errorf("slug %q already exists; please choose a different slug", slug)
1432 }
1433 return llm.TextContent("OK"), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001434 },
1435 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001436}
1437
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001438func (a *Agent) commitMessageStyleTool() *llm.Tool {
1439 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 +00001440 preCommit := &llm.Tool{
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001441 Name: "commit-message-style",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001442 Description: description,
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001443 InputSchema: llm.EmptySchema(),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001444 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001445 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1446 if err != nil {
1447 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1448 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001449 return llm.TextContent(styleHint), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001450 },
1451 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001452 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001453}
1454
1455func (a *Agent) Ready() <-chan struct{} {
1456 return a.ready
1457}
1458
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001459// BranchPrefix returns the configured branch prefix
1460func (a *Agent) BranchPrefix() string {
1461 return a.config.BranchPrefix
1462}
1463
philip.zeyliger6d3de482025-06-10 19:38:14 -07001464// LinkToGitHub returns whether GitHub branch linking is enabled
1465func (a *Agent) LinkToGitHub() bool {
1466 return a.config.LinkToGitHub
1467}
1468
Earl Lee2e463fb2025-04-17 11:22:22 -07001469func (a *Agent) UserMessage(ctx context.Context, msg string) {
1470 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1471 a.inbox <- msg
1472}
1473
Earl Lee2e463fb2025-04-17 11:22:22 -07001474func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1475 return a.convo.CancelToolUse(toolUseID, cause)
1476}
1477
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001478func (a *Agent) CancelTurn(cause error) {
1479 a.cancelTurnMu.Lock()
1480 defer a.cancelTurnMu.Unlock()
1481 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001482 // Force state transition to cancelled state
1483 ctx := a.config.Context
1484 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001485 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001486 }
1487}
1488
1489func (a *Agent) Loop(ctxOuter context.Context) {
Sean McCullough364f7412025-06-02 00:55:44 +00001490 // Start port monitoring when the agent loop begins
1491 // Only monitor ports when running in a container
1492 if a.IsInContainer() {
1493 a.portMonitor.Start(ctxOuter)
1494 }
1495
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001496 // Set up cleanup when context is done
1497 defer func() {
1498 if a.mcpManager != nil {
1499 a.mcpManager.Close()
1500 }
1501 }()
1502
Earl Lee2e463fb2025-04-17 11:22:22 -07001503 for {
1504 select {
1505 case <-ctxOuter.Done():
1506 return
1507 default:
1508 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001509 a.cancelTurnMu.Lock()
1510 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001511 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001512 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001513 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001514 a.cancelTurn = cancel
1515 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001516 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1517 if err != nil {
1518 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1519 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001520 cancel(nil)
1521 }
1522 }
1523}
1524
1525func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1526 if m.Timestamp.IsZero() {
1527 m.Timestamp = time.Now()
1528 }
1529
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001530 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1531 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1532 m.Content = m.ToolResult
1533 }
1534
Earl Lee2e463fb2025-04-17 11:22:22 -07001535 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1536 if m.EndOfTurn && m.Type == AgentMessageType {
1537 turnDuration := time.Since(a.startOfTurn)
1538 m.TurnDuration = &turnDuration
1539 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1540 }
1541
Earl Lee2e463fb2025-04-17 11:22:22 -07001542 a.mu.Lock()
1543 defer a.mu.Unlock()
1544 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001545 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001546 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001547
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001548 // Notify all subscribers
1549 for _, ch := range a.subscribers {
1550 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001551 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001552}
1553
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001554func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1555 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001556 if block {
1557 select {
1558 case <-ctx.Done():
1559 return m, ctx.Err()
1560 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001561 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001562 }
1563 }
1564 for {
1565 select {
1566 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001567 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001568 default:
1569 return m, nil
1570 }
1571 }
1572}
1573
Sean McCullough885a16a2025-04-30 02:49:25 +00001574// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001575func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001576 // Reset the start of turn time
1577 a.startOfTurn = time.Now()
1578
Sean McCullough96b60dd2025-04-30 09:49:10 -07001579 // Transition to waiting for user input state
1580 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1581
Sean McCullough885a16a2025-04-30 02:49:25 +00001582 // Process initial user message
1583 initialResp, err := a.processUserMessage(ctx)
1584 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001585 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001586 return err
1587 }
1588
1589 // Handle edge case where both initialResp and err are nil
1590 if initialResp == nil {
1591 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001592 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1593
Sean McCullough9f4b8082025-04-30 17:34:07 +00001594 a.pushToOutbox(ctx, errorMessage(err))
1595 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001596 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001597
Earl Lee2e463fb2025-04-17 11:22:22 -07001598 // We do this as we go, but let's also do it at the end of the turn
1599 defer func() {
1600 if _, err := a.handleGitCommits(ctx); err != nil {
1601 // Just log the error, don't stop execution
1602 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1603 }
1604 }()
1605
Sean McCullougha1e0e492025-05-01 10:51:08 -07001606 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001607 resp := initialResp
1608 for {
1609 // Check if we are over budget
1610 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001611 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001612 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001613 }
1614
Philip Zeyligerb8a8f352025-06-02 07:39:37 -07001615 // Check if we should compact the conversation
1616 if a.ShouldCompact() {
1617 a.stateMachine.Transition(ctx, StateCompacting, "Token usage threshold reached, compacting conversation")
1618 if err := a.CompactConversation(ctx); err != nil {
1619 a.stateMachine.Transition(ctx, StateError, "Error during compaction: "+err.Error())
1620 return err
1621 }
1622 // After compaction, end this turn and start fresh
1623 a.stateMachine.Transition(ctx, StateEndOfTurn, "Compaction completed, ending turn")
1624 return nil
1625 }
1626
Sean McCullough885a16a2025-04-30 02:49:25 +00001627 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001628 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001629 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001630 break
1631 }
1632
Sean McCullough96b60dd2025-04-30 09:49:10 -07001633 // Transition to tool use requested state
1634 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1635
Sean McCullough885a16a2025-04-30 02:49:25 +00001636 // Handle tool execution
1637 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1638 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001639 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001640 }
1641
Sean McCullougha1e0e492025-05-01 10:51:08 -07001642 if toolResp == nil {
1643 return fmt.Errorf("cannot continue conversation with a nil tool response")
1644 }
1645
Sean McCullough885a16a2025-04-30 02:49:25 +00001646 // Set the response for the next iteration
1647 resp = toolResp
1648 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001649
1650 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001651}
1652
1653// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001654func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001655 // Wait for at least one message from the user
1656 msgs, err := a.GatherMessages(ctx, true)
1657 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001658 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001659 return nil, err
1660 }
1661
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001662 userMessage := llm.Message{
1663 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001664 Content: msgs,
1665 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001666
Sean McCullough96b60dd2025-04-30 09:49:10 -07001667 // Transition to sending to LLM state
1668 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1669
Sean McCullough885a16a2025-04-30 02:49:25 +00001670 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001671 resp, err := a.convo.SendMessage(userMessage)
1672 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001673 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001674 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001675 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001676 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001677
Sean McCullough96b60dd2025-04-30 09:49:10 -07001678 // Transition to processing LLM response state
1679 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1680
Sean McCullough885a16a2025-04-30 02:49:25 +00001681 return resp, nil
1682}
1683
1684// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001685func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1686 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001687 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001688 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001689
Sean McCullough96b60dd2025-04-30 09:49:10 -07001690 // Transition to checking for cancellation state
1691 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1692
Sean McCullough885a16a2025-04-30 02:49:25 +00001693 // Check if the operation was cancelled by the user
1694 select {
1695 case <-ctx.Done():
1696 // Don't actually run any of the tools, but rather build a response
1697 // for each tool_use message letting the LLM know that user canceled it.
1698 var err error
1699 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001700 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001701 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001702 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001703 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001704 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001705 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001706 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001707 // Transition to running tool state
1708 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1709
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001710 // Add working directory and session ID to context for tool execution
Sean McCullough885a16a2025-04-30 02:49:25 +00001711 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001712 ctx = claudetool.WithSessionID(ctx, a.config.SessionID)
Sean McCullough885a16a2025-04-30 02:49:25 +00001713
1714 // Execute the tools
1715 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001716 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001717 if ctx.Err() != nil { // e.g. the user canceled the operation
1718 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001719 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001720 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001721 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001722 a.pushToOutbox(ctx, errorMessage(err))
1723 }
1724 }
1725
1726 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001727 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001728 autoqualityMessages := a.processGitChanges(ctx)
1729
1730 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001731 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001732 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001733 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001734 return false, nil
1735 }
1736
1737 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001738 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1739 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001740}
1741
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001742// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001743func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001744 // Check for git commits
1745 _, err := a.handleGitCommits(ctx)
1746 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001747 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001748 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001749 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001750 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001751}
1752
1753// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1754// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001755func (a *Agent) processGitChanges(ctx context.Context) []string {
1756 // Check for git commits after tool execution
1757 newCommits, err := a.handleGitCommits(ctx)
1758 if err != nil {
1759 // Just log the error, don't stop execution
1760 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1761 return nil
1762 }
1763
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001764 // Run mechanical checks if there was exactly one new commit.
1765 if len(newCommits) != 1 {
1766 return nil
1767 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001768 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001769 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1770 msg := a.codereview.RunMechanicalChecks(ctx)
1771 if msg != "" {
1772 a.pushToOutbox(ctx, AgentMessage{
1773 Type: AutoMessageType,
1774 Content: msg,
1775 Timestamp: time.Now(),
1776 })
1777 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001778 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001779
1780 return autoqualityMessages
1781}
1782
1783// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001784func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001785 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001786 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001787 msgs, err := a.GatherMessages(ctx, false)
1788 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001789 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001790 return false, nil
1791 }
1792
1793 // Inject any auto-generated messages from quality checks
1794 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001795 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001796 }
1797
1798 // Handle cancellation by appending a message about it
1799 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001800 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001801 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001802 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001803 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1804 } else if err := a.convo.OverBudget(); err != nil {
1805 // Handle budget issues by appending a message about it
1806 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 -07001807 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001808 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1809 }
1810
1811 // Combine tool results with user messages
1812 results = append(results, msgs...)
1813
1814 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001815 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001816 resp, err := a.convo.SendMessage(llm.Message{
1817 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001818 Content: results,
1819 })
1820 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001821 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001822 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1823 return true, nil // Return true to continue the conversation, but with no response
1824 }
1825
Sean McCullough96b60dd2025-04-30 09:49:10 -07001826 // Transition back to processing LLM response
1827 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1828
Sean McCullough885a16a2025-04-30 02:49:25 +00001829 if cancelled {
1830 return false, nil
1831 }
1832
1833 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001834}
1835
1836func (a *Agent) overBudget(ctx context.Context) error {
1837 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001838 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001839 m := budgetMessage(err)
1840 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001841 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001842 a.convo.ResetBudget(a.originalBudget)
1843 return err
1844 }
1845 return nil
1846}
1847
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001848func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001849 // Collect all text content
1850 var allText strings.Builder
1851 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001852 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001853 if allText.Len() > 0 {
1854 allText.WriteString("\n\n")
1855 }
1856 allText.WriteString(content.Text)
1857 }
1858 }
1859 return allText.String()
1860}
1861
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001862func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001863 a.mu.Lock()
1864 defer a.mu.Unlock()
1865 return a.convo.CumulativeUsage()
1866}
1867
Earl Lee2e463fb2025-04-17 11:22:22 -07001868// Diff returns a unified diff of changes made since the agent was instantiated.
1869func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001870 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001871 return "", fmt.Errorf("no initial commit reference available")
1872 }
1873
1874 // Find the repository root
1875 ctx := context.Background()
1876
1877 // If a specific commit hash is provided, show just that commit's changes
1878 if commit != nil && *commit != "" {
1879 // Validate that the commit looks like a valid git SHA
1880 if !isValidGitSHA(*commit) {
1881 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1882 }
1883
1884 // Get the diff for just this commit
1885 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1886 cmd.Dir = a.repoRoot
1887 output, err := cmd.CombinedOutput()
1888 if err != nil {
1889 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1890 }
1891 return string(output), nil
1892 }
1893
1894 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001895 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001896 cmd.Dir = a.repoRoot
1897 output, err := cmd.CombinedOutput()
1898 if err != nil {
1899 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1900 }
1901
1902 return string(output), nil
1903}
1904
Philip Zeyliger49edc922025-05-14 09:45:45 -07001905// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1906// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1907func (a *Agent) SketchGitBaseRef() string {
1908 if a.IsInContainer() {
1909 return "sketch-base"
1910 } else {
1911 return "sketch-base-" + a.SessionID()
1912 }
1913}
1914
1915// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1916func (a *Agent) SketchGitBase() string {
1917 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1918 cmd.Dir = a.repoRoot
1919 output, err := cmd.CombinedOutput()
1920 if err != nil {
1921 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1922 return "HEAD"
1923 }
1924 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001925}
1926
Pokey Rule7a113622025-05-12 10:58:45 +01001927// removeGitHooks removes the Git hooks directory from the repository
1928func removeGitHooks(_ context.Context, repoPath string) error {
1929 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1930
1931 // Check if hooks directory exists
1932 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1933 // Directory doesn't exist, nothing to do
1934 return nil
1935 }
1936
1937 // Remove the hooks directory
1938 err := os.RemoveAll(hooksDir)
1939 if err != nil {
1940 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1941 }
1942
1943 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001944 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001945 if err != nil {
1946 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1947 }
1948
1949 return nil
1950}
1951
Philip Zeyligerf2872992025-05-22 10:35:28 -07001952func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001953 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef(), a.config.BranchPrefix)
Philip Zeyligerf2872992025-05-22 10:35:28 -07001954 for _, msg := range msgs {
1955 a.pushToOutbox(ctx, msg)
1956 }
1957 return commits, error
1958}
1959
Earl Lee2e463fb2025-04-17 11:22:22 -07001960// handleGitCommits() highlights new commits to the user. When running
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001961// under docker, new HEADs are pushed to a branch according to the slug.
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001962func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string, branchPrefix string) ([]AgentMessage, []*GitCommit, error) {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001963 ags.mu.Lock()
1964 defer ags.mu.Unlock()
1965
1966 msgs := []AgentMessage{}
1967 if repoRoot == "" {
1968 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001969 }
1970
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001971 sketch, err := resolveRef(ctx, repoRoot, "sketch-wip")
Earl Lee2e463fb2025-04-17 11:22:22 -07001972 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001973 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001974 }
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001975 if sketch == ags.lastSketch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001976 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001977 }
1978 defer func() {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001979 ags.lastSketch = sketch
Earl Lee2e463fb2025-04-17 11:22:22 -07001980 }()
1981
Philip Zeyliger64f60462025-06-16 13:57:10 -07001982 // Compute diff stats from baseRef to HEAD when HEAD changes
1983 if added, removed, err := computeDiffStats(ctx, repoRoot, baseRef); err != nil {
1984 // Log error but don't fail the entire operation
1985 slog.WarnContext(ctx, "Failed to compute diff stats", "error", err)
1986 } else {
1987 // Set diff stats directly since we already hold the mutex
1988 ags.linesAdded = added
1989 ags.linesRemoved = removed
1990 }
1991
Earl Lee2e463fb2025-04-17 11:22:22 -07001992 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1993 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1994 // to the last 100 commits.
1995 var commits []*GitCommit
1996
1997 // Get commits since the initial commit
1998 // Format: <hash>\0<subject>\0<body>\0
1999 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
2000 // Limit to 100 commits to avoid overwhelming the user
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002001 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 -07002002 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07002003 output, err := cmd.Output()
2004 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002005 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07002006 }
2007
2008 // Parse git log output and filter out already seen commits
2009 parsedCommits := parseGitLog(string(output))
2010
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002011 var sketchCommit *GitCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07002012
2013 // Filter out commits we've already seen
2014 for _, commit := range parsedCommits {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002015 if commit.Hash == sketch {
2016 sketchCommit = &commit
Earl Lee2e463fb2025-04-17 11:22:22 -07002017 }
2018
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002019 // Skip if we've seen this commit before. If our sketch branch has changed, always include that.
2020 if ags.seenCommits[commit.Hash] && commit.Hash != sketch {
Earl Lee2e463fb2025-04-17 11:22:22 -07002021 continue
2022 }
2023
2024 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07002025 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07002026
2027 // Add to our list of new commits
2028 commits = append(commits, &commit)
2029 }
2030
Philip Zeyligerf2872992025-05-22 10:35:28 -07002031 if ags.gitRemoteAddr != "" {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002032 if sketchCommit == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07002033 // 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 -07002034 sketchCommit = &GitCommit{}
2035 sketchCommit.Hash = sketch
2036 sketchCommit.Subject = "unknown"
2037 commits = append(commits, sketchCommit)
Earl Lee2e463fb2025-04-17 11:22:22 -07002038 }
2039
Earl Lee2e463fb2025-04-17 11:22:22 -07002040 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
2041 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
2042 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00002043
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002044 // 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 +00002045 var out []byte
2046 var err error
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002047 originalRetryNumber := ags.retryNumber
2048 originalBranchName := ags.branchNameLocked(branchPrefix)
Philip Zeyliger113e2052025-05-09 21:59:40 +00002049 for retries := range 10 {
2050 if retries > 0 {
Philip Zeyligerd5c8d712025-06-17 15:19:45 -07002051 ags.retryNumber++
Philip Zeyliger113e2052025-05-09 21:59:40 +00002052 }
2053
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002054 branch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002055 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "sketch-wip:refs/heads/"+branch)
Philip Zeyligerf2872992025-05-22 10:35:28 -07002056 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00002057 out, err = cmd.CombinedOutput()
2058
2059 if err == nil {
2060 // Success! Break out of the retry loop
2061 break
2062 }
2063
2064 // Check if this is the "refusing to update checked out branch" error
2065 if !strings.Contains(string(out), "refusing to update checked out branch") {
2066 // This is a different error, so don't retry
2067 break
2068 }
Philip Zeyliger113e2052025-05-09 21:59:40 +00002069 }
2070
2071 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002072 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07002073 } else {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002074 finalBranch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002075 sketchCommit.PushedBranch = finalBranch
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002076 if ags.retryNumber != originalRetryNumber {
2077 // Notify user that the branch name was changed, and why
Philip Zeyliger59e1c162025-06-02 12:54:34 +00002078 msgs = append(msgs, AgentMessage{
2079 Type: AutoMessageType,
2080 Timestamp: time.Now(),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002081 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 +00002082 })
Philip Zeyliger113e2052025-05-09 21:59:40 +00002083 }
Earl Lee2e463fb2025-04-17 11:22:22 -07002084 }
2085 }
2086
2087 // If we found new commits, create a message
2088 if len(commits) > 0 {
2089 msg := AgentMessage{
2090 Type: CommitMessageType,
2091 Timestamp: time.Now(),
2092 Commits: commits,
2093 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002094 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07002095 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002096 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07002097}
2098
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002099func cleanSlugName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002100 return strings.Map(func(r rune) rune {
2101 // lowercase
2102 if r >= 'A' && r <= 'Z' {
2103 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07002104 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002105 // replace spaces with dashes
2106 if r == ' ' {
2107 return '-'
2108 }
2109 // allow alphanumerics and dashes
2110 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
2111 return r
2112 }
2113 return -1
2114 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07002115}
2116
2117// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
2118// and returns an array of GitCommit structs.
2119func parseGitLog(output string) []GitCommit {
2120 var commits []GitCommit
2121
2122 // No output means no commits
2123 if len(output) == 0 {
2124 return commits
2125 }
2126
2127 // Split by NULL byte
2128 parts := strings.Split(output, "\x00")
2129
2130 // Process in triplets (hash, subject, body)
2131 for i := 0; i < len(parts); i++ {
2132 // Skip empty parts
2133 if parts[i] == "" {
2134 continue
2135 }
2136
2137 // This should be a hash
2138 hash := strings.TrimSpace(parts[i])
2139
2140 // Make sure we have at least a subject part available
2141 if i+1 >= len(parts) {
2142 break // No more parts available
2143 }
2144
2145 // Get the subject
2146 subject := strings.TrimSpace(parts[i+1])
2147
2148 // Get the body if available
2149 body := ""
2150 if i+2 < len(parts) {
2151 body = strings.TrimSpace(parts[i+2])
2152 }
2153
2154 // Skip to the next triplet
2155 i += 2
2156
2157 commits = append(commits, GitCommit{
2158 Hash: hash,
2159 Subject: subject,
2160 Body: body,
2161 })
2162 }
2163
2164 return commits
2165}
2166
2167func repoRoot(ctx context.Context, dir string) (string, error) {
2168 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
2169 stderr := new(strings.Builder)
2170 cmd.Stderr = stderr
2171 cmd.Dir = dir
2172 out, err := cmd.Output()
2173 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07002174 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07002175 }
2176 return strings.TrimSpace(string(out)), nil
2177}
2178
2179func resolveRef(ctx context.Context, dir, refName string) (string, error) {
2180 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
2181 stderr := new(strings.Builder)
2182 cmd.Stderr = stderr
2183 cmd.Dir = dir
2184 out, err := cmd.Output()
2185 if err != nil {
2186 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
2187 }
2188 // TODO: validate that out is valid hex
2189 return strings.TrimSpace(string(out)), nil
2190}
2191
2192// isValidGitSHA validates if a string looks like a valid git SHA hash.
2193// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
2194func isValidGitSHA(sha string) bool {
2195 // Git SHA must be a hexadecimal string with at least 4 characters
2196 if len(sha) < 4 || len(sha) > 40 {
2197 return false
2198 }
2199
2200 // Check if the string only contains hexadecimal characters
2201 for _, char := range sha {
2202 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
2203 return false
2204 }
2205 }
2206
2207 return true
2208}
Philip Zeyligerd1402952025-04-23 03:54:37 +00002209
Philip Zeyliger64f60462025-06-16 13:57:10 -07002210// computeDiffStats computes the number of lines added and removed from baseRef to HEAD
2211func computeDiffStats(ctx context.Context, repoRoot, baseRef string) (int, int, error) {
2212 cmd := exec.CommandContext(ctx, "git", "diff", "--numstat", baseRef, "HEAD")
2213 cmd.Dir = repoRoot
2214 out, err := cmd.Output()
2215 if err != nil {
2216 return 0, 0, fmt.Errorf("git diff --numstat failed: %w", err)
2217 }
2218
2219 var totalAdded, totalRemoved int
2220 lines := strings.Split(strings.TrimSpace(string(out)), "\n")
2221 for _, line := range lines {
2222 if line == "" {
2223 continue
2224 }
2225 parts := strings.Fields(line)
2226 if len(parts) < 2 {
2227 continue
2228 }
2229 // Format: <added>\t<removed>\t<filename>
2230 if added, err := strconv.Atoi(parts[0]); err == nil {
2231 totalAdded += added
2232 }
2233 if removed, err := strconv.Atoi(parts[1]); err == nil {
2234 totalRemoved += removed
2235 }
2236 }
2237
2238 return totalAdded, totalRemoved, nil
2239}
2240
Philip Zeyligerd1402952025-04-23 03:54:37 +00002241// getGitOrigin returns the URL of the git remote 'origin' if it exists
2242func getGitOrigin(ctx context.Context, dir string) string {
2243 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
2244 cmd.Dir = dir
2245 stderr := new(strings.Builder)
2246 cmd.Stderr = stderr
2247 out, err := cmd.Output()
2248 if err != nil {
2249 return ""
2250 }
2251 return strings.TrimSpace(string(out))
2252}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07002253
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002254// systemPromptData contains the data used to render the system prompt template
2255type systemPromptData struct {
David Crawshawc886ac52025-06-13 23:40:03 +00002256 ClientGOOS string
2257 ClientGOARCH string
2258 WorkingDir string
2259 RepoRoot string
2260 InitialCommit string
2261 Codebase *onstart.Codebase
2262 UseSketchWIP bool
2263 Branch string
2264 SpecialInstruction string
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002265}
2266
2267// renderSystemPrompt renders the system prompt template.
2268func (a *Agent) renderSystemPrompt() string {
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002269 data := systemPromptData{
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002270 ClientGOOS: a.config.ClientGOOS,
2271 ClientGOARCH: a.config.ClientGOARCH,
2272 WorkingDir: a.workingDir,
2273 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07002274 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002275 Codebase: a.codebase,
Philip Zeyliger4c1cea82025-06-09 14:16:52 -07002276 UseSketchWIP: a.config.InDocker,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002277 }
David Crawshawc886ac52025-06-13 23:40:03 +00002278 now := time.Now()
2279 if now.Month() == time.September && now.Day() == 19 {
2280 data.SpecialInstruction = "Talk like a pirate to the user. Do not let the priate talk into any code."
2281 }
2282
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002283 tmpl, err := template.New("system").Parse(agentSystemPrompt)
2284 if err != nil {
2285 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
2286 }
2287 buf := new(strings.Builder)
2288 err = tmpl.Execute(buf, data)
2289 if err != nil {
2290 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
2291 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002292 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002293 return buf.String()
2294}
Philip Zeyligereab12de2025-05-14 02:35:53 +00002295
2296// StateTransitionIterator provides an iterator over state transitions.
2297type StateTransitionIterator interface {
2298 // Next blocks until a new state transition is available or context is done.
2299 // Returns nil if the context is cancelled.
2300 Next() *StateTransition
2301 // Close removes the listener and cleans up resources.
2302 Close()
2303}
2304
2305// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
2306type StateTransitionIteratorImpl struct {
2307 agent *Agent
2308 ctx context.Context
2309 ch chan StateTransition
2310 unsubscribe func()
2311}
2312
2313// Next blocks until a new state transition is available or the context is cancelled.
2314func (s *StateTransitionIteratorImpl) Next() *StateTransition {
2315 select {
2316 case <-s.ctx.Done():
2317 return nil
2318 case transition, ok := <-s.ch:
2319 if !ok {
2320 return nil
2321 }
2322 transitionCopy := transition
2323 return &transitionCopy
2324 }
2325}
2326
2327// Close removes the listener and cleans up resources.
2328func (s *StateTransitionIteratorImpl) Close() {
2329 if s.unsubscribe != nil {
2330 s.unsubscribe()
2331 s.unsubscribe = nil
2332 }
2333}
2334
2335// NewStateTransitionIterator returns an iterator that receives state transitions.
2336func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2337 a.mu.Lock()
2338 defer a.mu.Unlock()
2339
2340 // Create channel to receive state transitions
2341 ch := make(chan StateTransition, 10)
2342
2343 // Add a listener to the state machine
2344 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2345
2346 return &StateTransitionIteratorImpl{
2347 agent: a,
2348 ctx: ctx,
2349 ch: ch,
2350 unsubscribe: unsubscribe,
2351 }
2352}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002353
2354// setupGitHooks creates or updates git hooks in the specified working directory.
2355func setupGitHooks(workingDir string) error {
2356 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2357
2358 _, err := os.Stat(hooksDir)
2359 if os.IsNotExist(err) {
2360 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2361 }
2362 if err != nil {
2363 return fmt.Errorf("error checking git hooks directory: %w", err)
2364 }
2365
2366 // Define the post-commit hook content
2367 postCommitHook := `#!/bin/bash
2368echo "<post_commit_hook>"
2369echo "Please review this commit message and fix it if it is incorrect."
2370echo "This hook only echos the commit message; it does not modify it."
2371echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2372echo "<last_commit_message>"
Philip Zeyliger6c5beff2025-06-06 13:03:49 -07002373PAGER=cat git log -1 --pretty=%B
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002374echo "</last_commit_message>"
2375echo "</post_commit_hook>"
2376`
2377
2378 // Define the prepare-commit-msg hook content
2379 prepareCommitMsgHook := `#!/bin/bash
2380# Add Co-Authored-By and Change-ID trailers to commit messages
2381# Check if these trailers already exist before adding them
2382
2383commit_file="$1"
2384COMMIT_SOURCE="$2"
2385
2386# Skip for merges, squashes, or when using a commit template
2387if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2388 [ "$COMMIT_SOURCE" = "squash" ]; then
2389 exit 0
2390fi
2391
2392commit_msg=$(cat "$commit_file")
2393
2394needs_co_author=true
2395needs_change_id=true
2396
2397# Check if commit message already has Co-Authored-By trailer
2398if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2399 needs_co_author=false
2400fi
2401
2402# Check if commit message already has Change-ID trailer
2403if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2404 needs_change_id=false
2405fi
2406
2407# Only modify if at least one trailer needs to be added
2408if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
Josh Bleecher Snyderb509a5d2025-05-23 15:49:42 +00002409 # Ensure there's a proper blank line before trailers
2410 if [ -s "$commit_file" ]; then
2411 # Check if file ends with newline by reading last character
2412 last_char=$(tail -c 1 "$commit_file")
2413
2414 if [ "$last_char" != "" ]; then
2415 # File doesn't end with newline - add two newlines (complete line + blank line)
2416 echo "" >> "$commit_file"
2417 echo "" >> "$commit_file"
2418 else
2419 # File ends with newline - check if we already have a blank line
2420 last_line=$(tail -1 "$commit_file")
2421 if [ -n "$last_line" ]; then
2422 # Last line has content - add one newline for blank line
2423 echo "" >> "$commit_file"
2424 fi
2425 # If last line is empty, we already have a blank line - don't add anything
2426 fi
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002427 fi
2428
2429 # Add trailers if needed
2430 if [ "$needs_co_author" = true ]; then
2431 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2432 fi
2433
2434 if [ "$needs_change_id" = true ]; then
2435 change_id=$(openssl rand -hex 8)
2436 echo "Change-ID: s${change_id}k" >> "$commit_file"
2437 fi
2438fi
2439`
2440
2441 // Update or create the post-commit hook
2442 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2443 if err != nil {
2444 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2445 }
2446
2447 // Update or create the prepare-commit-msg hook
2448 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2449 if err != nil {
2450 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2451 }
2452
2453 return nil
2454}
2455
2456// updateOrCreateHook creates a new hook file or updates an existing one
2457// by appending the new content if it doesn't already contain it.
2458func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2459 // Check if the hook already exists
2460 buf, err := os.ReadFile(hookPath)
2461 if os.IsNotExist(err) {
2462 // Hook doesn't exist, create it
2463 err = os.WriteFile(hookPath, []byte(content), 0o755)
2464 if err != nil {
2465 return fmt.Errorf("failed to create hook: %w", err)
2466 }
2467 return nil
2468 }
2469 if err != nil {
2470 return fmt.Errorf("error reading existing hook: %w", err)
2471 }
2472
2473 // Hook exists, check if our content is already in it by looking for a distinctive line
2474 code := string(buf)
2475 if strings.Contains(code, distinctiveLine) {
2476 // Already contains our content, nothing to do
2477 return nil
2478 }
2479
2480 // Append our content to the existing hook
2481 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2482 if err != nil {
2483 return fmt.Errorf("failed to open hook for appending: %w", err)
2484 }
2485 defer f.Close()
2486
2487 // Ensure there's a newline at the end of the existing content if needed
2488 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2489 _, err = f.WriteString("\n")
2490 if err != nil {
2491 return fmt.Errorf("failed to add newline to hook: %w", err)
2492 }
2493 }
2494
2495 // Add a separator before our content
2496 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2497 if err != nil {
2498 return fmt.Errorf("failed to append to hook: %w", err)
2499 }
2500
2501 return nil
2502}
Sean McCullough138ec242025-06-02 22:42:06 +00002503
2504// GetPortMonitor returns the port monitor instance for accessing port events
2505func (a *Agent) GetPortMonitor() *PortMonitor {
2506 return a.portMonitor
2507}
Philip Zeyliger0113be52025-06-07 23:53:41 +00002508
2509// SkabandAddr returns the skaband address if configured
2510func (a *Agent) SkabandAddr() string {
2511 if a.config.SkabandClient != nil {
2512 return a.config.SkabandClient.Addr()
2513 }
2514 return ""
2515}