blob: 0c1f2ff47ba06db95f5be137e64bc4cf64eb23b9 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package loop
2
3import (
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07004 "cmp"
Earl Lee2e463fb2025-04-17 11:22:22 -07005 "context"
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -07006 _ "embed"
Earl Lee2e463fb2025-04-17 11:22:22 -07007 "encoding/json"
8 "fmt"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +00009 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070010 "log/slog"
11 "net/http"
12 "os"
13 "os/exec"
14 "runtime/debug"
15 "slices"
16 "strings"
17 "sync"
18 "time"
19
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +000020 "sketch.dev/browser"
Earl Lee2e463fb2025-04-17 11:22:22 -070021 "sketch.dev/claudetool"
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +000022 "sketch.dev/claudetool/bashkit"
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -070023 "sketch.dev/experiment"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070024 "sketch.dev/llm"
25 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070026)
27
28const (
29 userCancelMessage = "user requested agent to stop handling responses"
30)
31
Philip Zeyligerb7c58752025-05-01 10:10:17 -070032type MessageIterator interface {
33 // Next blocks until the next message is available. It may
34 // return nil if the underlying iterator context is done.
35 Next() *AgentMessage
36 Close()
37}
38
Earl Lee2e463fb2025-04-17 11:22:22 -070039type CodingAgent interface {
40 // Init initializes an agent inside a docker container.
41 Init(AgentInit) error
42
43 // Ready returns a channel closed after Init successfully called.
44 Ready() <-chan struct{}
45
46 // URL reports the HTTP URL of this agent.
47 URL() string
48
49 // UserMessage enqueues a message to the agent and returns immediately.
50 UserMessage(ctx context.Context, msg string)
51
Philip Zeyligerb7c58752025-05-01 10:10:17 -070052 // Returns an iterator that finishes when the context is done and
53 // starts with the given message index.
54 NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator
Earl Lee2e463fb2025-04-17 11:22:22 -070055
56 // Loop begins the agent loop returns only when ctx is cancelled.
57 Loop(ctx context.Context)
58
Sean McCulloughedc88dc2025-04-30 02:55:01 +000059 CancelTurn(cause error)
Earl Lee2e463fb2025-04-17 11:22:22 -070060
61 CancelToolUse(toolUseID string, cause error) error
62
63 // Returns a subset of the agent's message history.
64 Messages(start int, end int) []AgentMessage
65
66 // Returns the current number of messages in the history
67 MessageCount() int
68
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070069 TotalUsage() conversation.CumulativeUsage
70 OriginalBudget() conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -070071
Earl Lee2e463fb2025-04-17 11:22:22 -070072 WorkingDir() string
73
74 // Diff returns a unified diff of changes made since the agent was instantiated.
75 // If commit is non-nil, it shows the diff for just that specific commit.
76 Diff(commit *string) (string, error)
77
78 // InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
79 InitialCommit() string
80
81 // Title returns the current title of the conversation.
82 Title() string
83
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000084 // BranchName returns the git branch name for the conversation.
85 BranchName() string
86
Earl Lee2e463fb2025-04-17 11:22:22 -070087 // OS returns the operating system of the client.
88 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +000089
Philip Zeyligerc72fff52025-04-29 20:17:54 +000090 // SessionID returns the unique session identifier.
91 SessionID() string
92
Philip Zeyliger99a9a022025-04-27 15:15:25 +000093 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
94 OutstandingLLMCallCount() int
95
96 // OutstandingToolCalls returns the names of outstanding tool calls.
97 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +000098 OutsideOS() string
99 OutsideHostname() string
100 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000101 GitOrigin() string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000102 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
103 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700104
105 // RestartConversation resets the conversation history
106 RestartConversation(ctx context.Context, rev string, initialPrompt string) error
107 // SuggestReprompt suggests a re-prompt based on the current conversation.
108 SuggestReprompt(ctx context.Context) (string, error)
109 // IsInContainer returns true if the agent is running in a container
110 IsInContainer() bool
111 // FirstMessageIndex returns the index of the first message in the current conversation
112 FirstMessageIndex() int
Sean McCulloughd9d45812025-04-30 16:53:41 -0700113
114 CurrentStateName() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700115}
116
117type CodingAgentMessageType string
118
119const (
120 UserMessageType CodingAgentMessageType = "user"
121 AgentMessageType CodingAgentMessageType = "agent"
122 ErrorMessageType CodingAgentMessageType = "error"
123 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
124 ToolUseMessageType CodingAgentMessageType = "tool"
125 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
126 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
127
128 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
129)
130
131type AgentMessage struct {
132 Type CodingAgentMessageType `json:"type"`
133 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
134 EndOfTurn bool `json:"end_of_turn"`
135
136 Content string `json:"content"`
137 ToolName string `json:"tool_name,omitempty"`
138 ToolInput string `json:"input,omitempty"`
139 ToolResult string `json:"tool_result,omitempty"`
140 ToolError bool `json:"tool_error,omitempty"`
141 ToolCallId string `json:"tool_call_id,omitempty"`
142
143 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
144 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
145
Sean McCulloughd9f13372025-04-21 15:08:49 -0700146 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
147 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
148
Earl Lee2e463fb2025-04-17 11:22:22 -0700149 // Commits is a list of git commits for a commit message
150 Commits []*GitCommit `json:"commits,omitempty"`
151
152 Timestamp time.Time `json:"timestamp"`
153 ConversationID string `json:"conversation_id"`
154 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700155 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700156
157 // Message timing information
158 StartTime *time.Time `json:"start_time,omitempty"`
159 EndTime *time.Time `json:"end_time,omitempty"`
160 Elapsed *time.Duration `json:"elapsed,omitempty"`
161
162 // Turn duration - the time taken for a complete agent turn
163 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
164
165 Idx int `json:"idx"`
166}
167
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700168// SetConvo sets m.ConversationID and m.ParentConversationID based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700169func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700170 if convo == nil {
171 m.ConversationID = ""
172 m.ParentConversationID = nil
173 return
174 }
175 m.ConversationID = convo.ID
176 if convo.Parent != nil {
177 m.ParentConversationID = &convo.Parent.ID
178 }
179}
180
Earl Lee2e463fb2025-04-17 11:22:22 -0700181// GitCommit represents a single git commit for a commit message
182type GitCommit struct {
183 Hash string `json:"hash"` // Full commit hash
184 Subject string `json:"subject"` // Commit subject line
185 Body string `json:"body"` // Full commit message body
186 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
187}
188
189// ToolCall represents a single tool call within an agent message
190type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700191 Name string `json:"name"`
192 Input string `json:"input"`
193 ToolCallId string `json:"tool_call_id"`
194 ResultMessage *AgentMessage `json:"result_message,omitempty"`
195 Args string `json:"args,omitempty"`
196 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700197}
198
199func (a *AgentMessage) Attr() slog.Attr {
200 var attrs []any = []any{
201 slog.String("type", string(a.Type)),
202 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700203 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 if a.EndOfTurn {
205 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
206 }
207 if a.Content != "" {
208 attrs = append(attrs, slog.String("content", a.Content))
209 }
210 if a.ToolName != "" {
211 attrs = append(attrs, slog.String("tool_name", a.ToolName))
212 }
213 if a.ToolInput != "" {
214 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
215 }
216 if a.Elapsed != nil {
217 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
218 }
219 if a.TurnDuration != nil {
220 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
221 }
222 if a.ToolResult != "" {
223 attrs = append(attrs, slog.String("tool_result", a.ToolResult))
224 }
225 if a.ToolError {
226 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
227 }
228 if len(a.ToolCalls) > 0 {
229 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
230 for i, tc := range a.ToolCalls {
231 toolCallAttrs = append(toolCallAttrs, slog.Group(
232 fmt.Sprintf("tool_call_%d", i),
233 slog.String("name", tc.Name),
234 slog.String("input", tc.Input),
235 ))
236 }
237 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
238 }
239 if a.ConversationID != "" {
240 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
241 }
242 if a.ParentConversationID != nil {
243 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
244 }
245 if a.Usage != nil && !a.Usage.IsZero() {
246 attrs = append(attrs, a.Usage.Attr())
247 }
248 // TODO: timestamp, convo ids, idx?
249 return slog.Group("agent_message", attrs...)
250}
251
252func errorMessage(err error) AgentMessage {
253 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
254 if os.Getenv(("DEBUG")) == "1" {
255 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
256 }
257
258 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
259}
260
261func budgetMessage(err error) AgentMessage {
262 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
263}
264
265// ConvoInterface defines the interface for conversation interactions
266type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700267 CumulativeUsage() conversation.CumulativeUsage
268 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700270 SendMessage(message llm.Message) (*llm.Response, error)
271 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700272 GetID() string
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700273 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, error)
274 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700275 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700276 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700277}
278
279type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700280 convo ConvoInterface
281 config AgentConfig // config for this agent
282 workingDir string
283 repoRoot string // workingDir may be a subdir of repoRoot
284 url string
285 firstMessageIndex int // index of the first message in the current conversation
286 lastHEAD string // hash of the last HEAD that was pushed to the host (only when under docker)
287 initialCommit string // hash of the Git HEAD when the agent was instantiated or Init()
288 gitRemoteAddr string // HTTP URL of the host git repo (only when under docker)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000289 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700290 ready chan struct{} // closed when the agent is initialized (only when under docker)
291 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700292 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700293 title string
294 branchName string
295 codereview *claudetool.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700296 // State machine to track agent state
297 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000298 // Outside information
299 outsideHostname string
300 outsideOS string
301 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000302 // URL of the git remote 'origin' if it exists
303 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700304
305 // Time when the current turn started (reset at the beginning of InnerLoop)
306 startOfTurn time.Time
307
308 // Inbox - for messages from the user to the agent.
309 // sent on by UserMessage
310 // . e.g. when user types into the chat textarea
311 // read from by GatherMessages
312 inbox chan string
313
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000314 // protects cancelTurn
315 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000317 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700318
319 // protects following
320 mu sync.Mutex
321
322 // Stores all messages for this agent
323 history []AgentMessage
324
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700325 // Iterators add themselves here when they're ready to be notified of new messages.
326 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700327
328 // Track git commits we've already seen (by hash)
329 seenCommits map[string]bool
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000330
331 // Track outstanding LLM call IDs
332 outstandingLLMCalls map[string]struct{}
333
334 // Track outstanding tool calls by ID with their names
335 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700336}
337
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700338// NewIterator implements CodingAgent.
339func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
340 a.mu.Lock()
341 defer a.mu.Unlock()
342
343 return &MessageIteratorImpl{
344 agent: a,
345 ctx: ctx,
346 nextMessageIdx: nextMessageIdx,
347 ch: make(chan *AgentMessage, 100),
348 }
349}
350
351type MessageIteratorImpl struct {
352 agent *Agent
353 ctx context.Context
354 nextMessageIdx int
355 ch chan *AgentMessage
356 subscribed bool
357}
358
359func (m *MessageIteratorImpl) Close() {
360 m.agent.mu.Lock()
361 defer m.agent.mu.Unlock()
362 // Delete ourselves from the subscribers list
363 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
364 return x == m.ch
365 })
366 close(m.ch)
367}
368
369func (m *MessageIteratorImpl) Next() *AgentMessage {
370 // We avoid subscription at creation to let ourselves catch up to "current state"
371 // before subscribing.
372 if !m.subscribed {
373 m.agent.mu.Lock()
374 if m.nextMessageIdx < len(m.agent.history) {
375 msg := &m.agent.history[m.nextMessageIdx]
376 m.nextMessageIdx++
377 m.agent.mu.Unlock()
378 return msg
379 }
380 // The next message doesn't exist yet, so let's subscribe
381 m.agent.subscribers = append(m.agent.subscribers, m.ch)
382 m.subscribed = true
383 m.agent.mu.Unlock()
384 }
385
386 for {
387 select {
388 case <-m.ctx.Done():
389 m.agent.mu.Lock()
390 // Delete ourselves from the subscribers list
391 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
392 return x == m.ch
393 })
394 m.subscribed = false
395 m.agent.mu.Unlock()
396 return nil
397 case msg, ok := <-m.ch:
398 if !ok {
399 // Close may have been called
400 return nil
401 }
402 if msg.Idx == m.nextMessageIdx {
403 m.nextMessageIdx++
404 return msg
405 }
406 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
407 panic("out of order message")
408 }
409 }
410}
411
Sean McCulloughd9d45812025-04-30 16:53:41 -0700412// Assert that Agent satisfies the CodingAgent interface.
413var _ CodingAgent = &Agent{}
414
415// StateName implements CodingAgent.
416func (a *Agent) CurrentStateName() string {
417 if a.stateMachine == nil {
418 return ""
419 }
420 return a.stateMachine.currentState.String()
421}
422
Earl Lee2e463fb2025-04-17 11:22:22 -0700423func (a *Agent) URL() string { return a.url }
424
425// Title returns the current title of the conversation.
426// If no title has been set, returns an empty string.
427func (a *Agent) Title() string {
428 a.mu.Lock()
429 defer a.mu.Unlock()
430 return a.title
431}
432
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000433// BranchName returns the git branch name for the conversation.
434func (a *Agent) BranchName() string {
435 a.mu.Lock()
436 defer a.mu.Unlock()
437 return a.branchName
438}
439
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000440// OutstandingLLMCallCount returns the number of outstanding LLM calls.
441func (a *Agent) OutstandingLLMCallCount() int {
442 a.mu.Lock()
443 defer a.mu.Unlock()
444 return len(a.outstandingLLMCalls)
445}
446
447// OutstandingToolCalls returns the names of outstanding tool calls.
448func (a *Agent) OutstandingToolCalls() []string {
449 a.mu.Lock()
450 defer a.mu.Unlock()
451
452 tools := make([]string, 0, len(a.outstandingToolCalls))
453 for _, toolName := range a.outstandingToolCalls {
454 tools = append(tools, toolName)
455 }
456 return tools
457}
458
Earl Lee2e463fb2025-04-17 11:22:22 -0700459// OS returns the operating system of the client.
460func (a *Agent) OS() string {
461 return a.config.ClientGOOS
462}
463
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000464func (a *Agent) SessionID() string {
465 return a.config.SessionID
466}
467
Philip Zeyliger18532b22025-04-23 21:11:46 +0000468// OutsideOS returns the operating system of the outside system.
469func (a *Agent) OutsideOS() string {
470 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000471}
472
Philip Zeyliger18532b22025-04-23 21:11:46 +0000473// OutsideHostname returns the hostname of the outside system.
474func (a *Agent) OutsideHostname() string {
475 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000476}
477
Philip Zeyliger18532b22025-04-23 21:11:46 +0000478// OutsideWorkingDir returns the working directory on the outside system.
479func (a *Agent) OutsideWorkingDir() string {
480 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000481}
482
483// GitOrigin returns the URL of the git remote 'origin' if it exists.
484func (a *Agent) GitOrigin() string {
485 return a.gitOrigin
486}
487
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000488func (a *Agent) OpenBrowser(url string) {
489 if !a.IsInContainer() {
490 browser.Open(url)
491 return
492 }
493 // We're in Docker, need to send a request to the Git server
494 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700495 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000496 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700497 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000498 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700499 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000500 return
501 }
502 defer resp.Body.Close()
503 if resp.StatusCode == http.StatusOK {
504 return
505 }
506 body, _ := io.ReadAll(resp.Body)
507 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
508}
509
Sean McCullough96b60dd2025-04-30 09:49:10 -0700510// CurrentState returns the current state of the agent's state machine.
511func (a *Agent) CurrentState() State {
512 return a.stateMachine.CurrentState()
513}
514
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700515func (a *Agent) IsInContainer() bool {
516 return a.config.InDocker
517}
518
519func (a *Agent) FirstMessageIndex() int {
520 a.mu.Lock()
521 defer a.mu.Unlock()
522 return a.firstMessageIndex
523}
524
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700525// SetTitleBranch sets the title and branch name of the conversation.
526func (a *Agent) SetTitleBranch(title, branchName string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700527 a.mu.Lock()
528 defer a.mu.Unlock()
529 a.title = title
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700530 a.branchName = branchName
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700531
532 // TODO: We could potentially notify listeners of a state change, but,
533 // realistically, a new message will be sent for the tool result as well.
Earl Lee2e463fb2025-04-17 11:22:22 -0700534}
535
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000536// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700537func (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 +0000538 // Track the tool call
539 a.mu.Lock()
540 a.outstandingToolCalls[id] = toolName
541 a.mu.Unlock()
542}
543
Earl Lee2e463fb2025-04-17 11:22:22 -0700544// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700545func (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 +0000546 // Remove the tool call from outstanding calls
547 a.mu.Lock()
548 delete(a.outstandingToolCalls, toolID)
549 a.mu.Unlock()
550
Earl Lee2e463fb2025-04-17 11:22:22 -0700551 m := AgentMessage{
552 Type: ToolUseMessageType,
553 Content: content.Text,
554 ToolResult: content.ToolResult,
555 ToolError: content.ToolError,
556 ToolName: toolName,
557 ToolInput: string(toolInput),
558 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700559 StartTime: content.ToolUseStartTime,
560 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700561 }
562
563 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700564 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
565 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700566 m.Elapsed = &elapsed
567 }
568
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700569 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700570 a.pushToOutbox(ctx, m)
571}
572
573// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700574func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000575 a.mu.Lock()
576 defer a.mu.Unlock()
577 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700578 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
579}
580
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700581// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700582// that need to be displayed (as well as tool calls that we send along when
583// they're done). (It would be reasonable to also mention tool calls when they're
584// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700585func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000586 // Remove the LLM call from outstanding calls
587 a.mu.Lock()
588 delete(a.outstandingLLMCalls, id)
589 a.mu.Unlock()
590
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700591 if resp == nil {
592 // LLM API call failed
593 m := AgentMessage{
594 Type: ErrorMessageType,
595 Content: "API call failed, type 'continue' to try again",
596 }
597 m.SetConvo(convo)
598 a.pushToOutbox(ctx, m)
599 return
600 }
601
Earl Lee2e463fb2025-04-17 11:22:22 -0700602 endOfTurn := false
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700603 if resp.StopReason != llm.StopReasonToolUse && convo.Parent == nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700604 endOfTurn = true
605 }
606 m := AgentMessage{
607 Type: AgentMessageType,
608 Content: collectTextContent(resp),
609 EndOfTurn: endOfTurn,
610 Usage: &resp.Usage,
611 StartTime: resp.StartTime,
612 EndTime: resp.EndTime,
613 }
614
615 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700616 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700617 var toolCalls []ToolCall
618 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700619 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700620 toolCalls = append(toolCalls, ToolCall{
621 Name: part.ToolName,
622 Input: string(part.ToolInput),
623 ToolCallId: part.ID,
624 })
625 }
626 }
627 m.ToolCalls = toolCalls
628 }
629
630 // Calculate the elapsed time if both start and end times are set
631 if resp.StartTime != nil && resp.EndTime != nil {
632 elapsed := resp.EndTime.Sub(*resp.StartTime)
633 m.Elapsed = &elapsed
634 }
635
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700636 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700637 a.pushToOutbox(ctx, m)
638}
639
640// WorkingDir implements CodingAgent.
641func (a *Agent) WorkingDir() string {
642 return a.workingDir
643}
644
645// MessageCount implements CodingAgent.
646func (a *Agent) MessageCount() int {
647 a.mu.Lock()
648 defer a.mu.Unlock()
649 return len(a.history)
650}
651
652// Messages implements CodingAgent.
653func (a *Agent) Messages(start int, end int) []AgentMessage {
654 a.mu.Lock()
655 defer a.mu.Unlock()
656 return slices.Clone(a.history[start:end])
657}
658
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700659func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700660 return a.originalBudget
661}
662
663// AgentConfig contains configuration for creating a new Agent.
664type AgentConfig struct {
665 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700666 Service llm.Service
667 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700668 GitUsername string
669 GitEmail string
670 SessionID string
671 ClientGOOS string
672 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700673 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700674 UseAnthropicEdit bool
Philip Zeyliger18532b22025-04-23 21:11:46 +0000675 // Outside information
676 OutsideHostname string
677 OutsideOS string
678 OutsideWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -0700679}
680
681// NewAgent creates a new Agent.
682// It is not usable until Init() is called.
683func NewAgent(config AgentConfig) *Agent {
684 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000685 config: config,
686 ready: make(chan struct{}),
687 inbox: make(chan string, 100),
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700688 subscribers: make([]chan *AgentMessage, 0),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000689 startedAt: time.Now(),
690 originalBudget: config.Budget,
691 seenCommits: make(map[string]bool),
692 outsideHostname: config.OutsideHostname,
693 outsideOS: config.OutsideOS,
694 outsideWorkingDir: config.OutsideWorkingDir,
695 outstandingLLMCalls: make(map[string]struct{}),
696 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700697 stateMachine: NewStateMachine(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 }
699 return agent
700}
701
702type AgentInit struct {
703 WorkingDir string
704 NoGit bool // only for testing
705
706 InDocker bool
707 Commit string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000708 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700709 GitRemoteAddr string
710 HostAddr string
711}
712
713func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700714 if a.convo != nil {
715 return fmt.Errorf("Agent.Init: already initialized")
716 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 ctx := a.config.Context
718 if ini.InDocker {
719 cmd := exec.CommandContext(ctx, "git", "stash")
720 cmd.Dir = ini.WorkingDir
721 if out, err := cmd.CombinedOutput(); err != nil {
722 return fmt.Errorf("git stash: %s: %v", out, err)
723 }
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700724 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", ini.GitRemoteAddr)
725 cmd.Dir = ini.WorkingDir
726 if out, err := cmd.CombinedOutput(); err != nil {
727 return fmt.Errorf("git remote add: %s: %v", out, err)
728 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000729 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 cmd.Dir = ini.WorkingDir
731 if out, err := cmd.CombinedOutput(); err != nil {
732 return fmt.Errorf("git fetch: %s: %w", out, err)
733 }
734 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
735 cmd.Dir = ini.WorkingDir
736 if out, err := cmd.CombinedOutput(); err != nil {
737 return fmt.Errorf("git checkout %s: %s: %w", ini.Commit, out, err)
738 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700739 a.lastHEAD = ini.Commit
740 a.gitRemoteAddr = ini.GitRemoteAddr
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000741 a.outsideHTTP = ini.OutsideHTTP
Earl Lee2e463fb2025-04-17 11:22:22 -0700742 a.initialCommit = ini.Commit
743 if ini.HostAddr != "" {
744 a.url = "http://" + ini.HostAddr
745 }
746 }
747 a.workingDir = ini.WorkingDir
748
749 if !ini.NoGit {
750 repoRoot, err := repoRoot(ctx, a.workingDir)
751 if err != nil {
752 return fmt.Errorf("repoRoot: %w", err)
753 }
754 a.repoRoot = repoRoot
755
756 commitHash, err := resolveRef(ctx, a.repoRoot, "HEAD")
757 if err != nil {
758 return fmt.Errorf("resolveRef: %w", err)
759 }
760 a.initialCommit = commitHash
761
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -0700762 llmCodeReview := claudetool.NoLLMReview
763 if experiment.Enabled("llm_review") {
764 llmCodeReview = claudetool.DoLLMReview
765 }
766 codereview, err := claudetool.NewCodeReviewer(ctx, a.repoRoot, a.initialCommit, llmCodeReview)
Earl Lee2e463fb2025-04-17 11:22:22 -0700767 if err != nil {
768 return fmt.Errorf("Agent.Init: claudetool.NewCodeReviewer: %w", err)
769 }
770 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000771
772 a.gitOrigin = getGitOrigin(ctx, ini.WorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700773 }
774 a.lastHEAD = a.initialCommit
775 a.convo = a.initConvo()
776 close(a.ready)
777 return nil
778}
779
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700780//go:embed agent_system_prompt.txt
781var agentSystemPrompt string
782
Earl Lee2e463fb2025-04-17 11:22:22 -0700783// initConvo initializes the conversation.
784// It must not be called until all agent fields are initialized,
785// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700786func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700787 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700788 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700789 convo.PromptCaching = true
790 convo.Budget = a.config.Budget
791
792 var editPrompt string
793 if a.config.UseAnthropicEdit {
794 editPrompt = "Then use the str_replace_editor tool to make those edits. For short complete file replacements, you may use the bash tool with cat and heredoc stdin."
795 } else {
796 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
797 }
798
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700799 convo.SystemPrompt = fmt.Sprintf(agentSystemPrompt, editPrompt, a.config.ClientGOOS, a.config.ClientGOARCH, a.workingDir, a.repoRoot, a.initialCommit)
Earl Lee2e463fb2025-04-17 11:22:22 -0700800
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000801 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
802 bashPermissionCheck := func(command string) error {
803 // Check if branch name is set
804 a.mu.Lock()
805 branchSet := a.branchName != ""
806 a.mu.Unlock()
807
808 // If branch is set, all commands are allowed
809 if branchSet {
810 return nil
811 }
812
813 // If branch is not set, check if this is a git commit command
814 willCommit, err := bashkit.WillRunGitCommit(command)
815 if err != nil {
816 // If there's an error checking, we should allow the command to proceed
817 return nil
818 }
819
820 // If it's a git commit and branch is not set, return an error
821 if willCommit {
822 return fmt.Errorf("you must use the title tool before making git commits")
823 }
824
825 return nil
826 }
827
828 // Create a custom bash tool with the permission check
829 bashTool := claudetool.NewBashTool(bashPermissionCheck)
830
Earl Lee2e463fb2025-04-17 11:22:22 -0700831 // Register all tools with the conversation
832 // When adding, removing, or modifying tools here, double-check that the termui tool display
833 // template in termui/termui.go has pretty-printing support for all tools.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700834 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000835 bashTool, claudetool.Keyword,
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +0000836 claudetool.Think, a.preCommitTool(), makeDoneTool(a.codereview, a.config.GitUsername, a.config.GitEmail),
Sean McCullough485afc62025-04-28 14:28:39 -0700837 a.codereview.Tool(), a.multipleChoiceTool(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700838 }
839 if a.config.UseAnthropicEdit {
840 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
841 } else {
842 convo.Tools = append(convo.Tools, claudetool.Patch)
843 }
844 convo.Listener = a
845 return convo
846}
847
Sean McCullough485afc62025-04-28 14:28:39 -0700848func (a *Agent) multipleChoiceTool() *llm.Tool {
849 ret := &llm.Tool{
850 Name: "multiplechoice",
851 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.",
852 InputSchema: json.RawMessage(`{
853 "type": "object",
854 "description": "The question and a list of answers you would expect the user to choose from.",
855 "properties": {
856 "question": {
857 "type": "string",
858 "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?'"
859 },
860 "responseOptions": {
861 "type": "array",
862 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
863 "items": {
864 "type": "object",
865 "properties": {
866 "caption": {
867 "type": "string",
868 "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'"
869 },
870 "responseText": {
871 "type": "string",
872 "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'"
873 }
874 },
875 "required": ["caption", "responseText"]
876 }
877 }
878 },
879 "required": ["question", "responseOptions"]
880}`),
881 Run: func(ctx context.Context, input json.RawMessage) (string, error) {
882 // The Run logic for "multiplchoice" tool is a no-op on the server.
883 // The UI will present a list of options for the user to select from,
884 // and that's it as far as "executing" the tool_use goes.
885 // When the user *does* select one of the presented options, that
886 // responseText gets sent as a chat message on behalf of the user.
887 return "end your turn and wait for the user to respond", nil
888 },
889 }
890 return ret
891}
892
893type MultipleChoiceOption struct {
894 Caption string `json:"caption"`
895 ResponseText string `json:"responseText"`
896}
897
898type MultipleChoiceParams struct {
899 Question string `json:"question"`
900 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
901}
902
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +0000903// branchExists reports whether branchName exists, either locally or in well-known remotes.
904func branchExists(dir, branchName string) bool {
905 refs := []string{
906 "refs/heads/",
907 "refs/remotes/origin/",
908 "refs/remotes/sketch-host/",
909 }
910 for _, ref := range refs {
911 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
912 cmd.Dir = dir
913 if cmd.Run() == nil { // exit code 0 means branch exists
914 return true
915 }
916 }
917 return false
918}
919
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +0000920func (a *Agent) preCommitTool() *llm.Tool {
921 name := "title"
922 description := `Sets the conversation title and creates a git branch for tracking work. MANDATORY: You must use this tool before making any git commits.`
923 if experiment.Enabled("precommit") {
924 name = "precommit"
925 description = `Sets the conversation title, creates a git branch for tracking work, and provides git commit message style guidance. MANDATORY: You must use this tool before making any git commits.`
926 }
927 preCommit := &llm.Tool{
928 Name: name,
929 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -0700930 InputSchema: json.RawMessage(`{
931 "type": "object",
932 "properties": {
933 "title": {
934 "type": "string",
Josh Bleecher Snyder250348e2025-04-30 10:31:28 -0700935 "description": "A concise title summarizing what this conversation is about, imperative tense preferred"
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700936 },
937 "branch_name": {
938 "type": "string",
939 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
Earl Lee2e463fb2025-04-17 11:22:22 -0700940 }
941 },
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700942 "required": ["title", "branch_name"]
Earl Lee2e463fb2025-04-17 11:22:22 -0700943}`),
944 Run: func(ctx context.Context, input json.RawMessage) (string, error) {
945 var params struct {
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700946 Title string `json:"title"`
947 BranchName string `json:"branch_name"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700948 }
949 if err := json.Unmarshal(input, &params); err != nil {
950 return "", err
951 }
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700952 // It's unfortunate to not allow title changes,
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +0000953 // but it avoids accidentally generating multiple branches.
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700954 t := a.Title()
955 if t != "" {
956 return "", fmt.Errorf("title already set to: %s", t)
957 }
958
959 if params.BranchName == "" {
960 return "", fmt.Errorf("branch_name parameter cannot be empty")
961 }
962 if params.Title == "" {
963 return "", fmt.Errorf("title parameter cannot be empty")
964 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -0700965 if params.BranchName != cleanBranchName(params.BranchName) {
966 return "", fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
967 }
968 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +0000969 if branchExists(a.workingDir, branchName) {
970 return "", fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
971 }
972
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700973 a.SetTitleBranch(params.Title, branchName)
974
975 response := fmt.Sprintf("Title set to %q, branch name set to %q", params.Title, branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +0000976
977 if experiment.Enabled("precommit") {
978 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
979 if err != nil {
980 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
981 }
982 if len(styleHint) > 0 {
983 response += "\n\n" + styleHint
984 }
985 }
986
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700987 return response, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700988 },
989 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +0000990 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -0700991}
992
993func (a *Agent) Ready() <-chan struct{} {
994 return a.ready
995}
996
997func (a *Agent) UserMessage(ctx context.Context, msg string) {
998 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
999 a.inbox <- msg
1000}
1001
Sean McCullough485afc62025-04-28 14:28:39 -07001002func (a *Agent) ToolResultMessage(ctx context.Context, toolCallID, msg string) {
1003 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg, ToolCallId: toolCallID})
1004 a.inbox <- msg
1005}
1006
Earl Lee2e463fb2025-04-17 11:22:22 -07001007func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1008 return a.convo.CancelToolUse(toolUseID, cause)
1009}
1010
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001011func (a *Agent) CancelTurn(cause error) {
1012 a.cancelTurnMu.Lock()
1013 defer a.cancelTurnMu.Unlock()
1014 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001015 // Force state transition to cancelled state
1016 ctx := a.config.Context
1017 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001018 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001019 }
1020}
1021
1022func (a *Agent) Loop(ctxOuter context.Context) {
1023 for {
1024 select {
1025 case <-ctxOuter.Done():
1026 return
1027 default:
1028 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001029 a.cancelTurnMu.Lock()
1030 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001031 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001032 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001033 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001034 a.cancelTurn = cancel
1035 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001036 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1037 if err != nil {
1038 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1039 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001040 cancel(nil)
1041 }
1042 }
1043}
1044
1045func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1046 if m.Timestamp.IsZero() {
1047 m.Timestamp = time.Now()
1048 }
1049
1050 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1051 if m.EndOfTurn && m.Type == AgentMessageType {
1052 turnDuration := time.Since(a.startOfTurn)
1053 m.TurnDuration = &turnDuration
1054 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1055 }
1056
Earl Lee2e463fb2025-04-17 11:22:22 -07001057 a.mu.Lock()
1058 defer a.mu.Unlock()
1059 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001060 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001061 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001062
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001063 // Notify all subscribers
1064 for _, ch := range a.subscribers {
1065 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001066 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001067}
1068
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001069func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1070 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001071 if block {
1072 select {
1073 case <-ctx.Done():
1074 return m, ctx.Err()
1075 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001076 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001077 }
1078 }
1079 for {
1080 select {
1081 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001082 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001083 default:
1084 return m, nil
1085 }
1086 }
1087}
1088
Sean McCullough885a16a2025-04-30 02:49:25 +00001089// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001090func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001091 // Reset the start of turn time
1092 a.startOfTurn = time.Now()
1093
Sean McCullough96b60dd2025-04-30 09:49:10 -07001094 // Transition to waiting for user input state
1095 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1096
Sean McCullough885a16a2025-04-30 02:49:25 +00001097 // Process initial user message
1098 initialResp, err := a.processUserMessage(ctx)
1099 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001100 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001101 return err
1102 }
1103
1104 // Handle edge case where both initialResp and err are nil
1105 if initialResp == nil {
1106 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001107 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1108
Sean McCullough9f4b8082025-04-30 17:34:07 +00001109 a.pushToOutbox(ctx, errorMessage(err))
1110 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001111 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001112
Earl Lee2e463fb2025-04-17 11:22:22 -07001113 // We do this as we go, but let's also do it at the end of the turn
1114 defer func() {
1115 if _, err := a.handleGitCommits(ctx); err != nil {
1116 // Just log the error, don't stop execution
1117 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1118 }
1119 }()
1120
Sean McCullougha1e0e492025-05-01 10:51:08 -07001121 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001122 resp := initialResp
1123 for {
1124 // Check if we are over budget
1125 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001126 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001127 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001128 }
1129
1130 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001131 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001132 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001133 break
1134 }
1135
Sean McCullough96b60dd2025-04-30 09:49:10 -07001136 // Transition to tool use requested state
1137 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1138
Sean McCullough885a16a2025-04-30 02:49:25 +00001139 // Handle tool execution
1140 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1141 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001142 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001143 }
1144
Sean McCullougha1e0e492025-05-01 10:51:08 -07001145 if toolResp == nil {
1146 return fmt.Errorf("cannot continue conversation with a nil tool response")
1147 }
1148
Sean McCullough885a16a2025-04-30 02:49:25 +00001149 // Set the response for the next iteration
1150 resp = toolResp
1151 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001152
1153 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001154}
1155
1156// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001157func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001158 // Wait for at least one message from the user
1159 msgs, err := a.GatherMessages(ctx, true)
1160 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001161 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001162 return nil, err
1163 }
1164
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001165 userMessage := llm.Message{
1166 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001167 Content: msgs,
1168 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001169
Sean McCullough96b60dd2025-04-30 09:49:10 -07001170 // Transition to sending to LLM state
1171 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1172
Sean McCullough885a16a2025-04-30 02:49:25 +00001173 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001174 resp, err := a.convo.SendMessage(userMessage)
1175 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001176 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001177 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001178 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001179 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001180
Sean McCullough96b60dd2025-04-30 09:49:10 -07001181 // Transition to processing LLM response state
1182 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1183
Sean McCullough885a16a2025-04-30 02:49:25 +00001184 return resp, nil
1185}
1186
1187// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001188func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1189 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001190 cancelled := false
1191
Sean McCullough96b60dd2025-04-30 09:49:10 -07001192 // Transition to checking for cancellation state
1193 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1194
Sean McCullough885a16a2025-04-30 02:49:25 +00001195 // Check if the operation was cancelled by the user
1196 select {
1197 case <-ctx.Done():
1198 // Don't actually run any of the tools, but rather build a response
1199 // for each tool_use message letting the LLM know that user canceled it.
1200 var err error
1201 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001202 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001203 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001204 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001205 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001206 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001207 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001208 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001209 // Transition to running tool state
1210 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1211
Sean McCullough885a16a2025-04-30 02:49:25 +00001212 // Add working directory to context for tool execution
1213 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1214
1215 // Execute the tools
1216 var err error
1217 results, err = a.convo.ToolResultContents(ctx, resp)
1218 if ctx.Err() != nil { // e.g. the user canceled the operation
1219 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001220 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001221 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001222 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001223 a.pushToOutbox(ctx, errorMessage(err))
1224 }
1225 }
1226
1227 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001228 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001229 autoqualityMessages := a.processGitChanges(ctx)
1230
1231 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001232 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001233 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001234 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001235 return false, nil
1236 }
1237
1238 // Continue the conversation with tool results and any user messages
1239 return a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1240}
1241
1242// processGitChanges checks for new git commits and runs autoformatters if needed
1243func (a *Agent) processGitChanges(ctx context.Context) []string {
1244 // Check for git commits after tool execution
1245 newCommits, err := a.handleGitCommits(ctx)
1246 if err != nil {
1247 // Just log the error, don't stop execution
1248 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1249 return nil
1250 }
1251
1252 // Run autoformatters if there was exactly one new commit
1253 var autoqualityMessages []string
1254 if len(newCommits) == 1 {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001255 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running autoformatters on new commit")
Sean McCullough885a16a2025-04-30 02:49:25 +00001256 formatted := a.codereview.Autoformat(ctx)
1257 if len(formatted) > 0 {
1258 msg := fmt.Sprintf(`
Earl Lee2e463fb2025-04-17 11:22:22 -07001259I ran autoformatters and they updated these files:
1260
1261%s
1262
1263Please amend your latest git commit with these changes and then continue with what you were doing.`,
Sean McCullough885a16a2025-04-30 02:49:25 +00001264 strings.Join(formatted, "\n"),
1265 )[1:]
1266 a.pushToOutbox(ctx, AgentMessage{
1267 Type: AutoMessageType,
1268 Content: msg,
1269 Timestamp: time.Now(),
1270 })
1271 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001272 }
1273 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001274
1275 return autoqualityMessages
1276}
1277
1278// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001279func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001280 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001281 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001282 msgs, err := a.GatherMessages(ctx, false)
1283 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001284 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001285 return false, nil
1286 }
1287
1288 // Inject any auto-generated messages from quality checks
1289 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001290 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001291 }
1292
1293 // Handle cancellation by appending a message about it
1294 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001295 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001296 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001297 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001298 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1299 } else if err := a.convo.OverBudget(); err != nil {
1300 // Handle budget issues by appending a message about it
1301 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 -07001302 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001303 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1304 }
1305
1306 // Combine tool results with user messages
1307 results = append(results, msgs...)
1308
1309 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001310 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001311 resp, err := a.convo.SendMessage(llm.Message{
1312 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001313 Content: results,
1314 })
1315 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001316 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001317 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1318 return true, nil // Return true to continue the conversation, but with no response
1319 }
1320
Sean McCullough96b60dd2025-04-30 09:49:10 -07001321 // Transition back to processing LLM response
1322 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1323
Sean McCullough885a16a2025-04-30 02:49:25 +00001324 if cancelled {
1325 return false, nil
1326 }
1327
1328 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001329}
1330
1331func (a *Agent) overBudget(ctx context.Context) error {
1332 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001333 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001334 m := budgetMessage(err)
1335 m.Content = m.Content + "\n\nBudget reset."
1336 a.pushToOutbox(ctx, budgetMessage(err))
1337 a.convo.ResetBudget(a.originalBudget)
1338 return err
1339 }
1340 return nil
1341}
1342
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001343func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001344 // Collect all text content
1345 var allText strings.Builder
1346 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001347 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001348 if allText.Len() > 0 {
1349 allText.WriteString("\n\n")
1350 }
1351 allText.WriteString(content.Text)
1352 }
1353 }
1354 return allText.String()
1355}
1356
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001357func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001358 a.mu.Lock()
1359 defer a.mu.Unlock()
1360 return a.convo.CumulativeUsage()
1361}
1362
Earl Lee2e463fb2025-04-17 11:22:22 -07001363// Diff returns a unified diff of changes made since the agent was instantiated.
1364func (a *Agent) Diff(commit *string) (string, error) {
1365 if a.initialCommit == "" {
1366 return "", fmt.Errorf("no initial commit reference available")
1367 }
1368
1369 // Find the repository root
1370 ctx := context.Background()
1371
1372 // If a specific commit hash is provided, show just that commit's changes
1373 if commit != nil && *commit != "" {
1374 // Validate that the commit looks like a valid git SHA
1375 if !isValidGitSHA(*commit) {
1376 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1377 }
1378
1379 // Get the diff for just this commit
1380 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1381 cmd.Dir = a.repoRoot
1382 output, err := cmd.CombinedOutput()
1383 if err != nil {
1384 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1385 }
1386 return string(output), nil
1387 }
1388
1389 // Otherwise, get the diff between the initial commit and the current state using exec.Command
1390 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.initialCommit)
1391 cmd.Dir = a.repoRoot
1392 output, err := cmd.CombinedOutput()
1393 if err != nil {
1394 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1395 }
1396
1397 return string(output), nil
1398}
1399
1400// InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
1401func (a *Agent) InitialCommit() string {
1402 return a.initialCommit
1403}
1404
1405// handleGitCommits() highlights new commits to the user. When running
1406// under docker, new HEADs are pushed to a branch according to the title.
1407func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1408 if a.repoRoot == "" {
1409 return nil, nil
1410 }
1411
1412 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1413 if err != nil {
1414 return nil, err
1415 }
1416 if head == a.lastHEAD {
1417 return nil, nil // nothing to do
1418 }
1419 defer func() {
1420 a.lastHEAD = head
1421 }()
1422
1423 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1424 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1425 // to the last 100 commits.
1426 var commits []*GitCommit
1427
1428 // Get commits since the initial commit
1429 // Format: <hash>\0<subject>\0<body>\0
1430 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1431 // Limit to 100 commits to avoid overwhelming the user
1432 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+a.initialCommit, head)
1433 cmd.Dir = a.repoRoot
1434 output, err := cmd.Output()
1435 if err != nil {
1436 return nil, fmt.Errorf("failed to get git log: %w", err)
1437 }
1438
1439 // Parse git log output and filter out already seen commits
1440 parsedCommits := parseGitLog(string(output))
1441
1442 var headCommit *GitCommit
1443
1444 // Filter out commits we've already seen
1445 for _, commit := range parsedCommits {
1446 if commit.Hash == head {
1447 headCommit = &commit
1448 }
1449
1450 // Skip if we've seen this commit before. If our head has changed, always include that.
1451 if a.seenCommits[commit.Hash] && commit.Hash != head {
1452 continue
1453 }
1454
1455 // Mark this commit as seen
1456 a.seenCommits[commit.Hash] = true
1457
1458 // Add to our list of new commits
1459 commits = append(commits, &commit)
1460 }
1461
1462 if a.gitRemoteAddr != "" {
1463 if headCommit == nil {
1464 // I think this can only happen if we have a bug or if there's a race.
1465 headCommit = &GitCommit{}
1466 headCommit.Hash = head
1467 headCommit.Subject = "unknown"
1468 commits = append(commits, headCommit)
1469 }
1470
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001471 branch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
Earl Lee2e463fb2025-04-17 11:22:22 -07001472
1473 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1474 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1475 // then use push with lease to replace.
1476 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1477 cmd.Dir = a.workingDir
1478 if out, err := cmd.CombinedOutput(); err != nil {
1479 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1480 } else {
1481 headCommit.PushedBranch = branch
1482 }
1483 }
1484
1485 // If we found new commits, create a message
1486 if len(commits) > 0 {
1487 msg := AgentMessage{
1488 Type: CommitMessageType,
1489 Timestamp: time.Now(),
1490 Commits: commits,
1491 }
1492 a.pushToOutbox(ctx, msg)
1493 }
1494 return commits, nil
1495}
1496
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001497func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001498 return strings.Map(func(r rune) rune {
1499 // lowercase
1500 if r >= 'A' && r <= 'Z' {
1501 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001502 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001503 // replace spaces with dashes
1504 if r == ' ' {
1505 return '-'
1506 }
1507 // allow alphanumerics and dashes
1508 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1509 return r
1510 }
1511 return -1
1512 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001513}
1514
1515// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1516// and returns an array of GitCommit structs.
1517func parseGitLog(output string) []GitCommit {
1518 var commits []GitCommit
1519
1520 // No output means no commits
1521 if len(output) == 0 {
1522 return commits
1523 }
1524
1525 // Split by NULL byte
1526 parts := strings.Split(output, "\x00")
1527
1528 // Process in triplets (hash, subject, body)
1529 for i := 0; i < len(parts); i++ {
1530 // Skip empty parts
1531 if parts[i] == "" {
1532 continue
1533 }
1534
1535 // This should be a hash
1536 hash := strings.TrimSpace(parts[i])
1537
1538 // Make sure we have at least a subject part available
1539 if i+1 >= len(parts) {
1540 break // No more parts available
1541 }
1542
1543 // Get the subject
1544 subject := strings.TrimSpace(parts[i+1])
1545
1546 // Get the body if available
1547 body := ""
1548 if i+2 < len(parts) {
1549 body = strings.TrimSpace(parts[i+2])
1550 }
1551
1552 // Skip to the next triplet
1553 i += 2
1554
1555 commits = append(commits, GitCommit{
1556 Hash: hash,
1557 Subject: subject,
1558 Body: body,
1559 })
1560 }
1561
1562 return commits
1563}
1564
1565func repoRoot(ctx context.Context, dir string) (string, error) {
1566 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1567 stderr := new(strings.Builder)
1568 cmd.Stderr = stderr
1569 cmd.Dir = dir
1570 out, err := cmd.Output()
1571 if err != nil {
1572 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1573 }
1574 return strings.TrimSpace(string(out)), nil
1575}
1576
1577func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1578 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1579 stderr := new(strings.Builder)
1580 cmd.Stderr = stderr
1581 cmd.Dir = dir
1582 out, err := cmd.Output()
1583 if err != nil {
1584 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1585 }
1586 // TODO: validate that out is valid hex
1587 return strings.TrimSpace(string(out)), nil
1588}
1589
1590// isValidGitSHA validates if a string looks like a valid git SHA hash.
1591// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1592func isValidGitSHA(sha string) bool {
1593 // Git SHA must be a hexadecimal string with at least 4 characters
1594 if len(sha) < 4 || len(sha) > 40 {
1595 return false
1596 }
1597
1598 // Check if the string only contains hexadecimal characters
1599 for _, char := range sha {
1600 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1601 return false
1602 }
1603 }
1604
1605 return true
1606}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001607
1608// getGitOrigin returns the URL of the git remote 'origin' if it exists
1609func getGitOrigin(ctx context.Context, dir string) string {
1610 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1611 cmd.Dir = dir
1612 stderr := new(strings.Builder)
1613 cmd.Stderr = stderr
1614 out, err := cmd.Output()
1615 if err != nil {
1616 return ""
1617 }
1618 return strings.TrimSpace(string(out))
1619}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001620
1621func (a *Agent) initGitRevision(ctx context.Context, workingDir, revision string) error {
1622 cmd := exec.CommandContext(ctx, "git", "stash")
1623 cmd.Dir = workingDir
1624 if out, err := cmd.CombinedOutput(); err != nil {
1625 return fmt.Errorf("git stash: %s: %v", out, err)
1626 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +00001627 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001628 cmd.Dir = workingDir
1629 if out, err := cmd.CombinedOutput(); err != nil {
1630 return fmt.Errorf("git fetch: %s: %w", out, err)
1631 }
1632 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", revision)
1633 cmd.Dir = workingDir
1634 if out, err := cmd.CombinedOutput(); err != nil {
1635 return fmt.Errorf("git checkout %s: %s: %w", revision, out, err)
1636 }
1637 a.lastHEAD = revision
1638 a.initialCommit = revision
1639 return nil
1640}
1641
1642func (a *Agent) RestartConversation(ctx context.Context, rev string, initialPrompt string) error {
1643 a.mu.Lock()
1644 a.title = ""
1645 a.firstMessageIndex = len(a.history)
1646 a.convo = a.initConvo()
1647 gitReset := func() error {
1648 if a.config.InDocker && rev != "" {
1649 err := a.initGitRevision(ctx, a.workingDir, rev)
1650 if err != nil {
1651 return err
1652 }
1653 } else if !a.config.InDocker && rev != "" {
1654 return fmt.Errorf("Not resetting git repo when working outside of a container.")
1655 }
1656 return nil
1657 }
1658 err := gitReset()
1659 a.mu.Unlock()
1660 if err != nil {
1661 a.pushToOutbox(a.config.Context, errorMessage(err))
1662 }
1663
1664 a.pushToOutbox(a.config.Context, AgentMessage{
1665 Type: AgentMessageType, Content: "Conversation restarted.",
1666 })
1667 if initialPrompt != "" {
1668 a.UserMessage(ctx, initialPrompt)
1669 }
1670 return nil
1671}
1672
1673func (a *Agent) SuggestReprompt(ctx context.Context) (string, error) {
1674 msg := `The user has requested a suggestion for a re-prompt.
1675
1676 Given the current conversation thus far, suggest a re-prompt that would
1677 capture the instructions and feedback so far, as well as any
1678 research or other information that would be helpful in implementing
1679 the task.
1680
1681 Reply with ONLY the reprompt text.
1682 `
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001683 userMessage := llm.UserStringMessage(msg)
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001684 // By doing this in a subconversation, the agent doesn't call tools (because
1685 // there aren't any), and there's not a concurrency risk with on-going other
1686 // outstanding conversations.
1687 convo := a.convo.SubConvoWithHistory()
1688 resp, err := convo.SendMessage(userMessage)
1689 if err != nil {
1690 a.pushToOutbox(ctx, errorMessage(err))
1691 return "", err
1692 }
1693 textContent := collectTextContent(resp)
1694 return textContent, nil
1695}