blob: 2683cdcdfc9113a945827400273b34f12d3e8e3f [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
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001284 // Add MCP tools if configured
1285 if len(a.config.MCPServers) > 0 {
Philip Zeyliger4201bde2025-06-27 17:22:43 -07001286
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001287 slog.InfoContext(ctx, "Initializing MCP connections", "servers", len(a.config.MCPServers))
Philip Zeyliger4201bde2025-06-27 17:22:43 -07001288 serverConfigs, parseErrors := mcp.ParseServerConfigs(ctx, a.config.MCPServers)
1289
1290 // Replace any headers with value _sketch_public_key_ and _sketch_session_id_ with those values.
1291 for i := range serverConfigs {
1292 if serverConfigs[i].Headers != nil {
1293 for key, value := range serverConfigs[i].Headers {
1294 // Replace _sketch_public_key_ placeholder
1295 if value == "_sketch_public_key_" {
1296 serverConfigs[i].Headers[key] = os.Getenv("SKETCH_PUB_KEY")
1297 }
1298 }
1299 }
1300 }
1301 mcpConnections, mcpErrors := a.mcpManager.ConnectToServerConfigs(ctx, serverConfigs, 10*time.Second, parseErrors)
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001302
1303 if len(mcpErrors) > 0 {
1304 for _, err := range mcpErrors {
1305 slog.ErrorContext(ctx, "MCP connection error", "error", err)
1306 // Send agent message about MCP connection failures
1307 a.pushToOutbox(ctx, AgentMessage{
1308 Type: ErrorMessageType,
1309 Content: fmt.Sprintf("MCP server connection failed: %v", err),
1310 })
1311 }
1312 }
1313
1314 if len(mcpConnections) > 0 {
1315 // Add tools from all successful connections
1316 totalTools := 0
1317 for _, connection := range mcpConnections {
1318 convo.Tools = append(convo.Tools, connection.Tools...)
1319 totalTools += len(connection.Tools)
1320 // Log tools per server using structured data
1321 slog.InfoContext(ctx, "Added MCP tools from server", "server", connection.ServerName, "count", len(connection.Tools), "tools", connection.ToolNames)
1322 }
1323 slog.InfoContext(ctx, "Total MCP tools added", "count", totalTools)
1324 } else {
1325 slog.InfoContext(ctx, "No MCP tools available after connection attempts")
1326 }
1327 }
1328
Earl Lee2e463fb2025-04-17 11:22:22 -07001329 convo.Listener = a
1330 return convo
1331}
1332
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001333var multipleChoiceTool = &llm.Tool{
1334 Name: "multiplechoice",
1335 Description: "Present the user with an quick way to answer to your question using one of a short list of possible answers you would expect from the user.",
1336 EndsTurn: true,
1337 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -07001338 "type": "object",
1339 "description": "The question and a list of answers you would expect the user to choose from.",
1340 "properties": {
1341 "question": {
1342 "type": "string",
1343 "description": "The text of the multiple-choice question you would like the user, e.g. 'What kinds of test cases would you like me to add?'"
1344 },
1345 "responseOptions": {
1346 "type": "array",
1347 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
1348 "items": {
1349 "type": "object",
1350 "properties": {
1351 "caption": {
1352 "type": "string",
1353 "description": "The caption, e.g. 'Basic coverage', 'Error return values', or 'Malformed input' for the response button. Do NOT include options for responses that would end the conversation like 'Ok', 'No thank you', 'This looks good'"
1354 },
1355 "responseText": {
1356 "type": "string",
1357 "description": "The full text of the response, e.g. 'Add unit tests for basic test coverage', 'Add unit tests for error return values', or 'Add unit tests for malformed input'"
1358 }
1359 },
1360 "required": ["caption", "responseText"]
1361 }
1362 }
1363 },
1364 "required": ["question", "responseOptions"]
1365}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001366 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1367 // The Run logic for "multiplechoice" tool is a no-op on the server.
1368 // The UI will present a list of options for the user to select from,
1369 // and that's it as far as "executing" the tool_use goes.
1370 // When the user *does* select one of the presented options, that
1371 // responseText gets sent as a chat message on behalf of the user.
1372 return llm.TextContent("end your turn and wait for the user to respond"), nil
1373 },
Sean McCullough485afc62025-04-28 14:28:39 -07001374}
1375
1376type MultipleChoiceOption struct {
1377 Caption string `json:"caption"`
1378 ResponseText string `json:"responseText"`
1379}
1380
1381type MultipleChoiceParams struct {
1382 Question string `json:"question"`
1383 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1384}
1385
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001386// branchExists reports whether branchName exists, either locally or in well-known remotes.
1387func branchExists(dir, branchName string) bool {
1388 refs := []string{
1389 "refs/heads/",
1390 "refs/remotes/origin/",
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001391 }
1392 for _, ref := range refs {
1393 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1394 cmd.Dir = dir
1395 if cmd.Run() == nil { // exit code 0 means branch exists
1396 return true
1397 }
1398 }
1399 return false
1400}
1401
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001402func (a *Agent) setSlugTool() *llm.Tool {
1403 return &llm.Tool{
1404 Name: "set-slug",
1405 Description: `Set a short slug as an identifier for this conversation.`,
Earl Lee2e463fb2025-04-17 11:22:22 -07001406 InputSchema: json.RawMessage(`{
1407 "type": "object",
1408 "properties": {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001409 "slug": {
Earl Lee2e463fb2025-04-17 11:22:22 -07001410 "type": "string",
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001411 "description": "A 2-3 word alphanumeric hyphenated slug, imperative tense"
Earl Lee2e463fb2025-04-17 11:22:22 -07001412 }
1413 },
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001414 "required": ["slug"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001415}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001416 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001417 var params struct {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001418 Slug string `json:"slug"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001419 }
1420 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001421 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001422 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001423 // Prevent slug changes if there have been git changes
1424 // This lets the agent change its mind about a good slug,
1425 // while ensuring that once a branch has been pushed, it remains stable.
1426 if s := a.Slug(); s != "" && s != params.Slug && a.gitState.HasSeenCommits() {
1427 return nil, fmt.Errorf("slug already set to %q", s)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001428 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001429 if params.Slug == "" {
1430 return nil, fmt.Errorf("slug parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001431 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001432 slug := cleanSlugName(params.Slug)
1433 if slug == "" {
1434 return nil, fmt.Errorf("slug parameter could not be converted to a valid slug")
1435 }
1436 a.SetSlug(slug)
1437 // TODO: do this by a call to outie, rather than semi-guessing from innie
1438 if branchExists(a.workingDir, a.BranchName()) {
1439 return nil, fmt.Errorf("slug %q already exists; please choose a different slug", slug)
1440 }
1441 return llm.TextContent("OK"), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001442 },
1443 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001444}
1445
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001446func (a *Agent) commitMessageStyleTool() *llm.Tool {
1447 description := `Provides git commit message style guidance. MANDATORY: You must use this tool before making any git commits.`
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001448 preCommit := &llm.Tool{
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001449 Name: "commit-message-style",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001450 Description: description,
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001451 InputSchema: llm.EmptySchema(),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001452 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001453 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1454 if err != nil {
1455 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1456 }
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001457 return llm.TextContent(styleHint), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001458 },
1459 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001460 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001461}
1462
1463func (a *Agent) Ready() <-chan struct{} {
1464 return a.ready
1465}
1466
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001467// BranchPrefix returns the configured branch prefix
1468func (a *Agent) BranchPrefix() string {
1469 return a.config.BranchPrefix
1470}
1471
philip.zeyliger6d3de482025-06-10 19:38:14 -07001472// LinkToGitHub returns whether GitHub branch linking is enabled
1473func (a *Agent) LinkToGitHub() bool {
1474 return a.config.LinkToGitHub
1475}
1476
Earl Lee2e463fb2025-04-17 11:22:22 -07001477func (a *Agent) UserMessage(ctx context.Context, msg string) {
1478 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1479 a.inbox <- msg
1480}
1481
Earl Lee2e463fb2025-04-17 11:22:22 -07001482func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1483 return a.convo.CancelToolUse(toolUseID, cause)
1484}
1485
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001486func (a *Agent) CancelTurn(cause error) {
1487 a.cancelTurnMu.Lock()
1488 defer a.cancelTurnMu.Unlock()
1489 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001490 // Force state transition to cancelled state
1491 ctx := a.config.Context
1492 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001493 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001494 }
1495}
1496
1497func (a *Agent) Loop(ctxOuter context.Context) {
Sean McCullough364f7412025-06-02 00:55:44 +00001498 // Start port monitoring when the agent loop begins
1499 // Only monitor ports when running in a container
1500 if a.IsInContainer() {
1501 a.portMonitor.Start(ctxOuter)
1502 }
1503
Philip Zeyliger194bfa82025-06-24 06:03:06 -07001504 // Set up cleanup when context is done
1505 defer func() {
1506 if a.mcpManager != nil {
1507 a.mcpManager.Close()
1508 }
1509 }()
1510
Earl Lee2e463fb2025-04-17 11:22:22 -07001511 for {
1512 select {
1513 case <-ctxOuter.Done():
1514 return
1515 default:
1516 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001517 a.cancelTurnMu.Lock()
1518 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001519 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001520 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001521 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001522 a.cancelTurn = cancel
1523 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001524 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1525 if err != nil {
1526 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1527 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001528 cancel(nil)
1529 }
1530 }
1531}
1532
1533func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1534 if m.Timestamp.IsZero() {
1535 m.Timestamp = time.Now()
1536 }
1537
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001538 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1539 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1540 m.Content = m.ToolResult
1541 }
1542
Earl Lee2e463fb2025-04-17 11:22:22 -07001543 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1544 if m.EndOfTurn && m.Type == AgentMessageType {
1545 turnDuration := time.Since(a.startOfTurn)
1546 m.TurnDuration = &turnDuration
1547 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1548 }
1549
Earl Lee2e463fb2025-04-17 11:22:22 -07001550 a.mu.Lock()
1551 defer a.mu.Unlock()
1552 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001553 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001554 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001555
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001556 // Notify all subscribers
1557 for _, ch := range a.subscribers {
1558 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001559 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001560}
1561
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001562func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1563 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001564 if block {
1565 select {
1566 case <-ctx.Done():
1567 return m, ctx.Err()
1568 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001569 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001570 }
1571 }
1572 for {
1573 select {
1574 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001575 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001576 default:
1577 return m, nil
1578 }
1579 }
1580}
1581
Sean McCullough885a16a2025-04-30 02:49:25 +00001582// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001583func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001584 // Reset the start of turn time
1585 a.startOfTurn = time.Now()
1586
Sean McCullough96b60dd2025-04-30 09:49:10 -07001587 // Transition to waiting for user input state
1588 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1589
Sean McCullough885a16a2025-04-30 02:49:25 +00001590 // Process initial user message
1591 initialResp, err := a.processUserMessage(ctx)
1592 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001593 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001594 return err
1595 }
1596
1597 // Handle edge case where both initialResp and err are nil
1598 if initialResp == nil {
1599 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001600 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1601
Sean McCullough9f4b8082025-04-30 17:34:07 +00001602 a.pushToOutbox(ctx, errorMessage(err))
1603 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001604 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001605
Earl Lee2e463fb2025-04-17 11:22:22 -07001606 // We do this as we go, but let's also do it at the end of the turn
1607 defer func() {
1608 if _, err := a.handleGitCommits(ctx); err != nil {
1609 // Just log the error, don't stop execution
1610 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1611 }
1612 }()
1613
Sean McCullougha1e0e492025-05-01 10:51:08 -07001614 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001615 resp := initialResp
1616 for {
1617 // Check if we are over budget
1618 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001619 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001620 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001621 }
1622
Philip Zeyligerb8a8f352025-06-02 07:39:37 -07001623 // Check if we should compact the conversation
1624 if a.ShouldCompact() {
1625 a.stateMachine.Transition(ctx, StateCompacting, "Token usage threshold reached, compacting conversation")
1626 if err := a.CompactConversation(ctx); err != nil {
1627 a.stateMachine.Transition(ctx, StateError, "Error during compaction: "+err.Error())
1628 return err
1629 }
1630 // After compaction, end this turn and start fresh
1631 a.stateMachine.Transition(ctx, StateEndOfTurn, "Compaction completed, ending turn")
1632 return nil
1633 }
1634
Sean McCullough885a16a2025-04-30 02:49:25 +00001635 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001636 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001637 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001638 break
1639 }
1640
Sean McCullough96b60dd2025-04-30 09:49:10 -07001641 // Transition to tool use requested state
1642 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1643
Sean McCullough885a16a2025-04-30 02:49:25 +00001644 // Handle tool execution
1645 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1646 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001647 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001648 }
1649
Sean McCullougha1e0e492025-05-01 10:51:08 -07001650 if toolResp == nil {
1651 return fmt.Errorf("cannot continue conversation with a nil tool response")
1652 }
1653
Sean McCullough885a16a2025-04-30 02:49:25 +00001654 // Set the response for the next iteration
1655 resp = toolResp
1656 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001657
1658 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001659}
1660
1661// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001662func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001663 // Wait for at least one message from the user
1664 msgs, err := a.GatherMessages(ctx, true)
1665 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001666 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001667 return nil, err
1668 }
1669
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001670 userMessage := llm.Message{
1671 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001672 Content: msgs,
1673 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001674
Sean McCullough96b60dd2025-04-30 09:49:10 -07001675 // Transition to sending to LLM state
1676 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1677
Sean McCullough885a16a2025-04-30 02:49:25 +00001678 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001679 resp, err := a.convo.SendMessage(userMessage)
1680 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001681 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001682 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001683 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001684 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001685
Sean McCullough96b60dd2025-04-30 09:49:10 -07001686 // Transition to processing LLM response state
1687 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1688
Sean McCullough885a16a2025-04-30 02:49:25 +00001689 return resp, nil
1690}
1691
1692// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001693func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1694 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001695 cancelled := false
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001696 toolEndsTurn := false
Sean McCullough885a16a2025-04-30 02:49:25 +00001697
Sean McCullough96b60dd2025-04-30 09:49:10 -07001698 // Transition to checking for cancellation state
1699 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1700
Sean McCullough885a16a2025-04-30 02:49:25 +00001701 // Check if the operation was cancelled by the user
1702 select {
1703 case <-ctx.Done():
1704 // Don't actually run any of the tools, but rather build a response
1705 // for each tool_use message letting the LLM know that user canceled it.
1706 var err error
1707 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001708 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001709 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001710 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001711 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001712 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001713 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001714 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001715 // Transition to running tool state
1716 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1717
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001718 // Add working directory and session ID to context for tool execution
Sean McCullough885a16a2025-04-30 02:49:25 +00001719 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001720 ctx = claudetool.WithSessionID(ctx, a.config.SessionID)
Sean McCullough885a16a2025-04-30 02:49:25 +00001721
1722 // Execute the tools
1723 var err error
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001724 results, toolEndsTurn, err = a.convo.ToolResultContents(ctx, resp)
Sean McCullough885a16a2025-04-30 02:49:25 +00001725 if ctx.Err() != nil { // e.g. the user canceled the operation
1726 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001727 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001728 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001729 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001730 a.pushToOutbox(ctx, errorMessage(err))
1731 }
1732 }
1733
1734 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001735 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001736 autoqualityMessages := a.processGitChanges(ctx)
1737
1738 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001739 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001740 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001741 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001742 return false, nil
1743 }
1744
1745 // Continue the conversation with tool results and any user messages
Josh Bleecher Snyder64f2aa82025-05-14 18:31:05 +00001746 shouldContinue, resp := a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1747 return shouldContinue && !toolEndsTurn, resp
Sean McCullough885a16a2025-04-30 02:49:25 +00001748}
1749
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001750// DetectGitChanges checks for new git commits and pushes them if found
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001751func (a *Agent) DetectGitChanges(ctx context.Context) error {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001752 // Check for git commits
1753 _, err := a.handleGitCommits(ctx)
1754 if err != nil {
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001755 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001756 return fmt.Errorf("failed to check for new git commits: %w", err)
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001757 }
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001758 return nil
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001759}
1760
1761// processGitChanges checks for new git commits, runs autoformatters if needed, and returns any messages generated
1762// This is used internally by the agent loop
Sean McCullough885a16a2025-04-30 02:49:25 +00001763func (a *Agent) processGitChanges(ctx context.Context) []string {
1764 // Check for git commits after tool execution
1765 newCommits, err := a.handleGitCommits(ctx)
1766 if err != nil {
1767 // Just log the error, don't stop execution
1768 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1769 return nil
1770 }
1771
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001772 // Run mechanical checks if there was exactly one new commit.
1773 if len(newCommits) != 1 {
1774 return nil
1775 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001776 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001777 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1778 msg := a.codereview.RunMechanicalChecks(ctx)
1779 if msg != "" {
1780 a.pushToOutbox(ctx, AgentMessage{
1781 Type: AutoMessageType,
1782 Content: msg,
1783 Timestamp: time.Now(),
1784 })
1785 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001786 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001787
1788 return autoqualityMessages
1789}
1790
1791// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001792func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001793 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001794 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001795 msgs, err := a.GatherMessages(ctx, false)
1796 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001797 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001798 return false, nil
1799 }
1800
1801 // Inject any auto-generated messages from quality checks
1802 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001803 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001804 }
1805
1806 // Handle cancellation by appending a message about it
1807 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001808 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001809 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001810 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001811 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1812 } else if err := a.convo.OverBudget(); err != nil {
1813 // Handle budget issues by appending a message about it
1814 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 -07001815 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001816 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1817 }
1818
1819 // Combine tool results with user messages
1820 results = append(results, msgs...)
1821
1822 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001823 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001824 resp, err := a.convo.SendMessage(llm.Message{
1825 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001826 Content: results,
1827 })
1828 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001829 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001830 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1831 return true, nil // Return true to continue the conversation, but with no response
1832 }
1833
Sean McCullough96b60dd2025-04-30 09:49:10 -07001834 // Transition back to processing LLM response
1835 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1836
Sean McCullough885a16a2025-04-30 02:49:25 +00001837 if cancelled {
1838 return false, nil
1839 }
1840
1841 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001842}
1843
1844func (a *Agent) overBudget(ctx context.Context) error {
1845 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001846 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001847 m := budgetMessage(err)
1848 m.Content = m.Content + "\n\nBudget reset."
David Crawshaw35c72bc2025-05-20 11:17:10 -07001849 a.pushToOutbox(ctx, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001850 a.convo.ResetBudget(a.originalBudget)
1851 return err
1852 }
1853 return nil
1854}
1855
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001856func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001857 // Collect all text content
1858 var allText strings.Builder
1859 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001860 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001861 if allText.Len() > 0 {
1862 allText.WriteString("\n\n")
1863 }
1864 allText.WriteString(content.Text)
1865 }
1866 }
1867 return allText.String()
1868}
1869
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001870func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001871 a.mu.Lock()
1872 defer a.mu.Unlock()
1873 return a.convo.CumulativeUsage()
1874}
1875
Earl Lee2e463fb2025-04-17 11:22:22 -07001876// Diff returns a unified diff of changes made since the agent was instantiated.
1877func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001878 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001879 return "", fmt.Errorf("no initial commit reference available")
1880 }
1881
1882 // Find the repository root
1883 ctx := context.Background()
1884
1885 // If a specific commit hash is provided, show just that commit's changes
1886 if commit != nil && *commit != "" {
1887 // Validate that the commit looks like a valid git SHA
1888 if !isValidGitSHA(*commit) {
1889 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1890 }
1891
1892 // Get the diff for just this commit
1893 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1894 cmd.Dir = a.repoRoot
1895 output, err := cmd.CombinedOutput()
1896 if err != nil {
1897 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1898 }
1899 return string(output), nil
1900 }
1901
1902 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001903 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001904 cmd.Dir = a.repoRoot
1905 output, err := cmd.CombinedOutput()
1906 if err != nil {
1907 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1908 }
1909
1910 return string(output), nil
1911}
1912
Philip Zeyliger49edc922025-05-14 09:45:45 -07001913// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1914// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1915func (a *Agent) SketchGitBaseRef() string {
1916 if a.IsInContainer() {
1917 return "sketch-base"
1918 } else {
1919 return "sketch-base-" + a.SessionID()
1920 }
1921}
1922
1923// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1924func (a *Agent) SketchGitBase() string {
1925 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1926 cmd.Dir = a.repoRoot
1927 output, err := cmd.CombinedOutput()
1928 if err != nil {
1929 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1930 return "HEAD"
1931 }
1932 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001933}
1934
Pokey Rule7a113622025-05-12 10:58:45 +01001935// removeGitHooks removes the Git hooks directory from the repository
1936func removeGitHooks(_ context.Context, repoPath string) error {
1937 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1938
1939 // Check if hooks directory exists
1940 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1941 // Directory doesn't exist, nothing to do
1942 return nil
1943 }
1944
1945 // Remove the hooks directory
1946 err := os.RemoveAll(hooksDir)
1947 if err != nil {
1948 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1949 }
1950
1951 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001952 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001953 if err != nil {
1954 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1955 }
1956
1957 return nil
1958}
1959
Philip Zeyligerf2872992025-05-22 10:35:28 -07001960func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001961 msgs, commits, error := a.gitState.handleGitCommits(ctx, a.SessionID(), a.repoRoot, a.SketchGitBaseRef(), a.config.BranchPrefix)
Philip Zeyligerf2872992025-05-22 10:35:28 -07001962 for _, msg := range msgs {
1963 a.pushToOutbox(ctx, msg)
1964 }
1965 return commits, error
1966}
1967
Earl Lee2e463fb2025-04-17 11:22:22 -07001968// handleGitCommits() highlights new commits to the user. When running
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001969// under docker, new HEADs are pushed to a branch according to the slug.
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001970func (ags *AgentGitState) handleGitCommits(ctx context.Context, sessionID string, repoRoot string, baseRef string, branchPrefix string) ([]AgentMessage, []*GitCommit, error) {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001971 ags.mu.Lock()
1972 defer ags.mu.Unlock()
1973
1974 msgs := []AgentMessage{}
1975 if repoRoot == "" {
1976 return msgs, nil, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001977 }
1978
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001979 sketch, err := resolveRef(ctx, repoRoot, "sketch-wip")
Earl Lee2e463fb2025-04-17 11:22:22 -07001980 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001981 return msgs, nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001982 }
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001983 if sketch == ags.lastSketch {
Philip Zeyligerf2872992025-05-22 10:35:28 -07001984 return msgs, nil, nil // nothing to do
Earl Lee2e463fb2025-04-17 11:22:22 -07001985 }
1986 defer func() {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07001987 ags.lastSketch = sketch
Earl Lee2e463fb2025-04-17 11:22:22 -07001988 }()
1989
Philip Zeyliger64f60462025-06-16 13:57:10 -07001990 // Compute diff stats from baseRef to HEAD when HEAD changes
1991 if added, removed, err := computeDiffStats(ctx, repoRoot, baseRef); err != nil {
1992 // Log error but don't fail the entire operation
1993 slog.WarnContext(ctx, "Failed to compute diff stats", "error", err)
1994 } else {
1995 // Set diff stats directly since we already hold the mutex
1996 ags.linesAdded = added
1997 ags.linesRemoved = removed
1998 }
1999
Earl Lee2e463fb2025-04-17 11:22:22 -07002000 // Get new commits. Because it's possible that the agent does rebases, fixups, and
2001 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
2002 // to the last 100 commits.
2003 var commits []*GitCommit
2004
2005 // Get commits since the initial commit
2006 // Format: <hash>\0<subject>\0<body>\0
2007 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
2008 // Limit to 100 commits to avoid overwhelming the user
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002009 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 -07002010 cmd.Dir = repoRoot
Earl Lee2e463fb2025-04-17 11:22:22 -07002011 output, err := cmd.Output()
2012 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002013 return msgs, nil, fmt.Errorf("failed to get git log: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -07002014 }
2015
2016 // Parse git log output and filter out already seen commits
2017 parsedCommits := parseGitLog(string(output))
2018
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002019 var sketchCommit *GitCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07002020
2021 // Filter out commits we've already seen
2022 for _, commit := range parsedCommits {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002023 if commit.Hash == sketch {
2024 sketchCommit = &commit
Earl Lee2e463fb2025-04-17 11:22:22 -07002025 }
2026
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002027 // Skip if we've seen this commit before. If our sketch branch has changed, always include that.
2028 if ags.seenCommits[commit.Hash] && commit.Hash != sketch {
Earl Lee2e463fb2025-04-17 11:22:22 -07002029 continue
2030 }
2031
2032 // Mark this commit as seen
Philip Zeyligerf2872992025-05-22 10:35:28 -07002033 ags.seenCommits[commit.Hash] = true
Earl Lee2e463fb2025-04-17 11:22:22 -07002034
2035 // Add to our list of new commits
2036 commits = append(commits, &commit)
2037 }
2038
Philip Zeyligerf2872992025-05-22 10:35:28 -07002039 if ags.gitRemoteAddr != "" {
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002040 if sketchCommit == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07002041 // 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 -07002042 sketchCommit = &GitCommit{}
2043 sketchCommit.Hash = sketch
2044 sketchCommit.Subject = "unknown"
2045 commits = append(commits, sketchCommit)
Earl Lee2e463fb2025-04-17 11:22:22 -07002046 }
2047
Earl Lee2e463fb2025-04-17 11:22:22 -07002048 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
2049 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
2050 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00002051
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002052 // 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 +00002053 var out []byte
2054 var err error
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002055 originalRetryNumber := ags.retryNumber
2056 originalBranchName := ags.branchNameLocked(branchPrefix)
Philip Zeyliger113e2052025-05-09 21:59:40 +00002057 for retries := range 10 {
2058 if retries > 0 {
Philip Zeyligerd5c8d712025-06-17 15:19:45 -07002059 ags.retryNumber++
Philip Zeyliger113e2052025-05-09 21:59:40 +00002060 }
2061
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002062 branch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002063 cmd = exec.Command("git", "push", "--force", ags.gitRemoteAddr, "sketch-wip:refs/heads/"+branch)
Philip Zeyligerf2872992025-05-22 10:35:28 -07002064 cmd.Dir = repoRoot
Philip Zeyliger113e2052025-05-09 21:59:40 +00002065 out, err = cmd.CombinedOutput()
2066
2067 if err == nil {
2068 // Success! Break out of the retry loop
2069 break
2070 }
2071
2072 // Check if this is the "refusing to update checked out branch" error
2073 if !strings.Contains(string(out), "refusing to update checked out branch") {
2074 // This is a different error, so don't retry
2075 break
2076 }
Philip Zeyliger113e2052025-05-09 21:59:40 +00002077 }
2078
2079 if err != nil {
Philip Zeyligerf2872992025-05-22 10:35:28 -07002080 msgs = append(msgs, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
Earl Lee2e463fb2025-04-17 11:22:22 -07002081 } else {
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002082 finalBranch := ags.branchNameLocked(branchPrefix)
Josh Bleecher Snyder715b8d92025-06-06 12:36:38 -07002083 sketchCommit.PushedBranch = finalBranch
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002084 if ags.retryNumber != originalRetryNumber {
2085 // Notify user that the branch name was changed, and why
Philip Zeyliger59e1c162025-06-02 12:54:34 +00002086 msgs = append(msgs, AgentMessage{
2087 Type: AutoMessageType,
2088 Timestamp: time.Now(),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002089 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 +00002090 })
Philip Zeyliger113e2052025-05-09 21:59:40 +00002091 }
Earl Lee2e463fb2025-04-17 11:22:22 -07002092 }
2093 }
2094
2095 // If we found new commits, create a message
2096 if len(commits) > 0 {
2097 msg := AgentMessage{
2098 Type: CommitMessageType,
2099 Timestamp: time.Now(),
2100 Commits: commits,
2101 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002102 msgs = append(msgs, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07002103 }
Philip Zeyligerf2872992025-05-22 10:35:28 -07002104 return msgs, commits, nil
Earl Lee2e463fb2025-04-17 11:22:22 -07002105}
2106
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07002107func cleanSlugName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002108 return strings.Map(func(r rune) rune {
2109 // lowercase
2110 if r >= 'A' && r <= 'Z' {
2111 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07002112 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00002113 // replace spaces with dashes
2114 if r == ' ' {
2115 return '-'
2116 }
2117 // allow alphanumerics and dashes
2118 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
2119 return r
2120 }
2121 return -1
2122 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07002123}
2124
2125// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
2126// and returns an array of GitCommit structs.
2127func parseGitLog(output string) []GitCommit {
2128 var commits []GitCommit
2129
2130 // No output means no commits
2131 if len(output) == 0 {
2132 return commits
2133 }
2134
2135 // Split by NULL byte
2136 parts := strings.Split(output, "\x00")
2137
2138 // Process in triplets (hash, subject, body)
2139 for i := 0; i < len(parts); i++ {
2140 // Skip empty parts
2141 if parts[i] == "" {
2142 continue
2143 }
2144
2145 // This should be a hash
2146 hash := strings.TrimSpace(parts[i])
2147
2148 // Make sure we have at least a subject part available
2149 if i+1 >= len(parts) {
2150 break // No more parts available
2151 }
2152
2153 // Get the subject
2154 subject := strings.TrimSpace(parts[i+1])
2155
2156 // Get the body if available
2157 body := ""
2158 if i+2 < len(parts) {
2159 body = strings.TrimSpace(parts[i+2])
2160 }
2161
2162 // Skip to the next triplet
2163 i += 2
2164
2165 commits = append(commits, GitCommit{
2166 Hash: hash,
2167 Subject: subject,
2168 Body: body,
2169 })
2170 }
2171
2172 return commits
2173}
2174
2175func repoRoot(ctx context.Context, dir string) (string, error) {
2176 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
2177 stderr := new(strings.Builder)
2178 cmd.Stderr = stderr
2179 cmd.Dir = dir
2180 out, err := cmd.Output()
2181 if err != nil {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -07002182 return "", fmt.Errorf("git rev-parse (in %s) failed: %w\n%s", dir, err, stderr)
Earl Lee2e463fb2025-04-17 11:22:22 -07002183 }
2184 return strings.TrimSpace(string(out)), nil
2185}
2186
2187func resolveRef(ctx context.Context, dir, refName string) (string, error) {
2188 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
2189 stderr := new(strings.Builder)
2190 cmd.Stderr = stderr
2191 cmd.Dir = dir
2192 out, err := cmd.Output()
2193 if err != nil {
2194 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
2195 }
2196 // TODO: validate that out is valid hex
2197 return strings.TrimSpace(string(out)), nil
2198}
2199
2200// isValidGitSHA validates if a string looks like a valid git SHA hash.
2201// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
2202func isValidGitSHA(sha string) bool {
2203 // Git SHA must be a hexadecimal string with at least 4 characters
2204 if len(sha) < 4 || len(sha) > 40 {
2205 return false
2206 }
2207
2208 // Check if the string only contains hexadecimal characters
2209 for _, char := range sha {
2210 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
2211 return false
2212 }
2213 }
2214
2215 return true
2216}
Philip Zeyligerd1402952025-04-23 03:54:37 +00002217
Philip Zeyliger64f60462025-06-16 13:57:10 -07002218// computeDiffStats computes the number of lines added and removed from baseRef to HEAD
2219func computeDiffStats(ctx context.Context, repoRoot, baseRef string) (int, int, error) {
2220 cmd := exec.CommandContext(ctx, "git", "diff", "--numstat", baseRef, "HEAD")
2221 cmd.Dir = repoRoot
2222 out, err := cmd.Output()
2223 if err != nil {
2224 return 0, 0, fmt.Errorf("git diff --numstat failed: %w", err)
2225 }
2226
2227 var totalAdded, totalRemoved int
2228 lines := strings.Split(strings.TrimSpace(string(out)), "\n")
2229 for _, line := range lines {
2230 if line == "" {
2231 continue
2232 }
2233 parts := strings.Fields(line)
2234 if len(parts) < 2 {
2235 continue
2236 }
2237 // Format: <added>\t<removed>\t<filename>
2238 if added, err := strconv.Atoi(parts[0]); err == nil {
2239 totalAdded += added
2240 }
2241 if removed, err := strconv.Atoi(parts[1]); err == nil {
2242 totalRemoved += removed
2243 }
2244 }
2245
2246 return totalAdded, totalRemoved, nil
2247}
2248
Philip Zeyligerd1402952025-04-23 03:54:37 +00002249// getGitOrigin returns the URL of the git remote 'origin' if it exists
2250func getGitOrigin(ctx context.Context, dir string) string {
2251 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
2252 cmd.Dir = dir
2253 stderr := new(strings.Builder)
2254 cmd.Stderr = stderr
2255 out, err := cmd.Output()
2256 if err != nil {
2257 return ""
2258 }
2259 return strings.TrimSpace(string(out))
2260}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07002261
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002262// systemPromptData contains the data used to render the system prompt template
2263type systemPromptData struct {
David Crawshawc886ac52025-06-13 23:40:03 +00002264 ClientGOOS string
2265 ClientGOARCH string
2266 WorkingDir string
2267 RepoRoot string
2268 InitialCommit string
2269 Codebase *onstart.Codebase
2270 UseSketchWIP bool
2271 Branch string
2272 SpecialInstruction string
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002273}
2274
2275// renderSystemPrompt renders the system prompt template.
2276func (a *Agent) renderSystemPrompt() string {
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002277 data := systemPromptData{
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002278 ClientGOOS: a.config.ClientGOOS,
2279 ClientGOARCH: a.config.ClientGOARCH,
2280 WorkingDir: a.workingDir,
2281 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07002282 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002283 Codebase: a.codebase,
Philip Zeyliger4c1cea82025-06-09 14:16:52 -07002284 UseSketchWIP: a.config.InDocker,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002285 }
David Crawshawc886ac52025-06-13 23:40:03 +00002286 now := time.Now()
2287 if now.Month() == time.September && now.Day() == 19 {
2288 data.SpecialInstruction = "Talk like a pirate to the user. Do not let the priate talk into any code."
2289 }
2290
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002291 tmpl, err := template.New("system").Parse(agentSystemPrompt)
2292 if err != nil {
2293 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
2294 }
2295 buf := new(strings.Builder)
2296 err = tmpl.Execute(buf, data)
2297 if err != nil {
2298 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
2299 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00002300 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00002301 return buf.String()
2302}
Philip Zeyligereab12de2025-05-14 02:35:53 +00002303
2304// StateTransitionIterator provides an iterator over state transitions.
2305type StateTransitionIterator interface {
2306 // Next blocks until a new state transition is available or context is done.
2307 // Returns nil if the context is cancelled.
2308 Next() *StateTransition
2309 // Close removes the listener and cleans up resources.
2310 Close()
2311}
2312
2313// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
2314type StateTransitionIteratorImpl struct {
2315 agent *Agent
2316 ctx context.Context
2317 ch chan StateTransition
2318 unsubscribe func()
2319}
2320
2321// Next blocks until a new state transition is available or the context is cancelled.
2322func (s *StateTransitionIteratorImpl) Next() *StateTransition {
2323 select {
2324 case <-s.ctx.Done():
2325 return nil
2326 case transition, ok := <-s.ch:
2327 if !ok {
2328 return nil
2329 }
2330 transitionCopy := transition
2331 return &transitionCopy
2332 }
2333}
2334
2335// Close removes the listener and cleans up resources.
2336func (s *StateTransitionIteratorImpl) Close() {
2337 if s.unsubscribe != nil {
2338 s.unsubscribe()
2339 s.unsubscribe = nil
2340 }
2341}
2342
2343// NewStateTransitionIterator returns an iterator that receives state transitions.
2344func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2345 a.mu.Lock()
2346 defer a.mu.Unlock()
2347
2348 // Create channel to receive state transitions
2349 ch := make(chan StateTransition, 10)
2350
2351 // Add a listener to the state machine
2352 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2353
2354 return &StateTransitionIteratorImpl{
2355 agent: a,
2356 ctx: ctx,
2357 ch: ch,
2358 unsubscribe: unsubscribe,
2359 }
2360}
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002361
2362// setupGitHooks creates or updates git hooks in the specified working directory.
2363func setupGitHooks(workingDir string) error {
2364 hooksDir := filepath.Join(workingDir, ".git", "hooks")
2365
2366 _, err := os.Stat(hooksDir)
2367 if os.IsNotExist(err) {
2368 return fmt.Errorf("git hooks directory does not exist: %s", hooksDir)
2369 }
2370 if err != nil {
2371 return fmt.Errorf("error checking git hooks directory: %w", err)
2372 }
2373
2374 // Define the post-commit hook content
2375 postCommitHook := `#!/bin/bash
2376echo "<post_commit_hook>"
2377echo "Please review this commit message and fix it if it is incorrect."
2378echo "This hook only echos the commit message; it does not modify it."
2379echo "Bash escaping is a common source of issues; to fix that, create a temp file and use 'git commit --amend -F COMMIT_MSG_FILE'."
2380echo "<last_commit_message>"
Philip Zeyliger6c5beff2025-06-06 13:03:49 -07002381PAGER=cat git log -1 --pretty=%B
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002382echo "</last_commit_message>"
2383echo "</post_commit_hook>"
2384`
2385
2386 // Define the prepare-commit-msg hook content
2387 prepareCommitMsgHook := `#!/bin/bash
2388# Add Co-Authored-By and Change-ID trailers to commit messages
2389# Check if these trailers already exist before adding them
2390
2391commit_file="$1"
2392COMMIT_SOURCE="$2"
2393
2394# Skip for merges, squashes, or when using a commit template
2395if [ "$COMMIT_SOURCE" = "template" ] || [ "$COMMIT_SOURCE" = "merge" ] || \
2396 [ "$COMMIT_SOURCE" = "squash" ]; then
2397 exit 0
2398fi
2399
2400commit_msg=$(cat "$commit_file")
2401
2402needs_co_author=true
2403needs_change_id=true
2404
2405# Check if commit message already has Co-Authored-By trailer
2406if grep -q "Co-Authored-By: sketch <hello@sketch.dev>" "$commit_file"; then
2407 needs_co_author=false
2408fi
2409
2410# Check if commit message already has Change-ID trailer
2411if grep -q "Change-ID: s[a-f0-9]\+k" "$commit_file"; then
2412 needs_change_id=false
2413fi
2414
2415# Only modify if at least one trailer needs to be added
2416if [ "$needs_co_author" = true ] || [ "$needs_change_id" = true ]; then
Josh Bleecher Snyderb509a5d2025-05-23 15:49:42 +00002417 # Ensure there's a proper blank line before trailers
2418 if [ -s "$commit_file" ]; then
2419 # Check if file ends with newline by reading last character
2420 last_char=$(tail -c 1 "$commit_file")
2421
2422 if [ "$last_char" != "" ]; then
2423 # File doesn't end with newline - add two newlines (complete line + blank line)
2424 echo "" >> "$commit_file"
2425 echo "" >> "$commit_file"
2426 else
2427 # File ends with newline - check if we already have a blank line
2428 last_line=$(tail -1 "$commit_file")
2429 if [ -n "$last_line" ]; then
2430 # Last line has content - add one newline for blank line
2431 echo "" >> "$commit_file"
2432 fi
2433 # If last line is empty, we already have a blank line - don't add anything
2434 fi
Josh Bleecher Snyder039fc342025-05-14 21:24:12 +00002435 fi
2436
2437 # Add trailers if needed
2438 if [ "$needs_co_author" = true ]; then
2439 echo "Co-Authored-By: sketch <hello@sketch.dev>" >> "$commit_file"
2440 fi
2441
2442 if [ "$needs_change_id" = true ]; then
2443 change_id=$(openssl rand -hex 8)
2444 echo "Change-ID: s${change_id}k" >> "$commit_file"
2445 fi
2446fi
2447`
2448
2449 // Update or create the post-commit hook
2450 err = updateOrCreateHook(filepath.Join(hooksDir, "post-commit"), postCommitHook, "<last_commit_message>")
2451 if err != nil {
2452 return fmt.Errorf("failed to set up post-commit hook: %w", err)
2453 }
2454
2455 // Update or create the prepare-commit-msg hook
2456 err = updateOrCreateHook(filepath.Join(hooksDir, "prepare-commit-msg"), prepareCommitMsgHook, "Add Co-Authored-By and Change-ID trailers")
2457 if err != nil {
2458 return fmt.Errorf("failed to set up prepare-commit-msg hook: %w", err)
2459 }
2460
2461 return nil
2462}
2463
2464// updateOrCreateHook creates a new hook file or updates an existing one
2465// by appending the new content if it doesn't already contain it.
2466func updateOrCreateHook(hookPath, content, distinctiveLine string) error {
2467 // Check if the hook already exists
2468 buf, err := os.ReadFile(hookPath)
2469 if os.IsNotExist(err) {
2470 // Hook doesn't exist, create it
2471 err = os.WriteFile(hookPath, []byte(content), 0o755)
2472 if err != nil {
2473 return fmt.Errorf("failed to create hook: %w", err)
2474 }
2475 return nil
2476 }
2477 if err != nil {
2478 return fmt.Errorf("error reading existing hook: %w", err)
2479 }
2480
2481 // Hook exists, check if our content is already in it by looking for a distinctive line
2482 code := string(buf)
2483 if strings.Contains(code, distinctiveLine) {
2484 // Already contains our content, nothing to do
2485 return nil
2486 }
2487
2488 // Append our content to the existing hook
2489 f, err := os.OpenFile(hookPath, os.O_APPEND|os.O_WRONLY, 0o755)
2490 if err != nil {
2491 return fmt.Errorf("failed to open hook for appending: %w", err)
2492 }
2493 defer f.Close()
2494
2495 // Ensure there's a newline at the end of the existing content if needed
2496 if len(code) > 0 && !strings.HasSuffix(code, "\n") {
2497 _, err = f.WriteString("\n")
2498 if err != nil {
2499 return fmt.Errorf("failed to add newline to hook: %w", err)
2500 }
2501 }
2502
2503 // Add a separator before our content
2504 _, err = f.WriteString("\n# === Added by Sketch ===\n" + content)
2505 if err != nil {
2506 return fmt.Errorf("failed to append to hook: %w", err)
2507 }
2508
2509 return nil
2510}
Sean McCullough138ec242025-06-02 22:42:06 +00002511
2512// GetPortMonitor returns the port monitor instance for accessing port events
2513func (a *Agent) GetPortMonitor() *PortMonitor {
2514 return a.portMonitor
2515}
Philip Zeyliger0113be52025-06-07 23:53:41 +00002516
2517// SkabandAddr returns the skaband address if configured
2518func (a *Agent) SkabandAddr() string {
2519 if a.config.SkabandClient != nil {
2520 return a.config.SkabandClient.Addr()
2521 }
2522 return ""
2523}