blob: 05179eb895f1e9622ac8a621477a7c6037cc4ba1 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package loop
2
3import (
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07004 "cmp"
Earl Lee2e463fb2025-04-17 11:22:22 -07005 "context"
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -07006 _ "embed"
Earl Lee2e463fb2025-04-17 11:22:22 -07007 "encoding/json"
8 "fmt"
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +00009 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070010 "log/slog"
11 "net/http"
12 "os"
13 "os/exec"
Pokey Rule7a113622025-05-12 10:58:45 +010014 "path/filepath"
Earl Lee2e463fb2025-04-17 11:22:22 -070015 "runtime/debug"
16 "slices"
17 "strings"
18 "sync"
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +000019 "text/template"
Earl Lee2e463fb2025-04-17 11:22:22 -070020 "time"
21
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +000022 "sketch.dev/browser"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "sketch.dev/claudetool"
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +000024 "sketch.dev/claudetool/bashkit"
Autoformatter4962f152025-05-06 17:24:20 +000025 "sketch.dev/claudetool/browse"
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +000026 "sketch.dev/claudetool/codereview"
Josh Bleecher Snydera997be62025-05-07 22:52:46 +000027 "sketch.dev/claudetool/onstart"
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -070028 "sketch.dev/experiment"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070029 "sketch.dev/llm"
Philip Zeyliger72252cb2025-05-10 17:00:08 -070030 "sketch.dev/llm/ant"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070031 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070032)
33
34const (
35 userCancelMessage = "user requested agent to stop handling responses"
36)
37
Philip Zeyligerb7c58752025-05-01 10:10:17 -070038type MessageIterator interface {
39 // Next blocks until the next message is available. It may
40 // return nil if the underlying iterator context is done.
41 Next() *AgentMessage
42 Close()
43}
44
Earl Lee2e463fb2025-04-17 11:22:22 -070045type CodingAgent interface {
46 // Init initializes an agent inside a docker container.
47 Init(AgentInit) error
48
49 // Ready returns a channel closed after Init successfully called.
50 Ready() <-chan struct{}
51
52 // URL reports the HTTP URL of this agent.
53 URL() string
54
55 // UserMessage enqueues a message to the agent and returns immediately.
56 UserMessage(ctx context.Context, msg string)
57
Philip Zeyligerb7c58752025-05-01 10:10:17 -070058 // Returns an iterator that finishes when the context is done and
59 // starts with the given message index.
60 NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator
Earl Lee2e463fb2025-04-17 11:22:22 -070061
Philip Zeyligereab12de2025-05-14 02:35:53 +000062 // Returns an iterator that notifies of state transitions until the context is done.
63 NewStateTransitionIterator(ctx context.Context) StateTransitionIterator
64
Earl Lee2e463fb2025-04-17 11:22:22 -070065 // Loop begins the agent loop returns only when ctx is cancelled.
66 Loop(ctx context.Context)
67
Sean McCulloughedc88dc2025-04-30 02:55:01 +000068 CancelTurn(cause error)
Earl Lee2e463fb2025-04-17 11:22:22 -070069
70 CancelToolUse(toolUseID string, cause error) error
71
72 // Returns a subset of the agent's message history.
73 Messages(start int, end int) []AgentMessage
74
75 // Returns the current number of messages in the history
76 MessageCount() int
77
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070078 TotalUsage() conversation.CumulativeUsage
79 OriginalBudget() conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -070080
Earl Lee2e463fb2025-04-17 11:22:22 -070081 WorkingDir() string
82
83 // Diff returns a unified diff of changes made since the agent was instantiated.
84 // If commit is non-nil, it shows the diff for just that specific commit.
85 Diff(commit *string) (string, error)
86
Philip Zeyliger49edc922025-05-14 09:45:45 -070087 // SketchGitBase returns the commit that's the "base" for Sketch's work. It
88 // starts out as the commit where sketch started, but a user can move it if need
89 // be, for example in the case of a rebase. It is stored as a git tag.
90 SketchGitBase() string
Earl Lee2e463fb2025-04-17 11:22:22 -070091
92 // Title returns the current title of the conversation.
93 Title() string
94
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000095 // BranchName returns the git branch name for the conversation.
96 BranchName() string
97
Earl Lee2e463fb2025-04-17 11:22:22 -070098 // OS returns the operating system of the client.
99 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000100
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000101 // SessionID returns the unique session identifier.
102 SessionID() string
103
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000104 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
105 OutstandingLLMCallCount() int
106
107 // OutstandingToolCalls returns the names of outstanding tool calls.
108 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +0000109 OutsideOS() string
110 OutsideHostname() string
111 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000112 GitOrigin() string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000113 // OpenBrowser is a best-effort attempt to open a browser at url in outside sketch.
114 OpenBrowser(url string)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700115
116 // RestartConversation resets the conversation history
117 RestartConversation(ctx context.Context, rev string, initialPrompt string) error
118 // SuggestReprompt suggests a re-prompt based on the current conversation.
119 SuggestReprompt(ctx context.Context) (string, error)
120 // IsInContainer returns true if the agent is running in a container
121 IsInContainer() bool
122 // FirstMessageIndex returns the index of the first message in the current conversation
123 FirstMessageIndex() int
Sean McCulloughd9d45812025-04-30 16:53:41 -0700124
125 CurrentStateName() string
Earl Lee2e463fb2025-04-17 11:22:22 -0700126}
127
128type CodingAgentMessageType string
129
130const (
131 UserMessageType CodingAgentMessageType = "user"
132 AgentMessageType CodingAgentMessageType = "agent"
133 ErrorMessageType CodingAgentMessageType = "error"
134 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
135 ToolUseMessageType CodingAgentMessageType = "tool"
136 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
137 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
138
139 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
140)
141
142type AgentMessage struct {
143 Type CodingAgentMessageType `json:"type"`
144 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
145 EndOfTurn bool `json:"end_of_turn"`
146
147 Content string `json:"content"`
148 ToolName string `json:"tool_name,omitempty"`
149 ToolInput string `json:"input,omitempty"`
150 ToolResult string `json:"tool_result,omitempty"`
151 ToolError bool `json:"tool_error,omitempty"`
152 ToolCallId string `json:"tool_call_id,omitempty"`
153
154 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
155 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
156
Sean McCulloughd9f13372025-04-21 15:08:49 -0700157 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
158 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
159
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 // Commits is a list of git commits for a commit message
161 Commits []*GitCommit `json:"commits,omitempty"`
162
163 Timestamp time.Time `json:"timestamp"`
164 ConversationID string `json:"conversation_id"`
165 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700166 Usage *llm.Usage `json:"usage,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700167
168 // Message timing information
169 StartTime *time.Time `json:"start_time,omitempty"`
170 EndTime *time.Time `json:"end_time,omitempty"`
171 Elapsed *time.Duration `json:"elapsed,omitempty"`
172
173 // Turn duration - the time taken for a complete agent turn
174 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
175
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000176 // HideOutput indicates that this message should not be rendered in the UI.
177 // This is useful for subconversations that generate output that shouldn't be shown to the user.
178 HideOutput bool `json:"hide_output,omitempty"`
179
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 Idx int `json:"idx"`
181}
182
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000183// SetConvo sets m.ConversationID, m.ParentConversationID, and m.HideOutput based on convo.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700184func (m *AgentMessage) SetConvo(convo *conversation.Convo) {
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700185 if convo == nil {
186 m.ConversationID = ""
187 m.ParentConversationID = nil
188 return
189 }
190 m.ConversationID = convo.ID
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000191 m.HideOutput = convo.Hidden
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700192 if convo.Parent != nil {
193 m.ParentConversationID = &convo.Parent.ID
194 }
195}
196
Earl Lee2e463fb2025-04-17 11:22:22 -0700197// GitCommit represents a single git commit for a commit message
198type GitCommit struct {
199 Hash string `json:"hash"` // Full commit hash
200 Subject string `json:"subject"` // Commit subject line
201 Body string `json:"body"` // Full commit message body
202 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
203}
204
205// ToolCall represents a single tool call within an agent message
206type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700207 Name string `json:"name"`
208 Input string `json:"input"`
209 ToolCallId string `json:"tool_call_id"`
210 ResultMessage *AgentMessage `json:"result_message,omitempty"`
211 Args string `json:"args,omitempty"`
212 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700213}
214
215func (a *AgentMessage) Attr() slog.Attr {
216 var attrs []any = []any{
217 slog.String("type", string(a.Type)),
218 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700219 attrs = append(attrs, slog.Int("idx", a.Idx))
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 if a.EndOfTurn {
221 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
222 }
223 if a.Content != "" {
224 attrs = append(attrs, slog.String("content", a.Content))
225 }
226 if a.ToolName != "" {
227 attrs = append(attrs, slog.String("tool_name", a.ToolName))
228 }
229 if a.ToolInput != "" {
230 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
231 }
232 if a.Elapsed != nil {
233 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
234 }
235 if a.TurnDuration != nil {
236 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
237 }
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700238 if len(a.ToolResult) > 0 {
239 attrs = append(attrs, slog.Any("tool_result", a.ToolResult))
Earl Lee2e463fb2025-04-17 11:22:22 -0700240 }
241 if a.ToolError {
242 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
243 }
244 if len(a.ToolCalls) > 0 {
245 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
246 for i, tc := range a.ToolCalls {
247 toolCallAttrs = append(toolCallAttrs, slog.Group(
248 fmt.Sprintf("tool_call_%d", i),
249 slog.String("name", tc.Name),
250 slog.String("input", tc.Input),
251 ))
252 }
253 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
254 }
255 if a.ConversationID != "" {
256 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
257 }
258 if a.ParentConversationID != nil {
259 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
260 }
261 if a.Usage != nil && !a.Usage.IsZero() {
262 attrs = append(attrs, a.Usage.Attr())
263 }
264 // TODO: timestamp, convo ids, idx?
265 return slog.Group("agent_message", attrs...)
266}
267
268func errorMessage(err error) AgentMessage {
269 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
270 if os.Getenv(("DEBUG")) == "1" {
271 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
272 }
273
274 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
275}
276
277func budgetMessage(err error) AgentMessage {
278 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
279}
280
281// ConvoInterface defines the interface for conversation interactions
282type ConvoInterface interface {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700283 CumulativeUsage() conversation.CumulativeUsage
284 ResetBudget(conversation.Budget)
Earl Lee2e463fb2025-04-17 11:22:22 -0700285 OverBudget() error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700286 SendMessage(message llm.Message) (*llm.Response, error)
287 SendUserTextMessage(s string, otherContents ...llm.Content) (*llm.Response, error)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700288 GetID() string
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700289 ToolResultContents(ctx context.Context, resp *llm.Response) ([]llm.Content, error)
290 ToolResultCancelContents(resp *llm.Response) ([]llm.Content, error)
Earl Lee2e463fb2025-04-17 11:22:22 -0700291 CancelToolUse(toolUseID string, cause error) error
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700292 SubConvoWithHistory() *conversation.Convo
Earl Lee2e463fb2025-04-17 11:22:22 -0700293}
294
295type Agent struct {
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700296 convo ConvoInterface
297 config AgentConfig // config for this agent
298 workingDir string
299 repoRoot string // workingDir may be a subdir of repoRoot
300 url string
301 firstMessageIndex int // index of the first message in the current conversation
302 lastHEAD string // hash of the last HEAD that was pushed to the host (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700303 gitRemoteAddr string // HTTP URL of the host git repo (only when under docker)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000304 outsideHTTP string // base address of the outside webserver (only when under docker)
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700305 ready chan struct{} // closed when the agent is initialized (only when under docker)
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000306 codebase *onstart.Codebase
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700307 startedAt time.Time
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700308 originalBudget conversation.Budget
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700309 title string
310 branchName string
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000311 codereview *codereview.CodeReviewer
Sean McCullough96b60dd2025-04-30 09:49:10 -0700312 // State machine to track agent state
313 stateMachine *StateMachine
Philip Zeyliger18532b22025-04-23 21:11:46 +0000314 // Outside information
315 outsideHostname string
316 outsideOS string
317 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000318 // URL of the git remote 'origin' if it exists
319 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700320
321 // Time when the current turn started (reset at the beginning of InnerLoop)
322 startOfTurn time.Time
323
324 // Inbox - for messages from the user to the agent.
325 // sent on by UserMessage
326 // . e.g. when user types into the chat textarea
327 // read from by GatherMessages
328 inbox chan string
329
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000330 // protects cancelTurn
331 cancelTurnMu sync.Mutex
Earl Lee2e463fb2025-04-17 11:22:22 -0700332 // cancels potentially long-running tool_use calls or chains of them
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000333 cancelTurn context.CancelCauseFunc
Earl Lee2e463fb2025-04-17 11:22:22 -0700334
335 // protects following
336 mu sync.Mutex
337
338 // Stores all messages for this agent
339 history []AgentMessage
340
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700341 // Iterators add themselves here when they're ready to be notified of new messages.
342 subscribers []chan *AgentMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700343
344 // Track git commits we've already seen (by hash)
345 seenCommits map[string]bool
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000346
347 // Track outstanding LLM call IDs
348 outstandingLLMCalls map[string]struct{}
349
350 // Track outstanding tool calls by ID with their names
351 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700352}
353
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700354// NewIterator implements CodingAgent.
355func (a *Agent) NewIterator(ctx context.Context, nextMessageIdx int) MessageIterator {
356 a.mu.Lock()
357 defer a.mu.Unlock()
358
359 return &MessageIteratorImpl{
360 agent: a,
361 ctx: ctx,
362 nextMessageIdx: nextMessageIdx,
363 ch: make(chan *AgentMessage, 100),
364 }
365}
366
367type MessageIteratorImpl struct {
368 agent *Agent
369 ctx context.Context
370 nextMessageIdx int
371 ch chan *AgentMessage
372 subscribed bool
373}
374
375func (m *MessageIteratorImpl) Close() {
376 m.agent.mu.Lock()
377 defer m.agent.mu.Unlock()
378 // Delete ourselves from the subscribers list
379 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
380 return x == m.ch
381 })
382 close(m.ch)
383}
384
385func (m *MessageIteratorImpl) Next() *AgentMessage {
386 // We avoid subscription at creation to let ourselves catch up to "current state"
387 // before subscribing.
388 if !m.subscribed {
389 m.agent.mu.Lock()
390 if m.nextMessageIdx < len(m.agent.history) {
391 msg := &m.agent.history[m.nextMessageIdx]
392 m.nextMessageIdx++
393 m.agent.mu.Unlock()
394 return msg
395 }
396 // The next message doesn't exist yet, so let's subscribe
397 m.agent.subscribers = append(m.agent.subscribers, m.ch)
398 m.subscribed = true
399 m.agent.mu.Unlock()
400 }
401
402 for {
403 select {
404 case <-m.ctx.Done():
405 m.agent.mu.Lock()
406 // Delete ourselves from the subscribers list
407 m.agent.subscribers = slices.DeleteFunc(m.agent.subscribers, func(x chan *AgentMessage) bool {
408 return x == m.ch
409 })
410 m.subscribed = false
411 m.agent.mu.Unlock()
412 return nil
413 case msg, ok := <-m.ch:
414 if !ok {
415 // Close may have been called
416 return nil
417 }
418 if msg.Idx == m.nextMessageIdx {
419 m.nextMessageIdx++
420 return msg
421 }
422 slog.Debug("Out of order messages", "expected", m.nextMessageIdx, "got", msg.Idx, "m", msg.Content)
423 panic("out of order message")
424 }
425 }
426}
427
Sean McCulloughd9d45812025-04-30 16:53:41 -0700428// Assert that Agent satisfies the CodingAgent interface.
429var _ CodingAgent = &Agent{}
430
431// StateName implements CodingAgent.
432func (a *Agent) CurrentStateName() string {
433 if a.stateMachine == nil {
434 return ""
435 }
436 return a.stateMachine.currentState.String()
437}
438
Earl Lee2e463fb2025-04-17 11:22:22 -0700439func (a *Agent) URL() string { return a.url }
440
441// Title returns the current title of the conversation.
442// If no title has been set, returns an empty string.
443func (a *Agent) Title() string {
444 a.mu.Lock()
445 defer a.mu.Unlock()
446 return a.title
447}
448
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000449// BranchName returns the git branch name for the conversation.
450func (a *Agent) BranchName() string {
451 a.mu.Lock()
452 defer a.mu.Unlock()
453 return a.branchName
454}
455
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000456// OutstandingLLMCallCount returns the number of outstanding LLM calls.
457func (a *Agent) OutstandingLLMCallCount() int {
458 a.mu.Lock()
459 defer a.mu.Unlock()
460 return len(a.outstandingLLMCalls)
461}
462
463// OutstandingToolCalls returns the names of outstanding tool calls.
464func (a *Agent) OutstandingToolCalls() []string {
465 a.mu.Lock()
466 defer a.mu.Unlock()
467
468 tools := make([]string, 0, len(a.outstandingToolCalls))
469 for _, toolName := range a.outstandingToolCalls {
470 tools = append(tools, toolName)
471 }
472 return tools
473}
474
Earl Lee2e463fb2025-04-17 11:22:22 -0700475// OS returns the operating system of the client.
476func (a *Agent) OS() string {
477 return a.config.ClientGOOS
478}
479
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000480func (a *Agent) SessionID() string {
481 return a.config.SessionID
482}
483
Philip Zeyliger18532b22025-04-23 21:11:46 +0000484// OutsideOS returns the operating system of the outside system.
485func (a *Agent) OutsideOS() string {
486 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000487}
488
Philip Zeyliger18532b22025-04-23 21:11:46 +0000489// OutsideHostname returns the hostname of the outside system.
490func (a *Agent) OutsideHostname() string {
491 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000492}
493
Philip Zeyliger18532b22025-04-23 21:11:46 +0000494// OutsideWorkingDir returns the working directory on the outside system.
495func (a *Agent) OutsideWorkingDir() string {
496 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000497}
498
499// GitOrigin returns the URL of the git remote 'origin' if it exists.
500func (a *Agent) GitOrigin() string {
501 return a.gitOrigin
502}
503
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000504func (a *Agent) OpenBrowser(url string) {
505 if !a.IsInContainer() {
506 browser.Open(url)
507 return
508 }
509 // We're in Docker, need to send a request to the Git server
510 // to signal that the outer process should open the browser.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700511 // We don't get to specify a URL, because we are untrusted.
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000512 httpc := &http.Client{Timeout: 5 * time.Second}
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700513 resp, err := httpc.Post(a.outsideHTTP+"/browser", "text/plain", nil)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000514 if err != nil {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700515 slog.Debug("browser launch request connection failed", "err", err)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000516 return
517 }
518 defer resp.Body.Close()
519 if resp.StatusCode == http.StatusOK {
520 return
521 }
522 body, _ := io.ReadAll(resp.Body)
523 slog.Debug("browser launch request execution failed", "status", resp.Status, "body", string(body))
524}
525
Sean McCullough96b60dd2025-04-30 09:49:10 -0700526// CurrentState returns the current state of the agent's state machine.
527func (a *Agent) CurrentState() State {
528 return a.stateMachine.CurrentState()
529}
530
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700531func (a *Agent) IsInContainer() bool {
532 return a.config.InDocker
533}
534
535func (a *Agent) FirstMessageIndex() int {
536 a.mu.Lock()
537 defer a.mu.Unlock()
538 return a.firstMessageIndex
539}
540
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000541// SetTitle sets the title of the conversation.
542func (a *Agent) SetTitle(title string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700543 a.mu.Lock()
544 defer a.mu.Unlock()
545 a.title = title
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000546}
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700547
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000548// SetBranch sets the branch name of the conversation.
549func (a *Agent) SetBranch(branchName string) {
550 a.mu.Lock()
551 defer a.mu.Unlock()
552 a.branchName = branchName
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000553 convo, ok := a.convo.(*conversation.Convo)
554 if ok {
555 convo.ExtraData["branch"] = branchName
556 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700557}
558
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000559// OnToolCall implements ant.Listener and tracks the start of a tool call.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700560func (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 +0000561 // Track the tool call
562 a.mu.Lock()
563 a.outstandingToolCalls[id] = toolName
564 a.mu.Unlock()
565}
566
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700567// contentToString converts []llm.Content to a string, concatenating all text content and skipping non-text types.
568// If there's only one element in the array and it's a text type, it returns that text directly.
569// It also processes nested ToolResult arrays recursively.
570func contentToString(contents []llm.Content) string {
571 if len(contents) == 0 {
572 return ""
573 }
574
575 // If there's only one element and it's a text type, return it directly
576 if len(contents) == 1 && contents[0].Type == llm.ContentTypeText {
577 return contents[0].Text
578 }
579
580 // Otherwise, concatenate all text content
581 var result strings.Builder
582 for _, content := range contents {
583 if content.Type == llm.ContentTypeText {
584 result.WriteString(content.Text)
585 } else if content.Type == llm.ContentTypeToolResult && len(content.ToolResult) > 0 {
586 // Recursively process nested tool results
587 result.WriteString(contentToString(content.ToolResult))
588 }
589 }
590
591 return result.String()
592}
593
Earl Lee2e463fb2025-04-17 11:22:22 -0700594// OnToolResult implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700595func (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 +0000596 // Remove the tool call from outstanding calls
597 a.mu.Lock()
598 delete(a.outstandingToolCalls, toolID)
599 a.mu.Unlock()
600
Earl Lee2e463fb2025-04-17 11:22:22 -0700601 m := AgentMessage{
602 Type: ToolUseMessageType,
603 Content: content.Text,
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700604 ToolResult: contentToString(content.ToolResult),
Earl Lee2e463fb2025-04-17 11:22:22 -0700605 ToolError: content.ToolError,
606 ToolName: toolName,
607 ToolInput: string(toolInput),
608 ToolCallId: content.ToolUseID,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700609 StartTime: content.ToolUseStartTime,
610 EndTime: content.ToolUseEndTime,
Earl Lee2e463fb2025-04-17 11:22:22 -0700611 }
612
613 // Calculate the elapsed time if both start and end times are set
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700614 if content.ToolUseStartTime != nil && content.ToolUseEndTime != nil {
615 elapsed := content.ToolUseEndTime.Sub(*content.ToolUseStartTime)
Earl Lee2e463fb2025-04-17 11:22:22 -0700616 m.Elapsed = &elapsed
617 }
618
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700619 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700620 a.pushToOutbox(ctx, m)
621}
622
623// OnRequest implements ant.Listener.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700624func (a *Agent) OnRequest(ctx context.Context, convo *conversation.Convo, id string, msg *llm.Message) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000625 a.mu.Lock()
626 defer a.mu.Unlock()
627 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700628 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
629}
630
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700631// OnResponse implements conversation.Listener. Responses contain messages from the LLM
Earl Lee2e463fb2025-04-17 11:22:22 -0700632// that need to be displayed (as well as tool calls that we send along when
633// they're done). (It would be reasonable to also mention tool calls when they're
634// started, but we don't do that yet.)
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700635func (a *Agent) OnResponse(ctx context.Context, convo *conversation.Convo, id string, resp *llm.Response) {
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000636 // Remove the LLM call from outstanding calls
637 a.mu.Lock()
638 delete(a.outstandingLLMCalls, id)
639 a.mu.Unlock()
640
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700641 if resp == nil {
642 // LLM API call failed
643 m := AgentMessage{
644 Type: ErrorMessageType,
645 Content: "API call failed, type 'continue' to try again",
646 }
647 m.SetConvo(convo)
648 a.pushToOutbox(ctx, m)
649 return
650 }
651
Earl Lee2e463fb2025-04-17 11:22:22 -0700652 endOfTurn := false
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700653 if convo.Parent == nil { // subconvos never end the turn
654 switch resp.StopReason {
655 case llm.StopReasonToolUse:
656 // Check whether any of the tool calls are for tools that should end the turn
657 ToolSearch:
658 for _, part := range resp.Content {
659 if part.Type != llm.ContentTypeToolUse {
660 continue
661 }
Sean McCullough021557a2025-05-05 23:20:53 +0000662 // Find the tool by name
663 for _, tool := range convo.Tools {
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700664 if tool.Name == part.ToolName {
665 endOfTurn = tool.EndsTurn
666 break ToolSearch
Sean McCullough021557a2025-05-05 23:20:53 +0000667 }
668 }
Sean McCullough021557a2025-05-05 23:20:53 +0000669 }
Josh Bleecher Snyder4fcde4a2025-05-05 18:28:13 -0700670 default:
671 endOfTurn = true
Sean McCullough021557a2025-05-05 23:20:53 +0000672 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700673 }
674 m := AgentMessage{
675 Type: AgentMessageType,
676 Content: collectTextContent(resp),
677 EndOfTurn: endOfTurn,
678 Usage: &resp.Usage,
679 StartTime: resp.StartTime,
680 EndTime: resp.EndTime,
681 }
682
683 // Extract any tool calls from the response
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700684 if resp.StopReason == llm.StopReasonToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700685 var toolCalls []ToolCall
686 for _, part := range resp.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700687 if part.Type == llm.ContentTypeToolUse {
Earl Lee2e463fb2025-04-17 11:22:22 -0700688 toolCalls = append(toolCalls, ToolCall{
689 Name: part.ToolName,
690 Input: string(part.ToolInput),
691 ToolCallId: part.ID,
692 })
693 }
694 }
695 m.ToolCalls = toolCalls
696 }
697
698 // Calculate the elapsed time if both start and end times are set
699 if resp.StartTime != nil && resp.EndTime != nil {
700 elapsed := resp.EndTime.Sub(*resp.StartTime)
701 m.Elapsed = &elapsed
702 }
703
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700704 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 a.pushToOutbox(ctx, m)
706}
707
708// WorkingDir implements CodingAgent.
709func (a *Agent) WorkingDir() string {
710 return a.workingDir
711}
712
713// MessageCount implements CodingAgent.
714func (a *Agent) MessageCount() int {
715 a.mu.Lock()
716 defer a.mu.Unlock()
717 return len(a.history)
718}
719
720// Messages implements CodingAgent.
721func (a *Agent) Messages(start int, end int) []AgentMessage {
722 a.mu.Lock()
723 defer a.mu.Unlock()
724 return slices.Clone(a.history[start:end])
725}
726
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700727func (a *Agent) OriginalBudget() conversation.Budget {
Earl Lee2e463fb2025-04-17 11:22:22 -0700728 return a.originalBudget
729}
730
731// AgentConfig contains configuration for creating a new Agent.
732type AgentConfig struct {
733 Context context.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700734 Service llm.Service
735 Budget conversation.Budget
Earl Lee2e463fb2025-04-17 11:22:22 -0700736 GitUsername string
737 GitEmail string
738 SessionID string
739 ClientGOOS string
740 ClientGOARCH string
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700741 InDocker bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700742 UseAnthropicEdit bool
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000743 OneShot bool
Philip Zeyliger18532b22025-04-23 21:11:46 +0000744 // Outside information
745 OutsideHostname string
746 OutsideOS string
747 OutsideWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -0700748}
749
750// NewAgent creates a new Agent.
751// It is not usable until Init() is called.
752func NewAgent(config AgentConfig) *Agent {
753 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000754 config: config,
755 ready: make(chan struct{}),
756 inbox: make(chan string, 100),
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700757 subscribers: make([]chan *AgentMessage, 0),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000758 startedAt: time.Now(),
759 originalBudget: config.Budget,
760 seenCommits: make(map[string]bool),
761 outsideHostname: config.OutsideHostname,
762 outsideOS: config.OutsideOS,
763 outsideWorkingDir: config.OutsideWorkingDir,
764 outstandingLLMCalls: make(map[string]struct{}),
765 outstandingToolCalls: make(map[string]string),
Sean McCullough96b60dd2025-04-30 09:49:10 -0700766 stateMachine: NewStateMachine(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700767 }
768 return agent
769}
770
771type AgentInit struct {
772 WorkingDir string
773 NoGit bool // only for testing
774
775 InDocker bool
776 Commit string
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000777 OutsideHTTP string
Earl Lee2e463fb2025-04-17 11:22:22 -0700778 GitRemoteAddr string
779 HostAddr string
780}
781
782func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700783 if a.convo != nil {
784 return fmt.Errorf("Agent.Init: already initialized")
785 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700786 ctx := a.config.Context
787 if ini.InDocker {
788 cmd := exec.CommandContext(ctx, "git", "stash")
789 cmd.Dir = ini.WorkingDir
790 if out, err := cmd.CombinedOutput(); err != nil {
791 return fmt.Errorf("git stash: %s: %v", out, err)
792 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700793 // sketch-host is a git repo hosted by "outtie sketch". When it notices a 'git fetch',
794 // it runs "git fetch" underneath the covers to get its latest commits. By configuring
795 // an additional remote.sketch-host.fetch, we make "origin/main" on innie sketch look like
796 // origin/main on outtie sketch, which should make it easier to rebase.
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700797 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", ini.GitRemoteAddr)
798 cmd.Dir = ini.WorkingDir
799 if out, err := cmd.CombinedOutput(); err != nil {
800 return fmt.Errorf("git remote add: %s: %v", out, err)
801 }
Philip Zeyligere97a8e52025-05-09 14:53:33 -0700802 cmd = exec.CommandContext(ctx, "git", "config", "--add", "remote.sketch-host.fetch",
803 "+refs/heads/feature/*:refs/remotes/origin/feature/*")
804 cmd.Dir = ini.WorkingDir
805 if out, err := cmd.CombinedOutput(); err != nil {
806 return fmt.Errorf("git config --add: %s: %v", out, err)
807 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +0000808 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Earl Lee2e463fb2025-04-17 11:22:22 -0700809 cmd.Dir = ini.WorkingDir
810 if out, err := cmd.CombinedOutput(); err != nil {
811 return fmt.Errorf("git fetch: %s: %w", out, err)
812 }
813 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
814 cmd.Dir = ini.WorkingDir
Pokey Rule7a113622025-05-12 10:58:45 +0100815 if checkoutOut, err := cmd.CombinedOutput(); err != nil {
816 // Remove git hooks if they exist and retry
817 // Only try removing hooks if we haven't already removed them during fetch
818 hookPath := filepath.Join(ini.WorkingDir, ".git", "hooks")
819 if _, statErr := os.Stat(hookPath); statErr == nil {
820 slog.WarnContext(ctx, "git checkout failed, removing hooks and retrying",
821 slog.String("error", err.Error()),
822 slog.String("output", string(checkoutOut)))
823 if removeErr := removeGitHooks(ctx, ini.WorkingDir); removeErr != nil {
824 slog.WarnContext(ctx, "failed to remove git hooks", slog.String("error", removeErr.Error()))
825 }
826
827 // Retry the checkout operation
828 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
829 cmd.Dir = ini.WorkingDir
830 if retryOut, retryErr := cmd.CombinedOutput(); retryErr != nil {
831 return fmt.Errorf("git checkout %s failed even after removing hooks: %s: %w", ini.Commit, retryOut, retryErr)
832 }
833 } else {
834 return fmt.Errorf("git checkout %s: %s: %w", ini.Commit, checkoutOut, err)
835 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700836 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700837 a.gitRemoteAddr = ini.GitRemoteAddr
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000838 a.outsideHTTP = ini.OutsideHTTP
Earl Lee2e463fb2025-04-17 11:22:22 -0700839 if ini.HostAddr != "" {
840 a.url = "http://" + ini.HostAddr
841 }
842 }
843 a.workingDir = ini.WorkingDir
844
845 if !ini.NoGit {
846 repoRoot, err := repoRoot(ctx, a.workingDir)
847 if err != nil {
848 return fmt.Errorf("repoRoot: %w", err)
849 }
850 a.repoRoot = repoRoot
851
Earl Lee2e463fb2025-04-17 11:22:22 -0700852 if err != nil {
853 return fmt.Errorf("resolveRef: %w", err)
854 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700855
856 cmd := exec.CommandContext(ctx, "git", "tag", "-f", a.SketchGitBaseRef(), "HEAD")
857 cmd.Dir = repoRoot
858 if out, err := cmd.CombinedOutput(); err != nil {
859 return fmt.Errorf("git tag -f %s %s: %s: %w", a.SketchGitBaseRef(), "HEAD", out, err)
860 }
861 a.lastHEAD = ini.Commit
Earl Lee2e463fb2025-04-17 11:22:22 -0700862
Josh Bleecher Snydera997be62025-05-07 22:52:46 +0000863 if experiment.Enabled("memory") {
864 slog.Info("running codebase analysis")
865 codebase, err := onstart.AnalyzeCodebase(ctx, a.repoRoot)
866 if err != nil {
867 slog.Warn("failed to analyze codebase", "error", err)
868 }
869 a.codebase = codebase
870 }
871
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000872 llmCodeReview := codereview.NoLLMReview
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -0700873 if experiment.Enabled("llm_review") {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000874 llmCodeReview = codereview.DoLLMReview
Josh Bleecher Snydere2518e52025-04-29 11:13:40 -0700875 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700876 codereview, err := codereview.NewCodeReviewer(ctx, a.repoRoot, a.SketchGitBaseRef(), llmCodeReview)
Earl Lee2e463fb2025-04-17 11:22:22 -0700877 if err != nil {
Josh Bleecher Snyderf4047bb2025-05-05 23:02:56 +0000878 return fmt.Errorf("Agent.Init: codereview.NewCodeReviewer: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700879 }
880 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000881
882 a.gitOrigin = getGitOrigin(ctx, ini.WorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700883 }
Philip Zeyliger49edc922025-05-14 09:45:45 -0700884 a.lastHEAD = a.SketchGitBase()
Earl Lee2e463fb2025-04-17 11:22:22 -0700885 a.convo = a.initConvo()
886 close(a.ready)
887 return nil
888}
889
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700890//go:embed agent_system_prompt.txt
891var agentSystemPrompt string
892
Earl Lee2e463fb2025-04-17 11:22:22 -0700893// initConvo initializes the conversation.
894// It must not be called until all agent fields are initialized,
895// particularly workingDir and git.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700896func (a *Agent) initConvo() *conversation.Convo {
Earl Lee2e463fb2025-04-17 11:22:22 -0700897 ctx := a.config.Context
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700898 convo := conversation.New(ctx, a.config.Service)
Earl Lee2e463fb2025-04-17 11:22:22 -0700899 convo.PromptCaching = true
900 convo.Budget = a.config.Budget
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +0000901 convo.SystemPrompt = a.renderSystemPrompt()
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000902 convo.ExtraData = map[string]any{"session_id": a.config.SessionID}
Earl Lee2e463fb2025-04-17 11:22:22 -0700903
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000904 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
905 bashPermissionCheck := func(command string) error {
906 // Check if branch name is set
907 a.mu.Lock()
908 branchSet := a.branchName != ""
909 a.mu.Unlock()
910
911 // If branch is set, all commands are allowed
912 if branchSet {
913 return nil
914 }
915
916 // If branch is not set, check if this is a git commit command
917 willCommit, err := bashkit.WillRunGitCommit(command)
918 if err != nil {
919 // If there's an error checking, we should allow the command to proceed
920 return nil
921 }
922
923 // If it's a git commit and branch is not set, return an error
924 if willCommit {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +0000925 return fmt.Errorf("you must use the precommit tool before making git commits")
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000926 }
927
928 return nil
929 }
930
931 // Create a custom bash tool with the permission check
932 bashTool := claudetool.NewBashTool(bashPermissionCheck)
933
Earl Lee2e463fb2025-04-17 11:22:22 -0700934 // Register all tools with the conversation
935 // When adding, removing, or modifying tools here, double-check that the termui tool display
936 // template in termui/termui.go has pretty-printing support for all tools.
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000937
938 var browserTools []*llm.Tool
Philip Zeyliger80b488d2025-05-10 18:21:54 -0700939 _, supportsScreenshots := a.config.Service.(*ant.Service)
940 var bTools []*llm.Tool
941 var browserCleanup func()
942
943 bTools, browserCleanup = browse.RegisterBrowserTools(a.config.Context, supportsScreenshots)
944 // Add cleanup function to context cancel
945 go func() {
946 <-a.config.Context.Done()
947 browserCleanup()
948 }()
949 browserTools = bTools
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000950
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700951 convo.Tools = []*llm.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000952 bashTool, claudetool.Keyword,
Josh Bleecher Snyder93202652025-05-08 02:05:57 +0000953 claudetool.Think, a.titleTool(), a.precommitTool(), makeDoneTool(a.codereview),
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000954 a.codereview.Tool(),
955 }
956
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +0000957 if experiment.Enabled("kb") {
958 convo.Tools = append(convo.Tools, claudetool.KnowledgeBase)
959 }
960
Josh Bleecher Snyderb529e732025-05-07 22:06:46 +0000961 // One-shot mode is non-interactive, multiple choice requires human response
962 if !a.config.OneShot {
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700963 convo.Tools = append(convo.Tools, multipleChoiceTool)
Earl Lee2e463fb2025-04-17 11:22:22 -0700964 }
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000965
966 convo.Tools = append(convo.Tools, browserTools...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700967 if a.config.UseAnthropicEdit {
968 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
969 } else {
970 convo.Tools = append(convo.Tools, claudetool.Patch)
971 }
972 convo.Listener = a
973 return convo
974}
975
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -0700976var multipleChoiceTool = &llm.Tool{
977 Name: "multiplechoice",
978 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.",
979 EndsTurn: true,
980 InputSchema: json.RawMessage(`{
Sean McCullough485afc62025-04-28 14:28:39 -0700981 "type": "object",
982 "description": "The question and a list of answers you would expect the user to choose from.",
983 "properties": {
984 "question": {
985 "type": "string",
986 "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?'"
987 },
988 "responseOptions": {
989 "type": "array",
990 "description": "The set of possible answers to let the user quickly choose from, e.g. ['Basic unit test coverage', 'Error return values', 'Malformed input'].",
991 "items": {
992 "type": "object",
993 "properties": {
994 "caption": {
995 "type": "string",
996 "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'"
997 },
998 "responseText": {
999 "type": "string",
1000 "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'"
1001 }
1002 },
1003 "required": ["caption", "responseText"]
1004 }
1005 }
1006 },
1007 "required": ["question", "responseOptions"]
1008}`),
Josh Bleecher Snydera5c971e2025-05-14 10:49:08 -07001009 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
1010 // The Run logic for "multiplechoice" tool is a no-op on the server.
1011 // The UI will present a list of options for the user to select from,
1012 // and that's it as far as "executing" the tool_use goes.
1013 // When the user *does* select one of the presented options, that
1014 // responseText gets sent as a chat message on behalf of the user.
1015 return llm.TextContent("end your turn and wait for the user to respond"), nil
1016 },
Sean McCullough485afc62025-04-28 14:28:39 -07001017}
1018
1019type MultipleChoiceOption struct {
1020 Caption string `json:"caption"`
1021 ResponseText string `json:"responseText"`
1022}
1023
1024type MultipleChoiceParams struct {
1025 Question string `json:"question"`
1026 ResponseOptions []MultipleChoiceOption `json:"responseOptions"`
1027}
1028
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001029// branchExists reports whether branchName exists, either locally or in well-known remotes.
1030func branchExists(dir, branchName string) bool {
1031 refs := []string{
1032 "refs/heads/",
1033 "refs/remotes/origin/",
1034 "refs/remotes/sketch-host/",
1035 }
1036 for _, ref := range refs {
1037 cmd := exec.Command("git", "show-ref", "--verify", "--quiet", ref+branchName)
1038 cmd.Dir = dir
1039 if cmd.Run() == nil { // exit code 0 means branch exists
1040 return true
1041 }
1042 }
1043 return false
1044}
1045
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001046func (a *Agent) titleTool() *llm.Tool {
1047 description := `Sets the conversation title.`
1048 titleTool := &llm.Tool{
Josh Bleecher Snyder36a5cc12025-05-05 17:59:53 -07001049 Name: "title",
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001050 Description: description,
Earl Lee2e463fb2025-04-17 11:22:22 -07001051 InputSchema: json.RawMessage(`{
1052 "type": "object",
1053 "properties": {
1054 "title": {
1055 "type": "string",
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001056 "description": "Brief title (3-6 words) in imperative tense. Focus on core action/component."
Earl Lee2e463fb2025-04-17 11:22:22 -07001057 }
1058 },
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001059 "required": ["title"]
Earl Lee2e463fb2025-04-17 11:22:22 -07001060}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001061 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -07001062 var params struct {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001063 Title string `json:"title"`
Earl Lee2e463fb2025-04-17 11:22:22 -07001064 }
1065 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001066 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001067 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001068
1069 // We don't allow changing the title once set to be consistent with the previous behavior
1070 // and to prevent accidental title changes
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001071 t := a.Title()
1072 if t != "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001073 return nil, fmt.Errorf("title already set to: %s", t)
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001074 }
1075
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001076 if params.Title == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001077 return nil, fmt.Errorf("title parameter cannot be empty")
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001078 }
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001079
1080 a.SetTitle(params.Title)
1081 response := fmt.Sprintf("Title set to %q", params.Title)
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001082 return llm.TextContent(response), nil
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001083 },
1084 }
1085 return titleTool
1086}
1087
1088func (a *Agent) precommitTool() *llm.Tool {
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001089 description := `Creates a git branch for tracking work and provides git commit message style guidance. MANDATORY: You must use this tool before making any git commits.`
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001090 preCommit := &llm.Tool{
1091 Name: "precommit",
1092 Description: description,
1093 InputSchema: json.RawMessage(`{
1094 "type": "object",
1095 "properties": {
1096 "branch_name": {
1097 "type": "string",
1098 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
1099 }
1100 },
1101 "required": ["branch_name"]
1102}`),
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001103 Run: func(ctx context.Context, input json.RawMessage) ([]llm.Content, error) {
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001104 var params struct {
1105 BranchName string `json:"branch_name"`
1106 }
1107 if err := json.Unmarshal(input, &params); err != nil {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001108 return nil, err
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001109 }
1110
1111 b := a.BranchName()
1112 if b != "" {
Josh Bleecher Snyder44d1f1a2025-05-12 19:18:32 -07001113 return nil, fmt.Errorf("branch already set to %s; do not create a new branch", b)
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001114 }
1115
1116 if params.BranchName == "" {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001117 return nil, fmt.Errorf("branch_name must not be empty")
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001118 }
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001119 if params.BranchName != cleanBranchName(params.BranchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001120 return nil, fmt.Errorf("branch_name parameter must be alphanumeric hyphenated slug")
Josh Bleecher Snyder42f7a7c2025-04-30 10:29:21 -07001121 }
1122 branchName := "sketch/" + params.BranchName
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001123 if branchExists(a.workingDir, branchName) {
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001124 return nil, fmt.Errorf("branch %q already exists; please choose a different branch name", branchName)
Josh Bleecher Snyderfff269b2025-04-30 01:49:39 +00001125 }
1126
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +00001127 a.SetBranch(branchName)
1128 response := fmt.Sprintf("Branch name set to %q", branchName)
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001129
Josh Bleecher Snyder6aaf6af2025-05-07 20:47:13 +00001130 styleHint, err := claudetool.CommitMessageStyleHint(ctx, a.repoRoot)
1131 if err != nil {
1132 slog.DebugContext(ctx, "failed to get commit message style hint", "err", err)
1133 }
1134 if len(styleHint) > 0 {
1135 response += "\n\n" + styleHint
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001136 }
1137
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001138 return llm.TextContent(response), nil
Earl Lee2e463fb2025-04-17 11:22:22 -07001139 },
1140 }
Josh Bleecher Snyderd7970e62025-05-01 01:56:28 +00001141 return preCommit
Earl Lee2e463fb2025-04-17 11:22:22 -07001142}
1143
1144func (a *Agent) Ready() <-chan struct{} {
1145 return a.ready
1146}
1147
1148func (a *Agent) UserMessage(ctx context.Context, msg string) {
1149 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
1150 a.inbox <- msg
1151}
1152
Earl Lee2e463fb2025-04-17 11:22:22 -07001153func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
1154 return a.convo.CancelToolUse(toolUseID, cause)
1155}
1156
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001157func (a *Agent) CancelTurn(cause error) {
1158 a.cancelTurnMu.Lock()
1159 defer a.cancelTurnMu.Unlock()
1160 if a.cancelTurn != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001161 // Force state transition to cancelled state
1162 ctx := a.config.Context
1163 a.stateMachine.ForceTransition(ctx, StateCancelled, "User cancelled turn: "+cause.Error())
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001164 a.cancelTurn(cause)
Earl Lee2e463fb2025-04-17 11:22:22 -07001165 }
1166}
1167
1168func (a *Agent) Loop(ctxOuter context.Context) {
1169 for {
1170 select {
1171 case <-ctxOuter.Done():
1172 return
1173 default:
1174 ctxInner, cancel := context.WithCancelCause(ctxOuter)
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001175 a.cancelTurnMu.Lock()
1176 // Set .cancelTurn so the user can cancel whatever is happening
Sean McCullough885a16a2025-04-30 02:49:25 +00001177 // inside the conversation loop without canceling this outer Loop execution.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001178 // This cancelTurn func is intended be called from other goroutines,
Earl Lee2e463fb2025-04-17 11:22:22 -07001179 // hence the mutex.
Sean McCulloughedc88dc2025-04-30 02:55:01 +00001180 a.cancelTurn = cancel
1181 a.cancelTurnMu.Unlock()
Sean McCullough9f4b8082025-04-30 17:34:07 +00001182 err := a.processTurn(ctxInner) // Renamed from InnerLoop to better reflect its purpose
1183 if err != nil {
1184 slog.ErrorContext(ctxOuter, "Error in processing turn", "error", err)
1185 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001186 cancel(nil)
1187 }
1188 }
1189}
1190
1191func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
1192 if m.Timestamp.IsZero() {
1193 m.Timestamp = time.Now()
1194 }
1195
Philip Zeyliger72252cb2025-05-10 17:00:08 -07001196 // If this is a ToolUseMessage and ToolResult is set but Content is not, copy the ToolResult to Content
1197 if m.Type == ToolUseMessageType && m.ToolResult != "" && m.Content == "" {
1198 m.Content = m.ToolResult
1199 }
1200
Earl Lee2e463fb2025-04-17 11:22:22 -07001201 // If this is an end-of-turn message, calculate the turn duration and add it to the message
1202 if m.EndOfTurn && m.Type == AgentMessageType {
1203 turnDuration := time.Since(a.startOfTurn)
1204 m.TurnDuration = &turnDuration
1205 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
1206 }
1207
Earl Lee2e463fb2025-04-17 11:22:22 -07001208 a.mu.Lock()
1209 defer a.mu.Unlock()
1210 m.Idx = len(a.history)
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001211 slog.InfoContext(ctx, "agent message", m.Attr())
Earl Lee2e463fb2025-04-17 11:22:22 -07001212 a.history = append(a.history, m)
Earl Lee2e463fb2025-04-17 11:22:22 -07001213
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001214 // Notify all subscribers
1215 for _, ch := range a.subscribers {
1216 ch <- &m
Earl Lee2e463fb2025-04-17 11:22:22 -07001217 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001218}
1219
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001220func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]llm.Content, error) {
1221 var m []llm.Content
Earl Lee2e463fb2025-04-17 11:22:22 -07001222 if block {
1223 select {
1224 case <-ctx.Done():
1225 return m, ctx.Err()
1226 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001227 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001228 }
1229 }
1230 for {
1231 select {
1232 case msg := <-a.inbox:
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001233 m = append(m, llm.StringContent(msg))
Earl Lee2e463fb2025-04-17 11:22:22 -07001234 default:
1235 return m, nil
1236 }
1237 }
1238}
1239
Sean McCullough885a16a2025-04-30 02:49:25 +00001240// processTurn handles a single conversation turn with the user
Sean McCullough9f4b8082025-04-30 17:34:07 +00001241func (a *Agent) processTurn(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -07001242 // Reset the start of turn time
1243 a.startOfTurn = time.Now()
1244
Sean McCullough96b60dd2025-04-30 09:49:10 -07001245 // Transition to waiting for user input state
1246 a.stateMachine.Transition(ctx, StateWaitingForUserInput, "Starting turn")
1247
Sean McCullough885a16a2025-04-30 02:49:25 +00001248 // Process initial user message
1249 initialResp, err := a.processUserMessage(ctx)
1250 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001251 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001252 return err
1253 }
1254
1255 // Handle edge case where both initialResp and err are nil
1256 if initialResp == nil {
1257 err := fmt.Errorf("unexpected nil response from processUserMessage with no error")
Sean McCullough96b60dd2025-04-30 09:49:10 -07001258 a.stateMachine.Transition(ctx, StateError, "Error processing user message: "+err.Error())
1259
Sean McCullough9f4b8082025-04-30 17:34:07 +00001260 a.pushToOutbox(ctx, errorMessage(err))
1261 return err
Earl Lee2e463fb2025-04-17 11:22:22 -07001262 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001263
Earl Lee2e463fb2025-04-17 11:22:22 -07001264 // We do this as we go, but let's also do it at the end of the turn
1265 defer func() {
1266 if _, err := a.handleGitCommits(ctx); err != nil {
1267 // Just log the error, don't stop execution
1268 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1269 }
1270 }()
1271
Sean McCullougha1e0e492025-05-01 10:51:08 -07001272 // Main response loop - continue as long as the model is using tools or a tool use fails.
Sean McCullough885a16a2025-04-30 02:49:25 +00001273 resp := initialResp
1274 for {
1275 // Check if we are over budget
1276 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001277 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Sean McCullough9f4b8082025-04-30 17:34:07 +00001278 return err
Sean McCullough885a16a2025-04-30 02:49:25 +00001279 }
1280
1281 // If the model is not requesting to use a tool, we're done
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001282 if resp.StopReason != llm.StopReasonToolUse {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001283 a.stateMachine.Transition(ctx, StateEndOfTurn, "LLM completed response, ending turn")
Sean McCullough885a16a2025-04-30 02:49:25 +00001284 break
1285 }
1286
Sean McCullough96b60dd2025-04-30 09:49:10 -07001287 // Transition to tool use requested state
1288 a.stateMachine.Transition(ctx, StateToolUseRequested, "LLM requested tool use")
1289
Sean McCullough885a16a2025-04-30 02:49:25 +00001290 // Handle tool execution
1291 continueConversation, toolResp := a.handleToolExecution(ctx, resp)
1292 if !continueConversation {
Sean McCullough9f4b8082025-04-30 17:34:07 +00001293 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001294 }
1295
Sean McCullougha1e0e492025-05-01 10:51:08 -07001296 if toolResp == nil {
1297 return fmt.Errorf("cannot continue conversation with a nil tool response")
1298 }
1299
Sean McCullough885a16a2025-04-30 02:49:25 +00001300 // Set the response for the next iteration
1301 resp = toolResp
1302 }
Sean McCullough9f4b8082025-04-30 17:34:07 +00001303
1304 return nil
Sean McCullough885a16a2025-04-30 02:49:25 +00001305}
1306
1307// processUserMessage waits for user messages and sends them to the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001308func (a *Agent) processUserMessage(ctx context.Context) (*llm.Response, error) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001309 // Wait for at least one message from the user
1310 msgs, err := a.GatherMessages(ctx, true)
1311 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
Sean McCullough96b60dd2025-04-30 09:49:10 -07001312 a.stateMachine.Transition(ctx, StateError, "Error gathering messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001313 return nil, err
1314 }
1315
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001316 userMessage := llm.Message{
1317 Role: llm.MessageRoleUser,
Earl Lee2e463fb2025-04-17 11:22:22 -07001318 Content: msgs,
1319 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001320
Sean McCullough96b60dd2025-04-30 09:49:10 -07001321 // Transition to sending to LLM state
1322 a.stateMachine.Transition(ctx, StateSendingToLLM, "Sending user message to LLM")
1323
Sean McCullough885a16a2025-04-30 02:49:25 +00001324 // Send message to the model
Earl Lee2e463fb2025-04-17 11:22:22 -07001325 resp, err := a.convo.SendMessage(userMessage)
1326 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001327 a.stateMachine.Transition(ctx, StateError, "Error sending to LLM: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001328 a.pushToOutbox(ctx, errorMessage(err))
Sean McCullough885a16a2025-04-30 02:49:25 +00001329 return nil, err
Earl Lee2e463fb2025-04-17 11:22:22 -07001330 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001331
Sean McCullough96b60dd2025-04-30 09:49:10 -07001332 // Transition to processing LLM response state
1333 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response")
1334
Sean McCullough885a16a2025-04-30 02:49:25 +00001335 return resp, nil
1336}
1337
1338// handleToolExecution processes a tool use request from the model
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001339func (a *Agent) handleToolExecution(ctx context.Context, resp *llm.Response) (bool, *llm.Response) {
1340 var results []llm.Content
Sean McCullough885a16a2025-04-30 02:49:25 +00001341 cancelled := false
1342
Sean McCullough96b60dd2025-04-30 09:49:10 -07001343 // Transition to checking for cancellation state
1344 a.stateMachine.Transition(ctx, StateCheckingForCancellation, "Checking if user requested cancellation")
1345
Sean McCullough885a16a2025-04-30 02:49:25 +00001346 // Check if the operation was cancelled by the user
1347 select {
1348 case <-ctx.Done():
1349 // Don't actually run any of the tools, but rather build a response
1350 // for each tool_use message letting the LLM know that user canceled it.
1351 var err error
1352 results, err = a.convo.ToolResultCancelContents(resp)
Earl Lee2e463fb2025-04-17 11:22:22 -07001353 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001354 a.stateMachine.Transition(ctx, StateError, "Error creating cancellation response: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001355 a.pushToOutbox(ctx, errorMessage(err))
Earl Lee2e463fb2025-04-17 11:22:22 -07001356 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001357 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001358 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled by user")
Sean McCullough885a16a2025-04-30 02:49:25 +00001359 default:
Sean McCullough96b60dd2025-04-30 09:49:10 -07001360 // Transition to running tool state
1361 a.stateMachine.Transition(ctx, StateRunningTool, "Executing requested tool")
1362
Sean McCullough885a16a2025-04-30 02:49:25 +00001363 // Add working directory to context for tool execution
1364 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
1365
1366 // Execute the tools
1367 var err error
1368 results, err = a.convo.ToolResultContents(ctx, resp)
1369 if ctx.Err() != nil { // e.g. the user canceled the operation
1370 cancelled = true
Sean McCullough96b60dd2025-04-30 09:49:10 -07001371 a.stateMachine.Transition(ctx, StateCancelled, "Operation cancelled during tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001372 } else if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001373 a.stateMachine.Transition(ctx, StateError, "Error executing tool: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001374 a.pushToOutbox(ctx, errorMessage(err))
1375 }
1376 }
1377
1378 // Process git commits that may have occurred during tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001379 a.stateMachine.Transition(ctx, StateCheckingGitCommits, "Checking for git commits")
Sean McCullough885a16a2025-04-30 02:49:25 +00001380 autoqualityMessages := a.processGitChanges(ctx)
1381
1382 // Check budget again after tool execution
Sean McCullough96b60dd2025-04-30 09:49:10 -07001383 a.stateMachine.Transition(ctx, StateCheckingBudget, "Checking budget after tool execution")
Sean McCullough885a16a2025-04-30 02:49:25 +00001384 if err := a.overBudget(ctx); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001385 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded after tool execution: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001386 return false, nil
1387 }
1388
1389 // Continue the conversation with tool results and any user messages
1390 return a.continueTurnWithToolResults(ctx, results, autoqualityMessages, cancelled)
1391}
1392
1393// processGitChanges checks for new git commits and runs autoformatters if needed
1394func (a *Agent) processGitChanges(ctx context.Context) []string {
1395 // Check for git commits after tool execution
1396 newCommits, err := a.handleGitCommits(ctx)
1397 if err != nil {
1398 // Just log the error, don't stop execution
1399 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
1400 return nil
1401 }
1402
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001403 // Run mechanical checks if there was exactly one new commit.
1404 if len(newCommits) != 1 {
1405 return nil
1406 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001407 var autoqualityMessages []string
Josh Bleecher Snyderc72ceb22025-05-05 23:30:15 +00001408 a.stateMachine.Transition(ctx, StateRunningAutoformatters, "Running mechanical checks on new commit")
1409 msg := a.codereview.RunMechanicalChecks(ctx)
1410 if msg != "" {
1411 a.pushToOutbox(ctx, AgentMessage{
1412 Type: AutoMessageType,
1413 Content: msg,
1414 Timestamp: time.Now(),
1415 })
1416 autoqualityMessages = append(autoqualityMessages, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -07001417 }
Sean McCullough885a16a2025-04-30 02:49:25 +00001418
1419 return autoqualityMessages
1420}
1421
1422// continueTurnWithToolResults continues the conversation with tool results
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001423func (a *Agent) continueTurnWithToolResults(ctx context.Context, results []llm.Content, autoqualityMessages []string, cancelled bool) (bool, *llm.Response) {
Sean McCullough885a16a2025-04-30 02:49:25 +00001424 // Get any messages the user sent while tools were executing
Sean McCullough96b60dd2025-04-30 09:49:10 -07001425 a.stateMachine.Transition(ctx, StateGatheringAdditionalMessages, "Gathering additional user messages")
Sean McCullough885a16a2025-04-30 02:49:25 +00001426 msgs, err := a.GatherMessages(ctx, false)
1427 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001428 a.stateMachine.Transition(ctx, StateError, "Error gathering additional messages: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001429 return false, nil
1430 }
1431
1432 // Inject any auto-generated messages from quality checks
1433 for _, msg := range autoqualityMessages {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001434 msgs = append(msgs, llm.StringContent(msg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001435 }
1436
1437 // Handle cancellation by appending a message about it
1438 if cancelled {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001439 msgs = append(msgs, llm.StringContent(cancelToolUseMessage))
Sean McCullough885a16a2025-04-30 02:49:25 +00001440 // EndOfTurn is false here so that the client of this agent keeps processing
Philip Zeyligerb7c58752025-05-01 10:10:17 -07001441 // further messages; the conversation is not over.
Sean McCullough885a16a2025-04-30 02:49:25 +00001442 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
1443 } else if err := a.convo.OverBudget(); err != nil {
1444 // Handle budget issues by appending a message about it
1445 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 -07001446 msgs = append(msgs, llm.StringContent(budgetMsg))
Sean McCullough885a16a2025-04-30 02:49:25 +00001447 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
1448 }
1449
1450 // Combine tool results with user messages
1451 results = append(results, msgs...)
1452
1453 // Send the combined message to continue the conversation
Sean McCullough96b60dd2025-04-30 09:49:10 -07001454 a.stateMachine.Transition(ctx, StateSendingToolResults, "Sending tool results back to LLM")
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001455 resp, err := a.convo.SendMessage(llm.Message{
1456 Role: llm.MessageRoleUser,
Sean McCullough885a16a2025-04-30 02:49:25 +00001457 Content: results,
1458 })
1459 if err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001460 a.stateMachine.Transition(ctx, StateError, "Error sending tool results: "+err.Error())
Sean McCullough885a16a2025-04-30 02:49:25 +00001461 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
1462 return true, nil // Return true to continue the conversation, but with no response
1463 }
1464
Sean McCullough96b60dd2025-04-30 09:49:10 -07001465 // Transition back to processing LLM response
1466 a.stateMachine.Transition(ctx, StateProcessingLLMResponse, "Processing LLM response to tool results")
1467
Sean McCullough885a16a2025-04-30 02:49:25 +00001468 if cancelled {
1469 return false, nil
1470 }
1471
1472 return true, resp
Earl Lee2e463fb2025-04-17 11:22:22 -07001473}
1474
1475func (a *Agent) overBudget(ctx context.Context) error {
1476 if err := a.convo.OverBudget(); err != nil {
Sean McCullough96b60dd2025-04-30 09:49:10 -07001477 a.stateMachine.Transition(ctx, StateBudgetExceeded, "Budget exceeded: "+err.Error())
Earl Lee2e463fb2025-04-17 11:22:22 -07001478 m := budgetMessage(err)
1479 m.Content = m.Content + "\n\nBudget reset."
1480 a.pushToOutbox(ctx, budgetMessage(err))
1481 a.convo.ResetBudget(a.originalBudget)
1482 return err
1483 }
1484 return nil
1485}
1486
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001487func collectTextContent(msg *llm.Response) string {
Earl Lee2e463fb2025-04-17 11:22:22 -07001488 // Collect all text content
1489 var allText strings.Builder
1490 for _, content := range msg.Content {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001491 if content.Type == llm.ContentTypeText && content.Text != "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001492 if allText.Len() > 0 {
1493 allText.WriteString("\n\n")
1494 }
1495 allText.WriteString(content.Text)
1496 }
1497 }
1498 return allText.String()
1499}
1500
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001501func (a *Agent) TotalUsage() conversation.CumulativeUsage {
Earl Lee2e463fb2025-04-17 11:22:22 -07001502 a.mu.Lock()
1503 defer a.mu.Unlock()
1504 return a.convo.CumulativeUsage()
1505}
1506
Earl Lee2e463fb2025-04-17 11:22:22 -07001507// Diff returns a unified diff of changes made since the agent was instantiated.
1508func (a *Agent) Diff(commit *string) (string, error) {
Philip Zeyliger49edc922025-05-14 09:45:45 -07001509 if a.SketchGitBase() == "" {
Earl Lee2e463fb2025-04-17 11:22:22 -07001510 return "", fmt.Errorf("no initial commit reference available")
1511 }
1512
1513 // Find the repository root
1514 ctx := context.Background()
1515
1516 // If a specific commit hash is provided, show just that commit's changes
1517 if commit != nil && *commit != "" {
1518 // Validate that the commit looks like a valid git SHA
1519 if !isValidGitSHA(*commit) {
1520 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1521 }
1522
1523 // Get the diff for just this commit
1524 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1525 cmd.Dir = a.repoRoot
1526 output, err := cmd.CombinedOutput()
1527 if err != nil {
1528 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1529 }
1530 return string(output), nil
1531 }
1532
1533 // Otherwise, get the diff between the initial commit and the current state using exec.Command
Philip Zeyliger49edc922025-05-14 09:45:45 -07001534 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.SketchGitBaseRef())
Earl Lee2e463fb2025-04-17 11:22:22 -07001535 cmd.Dir = a.repoRoot
1536 output, err := cmd.CombinedOutput()
1537 if err != nil {
1538 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1539 }
1540
1541 return string(output), nil
1542}
1543
Philip Zeyliger49edc922025-05-14 09:45:45 -07001544// SketchGitBaseRef distinguishes between the typical container version, where sketch-base is
1545// unambiguous, and the "unsafe" version, where we need to use a session id to disambiguate.
1546func (a *Agent) SketchGitBaseRef() string {
1547 if a.IsInContainer() {
1548 return "sketch-base"
1549 } else {
1550 return "sketch-base-" + a.SessionID()
1551 }
1552}
1553
1554// SketchGitBase returns the Git commit hash that was saved when the agent was instantiated.
1555func (a *Agent) SketchGitBase() string {
1556 cmd := exec.CommandContext(context.Background(), "git", "rev-parse", a.SketchGitBaseRef())
1557 cmd.Dir = a.repoRoot
1558 output, err := cmd.CombinedOutput()
1559 if err != nil {
1560 slog.Warn("could not identify sketch-base", slog.String("error", err.Error()))
1561 return "HEAD"
1562 }
1563 return string(strings.TrimSpace(string(output)))
Earl Lee2e463fb2025-04-17 11:22:22 -07001564}
1565
Pokey Rule7a113622025-05-12 10:58:45 +01001566// removeGitHooks removes the Git hooks directory from the repository
1567func removeGitHooks(_ context.Context, repoPath string) error {
1568 hooksDir := filepath.Join(repoPath, ".git", "hooks")
1569
1570 // Check if hooks directory exists
1571 if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
1572 // Directory doesn't exist, nothing to do
1573 return nil
1574 }
1575
1576 // Remove the hooks directory
1577 err := os.RemoveAll(hooksDir)
1578 if err != nil {
1579 return fmt.Errorf("failed to remove git hooks directory: %w", err)
1580 }
1581
1582 // Create an empty hooks directory to prevent git from recreating default hooks
Autoformattere577ef72025-05-12 10:29:00 +00001583 err = os.MkdirAll(hooksDir, 0o755)
Pokey Rule7a113622025-05-12 10:58:45 +01001584 if err != nil {
1585 return fmt.Errorf("failed to create empty git hooks directory: %w", err)
1586 }
1587
1588 return nil
1589}
1590
Earl Lee2e463fb2025-04-17 11:22:22 -07001591// handleGitCommits() highlights new commits to the user. When running
1592// under docker, new HEADs are pushed to a branch according to the title.
1593func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1594 if a.repoRoot == "" {
1595 return nil, nil
1596 }
1597
1598 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1599 if err != nil {
1600 return nil, err
1601 }
1602 if head == a.lastHEAD {
1603 return nil, nil // nothing to do
1604 }
1605 defer func() {
1606 a.lastHEAD = head
1607 }()
1608
1609 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1610 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1611 // to the last 100 commits.
1612 var commits []*GitCommit
1613
1614 // Get commits since the initial commit
1615 // Format: <hash>\0<subject>\0<body>\0
1616 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1617 // Limit to 100 commits to avoid overwhelming the user
Philip Zeyliger49edc922025-05-14 09:45:45 -07001618 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+a.SketchGitBaseRef(), head)
Earl Lee2e463fb2025-04-17 11:22:22 -07001619 cmd.Dir = a.repoRoot
1620 output, err := cmd.Output()
1621 if err != nil {
1622 return nil, fmt.Errorf("failed to get git log: %w", err)
1623 }
1624
1625 // Parse git log output and filter out already seen commits
1626 parsedCommits := parseGitLog(string(output))
1627
1628 var headCommit *GitCommit
1629
1630 // Filter out commits we've already seen
1631 for _, commit := range parsedCommits {
1632 if commit.Hash == head {
1633 headCommit = &commit
1634 }
1635
1636 // Skip if we've seen this commit before. If our head has changed, always include that.
1637 if a.seenCommits[commit.Hash] && commit.Hash != head {
1638 continue
1639 }
1640
1641 // Mark this commit as seen
1642 a.seenCommits[commit.Hash] = true
1643
1644 // Add to our list of new commits
1645 commits = append(commits, &commit)
1646 }
1647
1648 if a.gitRemoteAddr != "" {
1649 if headCommit == nil {
1650 // I think this can only happen if we have a bug or if there's a race.
1651 headCommit = &GitCommit{}
1652 headCommit.Hash = head
1653 headCommit.Subject = "unknown"
1654 commits = append(commits, headCommit)
1655 }
1656
Philip Zeyliger113e2052025-05-09 21:59:40 +00001657 originalBranch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
1658 branch := originalBranch
Earl Lee2e463fb2025-04-17 11:22:22 -07001659
1660 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1661 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1662 // then use push with lease to replace.
Philip Zeyliger113e2052025-05-09 21:59:40 +00001663
1664 // Try up to 10 times with different branch names if the branch is checked out on the remote
1665 var out []byte
1666 var err error
1667 for retries := range 10 {
1668 if retries > 0 {
1669 // Add a numeric suffix to the branch name
1670 branch = fmt.Sprintf("%s%d", originalBranch, retries)
1671 }
1672
1673 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1674 cmd.Dir = a.workingDir
1675 out, err = cmd.CombinedOutput()
1676
1677 if err == nil {
1678 // Success! Break out of the retry loop
1679 break
1680 }
1681
1682 // Check if this is the "refusing to update checked out branch" error
1683 if !strings.Contains(string(out), "refusing to update checked out branch") {
1684 // This is a different error, so don't retry
1685 break
1686 }
1687
1688 // If we're on the last retry, we'll report the error
1689 if retries == 9 {
1690 break
1691 }
1692 }
1693
1694 if err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -07001695 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1696 } else {
1697 headCommit.PushedBranch = branch
Philip Zeyliger113e2052025-05-09 21:59:40 +00001698 // Update the agent's branch name if we ended up using a different one
1699 if branch != originalBranch {
1700 a.branchName = branch
1701 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001702 }
1703 }
1704
1705 // If we found new commits, create a message
1706 if len(commits) > 0 {
1707 msg := AgentMessage{
1708 Type: CommitMessageType,
1709 Timestamp: time.Now(),
1710 Commits: commits,
1711 }
1712 a.pushToOutbox(ctx, msg)
1713 }
1714 return commits, nil
1715}
1716
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001717func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001718 return strings.Map(func(r rune) rune {
1719 // lowercase
1720 if r >= 'A' && r <= 'Z' {
1721 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001722 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001723 // replace spaces with dashes
1724 if r == ' ' {
1725 return '-'
1726 }
1727 // allow alphanumerics and dashes
1728 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1729 return r
1730 }
1731 return -1
1732 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001733}
1734
1735// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1736// and returns an array of GitCommit structs.
1737func parseGitLog(output string) []GitCommit {
1738 var commits []GitCommit
1739
1740 // No output means no commits
1741 if len(output) == 0 {
1742 return commits
1743 }
1744
1745 // Split by NULL byte
1746 parts := strings.Split(output, "\x00")
1747
1748 // Process in triplets (hash, subject, body)
1749 for i := 0; i < len(parts); i++ {
1750 // Skip empty parts
1751 if parts[i] == "" {
1752 continue
1753 }
1754
1755 // This should be a hash
1756 hash := strings.TrimSpace(parts[i])
1757
1758 // Make sure we have at least a subject part available
1759 if i+1 >= len(parts) {
1760 break // No more parts available
1761 }
1762
1763 // Get the subject
1764 subject := strings.TrimSpace(parts[i+1])
1765
1766 // Get the body if available
1767 body := ""
1768 if i+2 < len(parts) {
1769 body = strings.TrimSpace(parts[i+2])
1770 }
1771
1772 // Skip to the next triplet
1773 i += 2
1774
1775 commits = append(commits, GitCommit{
1776 Hash: hash,
1777 Subject: subject,
1778 Body: body,
1779 })
1780 }
1781
1782 return commits
1783}
1784
1785func repoRoot(ctx context.Context, dir string) (string, error) {
1786 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1787 stderr := new(strings.Builder)
1788 cmd.Stderr = stderr
1789 cmd.Dir = dir
1790 out, err := cmd.Output()
1791 if err != nil {
1792 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1793 }
1794 return strings.TrimSpace(string(out)), nil
1795}
1796
1797func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1798 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1799 stderr := new(strings.Builder)
1800 cmd.Stderr = stderr
1801 cmd.Dir = dir
1802 out, err := cmd.Output()
1803 if err != nil {
1804 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1805 }
1806 // TODO: validate that out is valid hex
1807 return strings.TrimSpace(string(out)), nil
1808}
1809
1810// isValidGitSHA validates if a string looks like a valid git SHA hash.
1811// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1812func isValidGitSHA(sha string) bool {
1813 // Git SHA must be a hexadecimal string with at least 4 characters
1814 if len(sha) < 4 || len(sha) > 40 {
1815 return false
1816 }
1817
1818 // Check if the string only contains hexadecimal characters
1819 for _, char := range sha {
1820 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1821 return false
1822 }
1823 }
1824
1825 return true
1826}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001827
1828// getGitOrigin returns the URL of the git remote 'origin' if it exists
1829func getGitOrigin(ctx context.Context, dir string) string {
1830 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1831 cmd.Dir = dir
1832 stderr := new(strings.Builder)
1833 cmd.Stderr = stderr
1834 out, err := cmd.Output()
1835 if err != nil {
1836 return ""
1837 }
1838 return strings.TrimSpace(string(out))
1839}
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001840
1841func (a *Agent) initGitRevision(ctx context.Context, workingDir, revision string) error {
1842 cmd := exec.CommandContext(ctx, "git", "stash")
1843 cmd.Dir = workingDir
1844 if out, err := cmd.CombinedOutput(); err != nil {
1845 return fmt.Errorf("git stash: %s: %v", out, err)
1846 }
Josh Bleecher Snyder76ccdfd2025-05-01 17:14:18 +00001847 cmd = exec.CommandContext(ctx, "git", "fetch", "--prune", "sketch-host")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001848 cmd.Dir = workingDir
1849 if out, err := cmd.CombinedOutput(); err != nil {
1850 return fmt.Errorf("git fetch: %s: %w", out, err)
1851 }
1852 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", revision)
1853 cmd.Dir = workingDir
1854 if out, err := cmd.CombinedOutput(); err != nil {
1855 return fmt.Errorf("git checkout %s: %s: %w", revision, out, err)
1856 }
1857 a.lastHEAD = revision
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001858 return nil
1859}
1860
1861func (a *Agent) RestartConversation(ctx context.Context, rev string, initialPrompt string) error {
1862 a.mu.Lock()
1863 a.title = ""
1864 a.firstMessageIndex = len(a.history)
1865 a.convo = a.initConvo()
1866 gitReset := func() error {
1867 if a.config.InDocker && rev != "" {
1868 err := a.initGitRevision(ctx, a.workingDir, rev)
1869 if err != nil {
1870 return err
1871 }
1872 } else if !a.config.InDocker && rev != "" {
1873 return fmt.Errorf("Not resetting git repo when working outside of a container.")
1874 }
1875 return nil
1876 }
1877 err := gitReset()
1878 a.mu.Unlock()
1879 if err != nil {
1880 a.pushToOutbox(a.config.Context, errorMessage(err))
1881 }
1882
1883 a.pushToOutbox(a.config.Context, AgentMessage{
1884 Type: AgentMessageType, Content: "Conversation restarted.",
1885 })
1886 if initialPrompt != "" {
1887 a.UserMessage(ctx, initialPrompt)
1888 }
1889 return nil
1890}
1891
1892func (a *Agent) SuggestReprompt(ctx context.Context) (string, error) {
1893 msg := `The user has requested a suggestion for a re-prompt.
1894
1895 Given the current conversation thus far, suggest a re-prompt that would
1896 capture the instructions and feedback so far, as well as any
1897 research or other information that would be helpful in implementing
1898 the task.
1899
1900 Reply with ONLY the reprompt text.
1901 `
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001902 userMessage := llm.UserStringMessage(msg)
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001903 // By doing this in a subconversation, the agent doesn't call tools (because
1904 // there aren't any), and there's not a concurrency risk with on-going other
1905 // outstanding conversations.
1906 convo := a.convo.SubConvoWithHistory()
1907 resp, err := convo.SendMessage(userMessage)
1908 if err != nil {
1909 a.pushToOutbox(ctx, errorMessage(err))
1910 return "", err
1911 }
1912 textContent := collectTextContent(resp)
1913 return textContent, nil
1914}
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001915
1916// systemPromptData contains the data used to render the system prompt template
1917type systemPromptData struct {
1918 EditPrompt string
1919 ClientGOOS string
1920 ClientGOARCH string
1921 WorkingDir string
1922 RepoRoot string
1923 InitialCommit string
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001924 Codebase *onstart.Codebase
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001925}
1926
1927// renderSystemPrompt renders the system prompt template.
1928func (a *Agent) renderSystemPrompt() string {
1929 // Determine the appropriate edit prompt based on config
1930 var editPrompt string
1931 if a.config.UseAnthropicEdit {
1932 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."
1933 } else {
1934 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
1935 }
1936
1937 data := systemPromptData{
1938 EditPrompt: editPrompt,
1939 ClientGOOS: a.config.ClientGOOS,
1940 ClientGOARCH: a.config.ClientGOARCH,
1941 WorkingDir: a.workingDir,
1942 RepoRoot: a.repoRoot,
Philip Zeyliger49edc922025-05-14 09:45:45 -07001943 InitialCommit: a.SketchGitBase(),
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001944 Codebase: a.codebase,
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001945 }
1946
1947 tmpl, err := template.New("system").Parse(agentSystemPrompt)
1948 if err != nil {
1949 panic(fmt.Sprintf("failed to parse system prompt template: %v", err))
1950 }
1951 buf := new(strings.Builder)
1952 err = tmpl.Execute(buf, data)
1953 if err != nil {
1954 panic(fmt.Sprintf("failed to execute system prompt template: %v", err))
1955 }
Josh Bleecher Snydera997be62025-05-07 22:52:46 +00001956 // fmt.Printf("system prompt: %s\n", buf.String())
Josh Bleecher Snyder5cca56f2025-05-06 01:10:16 +00001957 return buf.String()
1958}
Philip Zeyligereab12de2025-05-14 02:35:53 +00001959
1960// StateTransitionIterator provides an iterator over state transitions.
1961type StateTransitionIterator interface {
1962 // Next blocks until a new state transition is available or context is done.
1963 // Returns nil if the context is cancelled.
1964 Next() *StateTransition
1965 // Close removes the listener and cleans up resources.
1966 Close()
1967}
1968
1969// StateTransitionIteratorImpl implements StateTransitionIterator using a state machine listener.
1970type StateTransitionIteratorImpl struct {
1971 agent *Agent
1972 ctx context.Context
1973 ch chan StateTransition
1974 unsubscribe func()
1975}
1976
1977// Next blocks until a new state transition is available or the context is cancelled.
1978func (s *StateTransitionIteratorImpl) Next() *StateTransition {
1979 select {
1980 case <-s.ctx.Done():
1981 return nil
1982 case transition, ok := <-s.ch:
1983 if !ok {
1984 return nil
1985 }
1986 transitionCopy := transition
1987 return &transitionCopy
1988 }
1989}
1990
1991// Close removes the listener and cleans up resources.
1992func (s *StateTransitionIteratorImpl) Close() {
1993 if s.unsubscribe != nil {
1994 s.unsubscribe()
1995 s.unsubscribe = nil
1996 }
1997}
1998
1999// NewStateTransitionIterator returns an iterator that receives state transitions.
2000func (a *Agent) NewStateTransitionIterator(ctx context.Context) StateTransitionIterator {
2001 a.mu.Lock()
2002 defer a.mu.Unlock()
2003
2004 // Create channel to receive state transitions
2005 ch := make(chan StateTransition, 10)
2006
2007 // Add a listener to the state machine
2008 unsubscribe := a.stateMachine.AddTransitionListener(ch)
2009
2010 return &StateTransitionIteratorImpl{
2011 agent: a,
2012 ctx: ctx,
2013 ch: ch,
2014 unsubscribe: unsubscribe,
2015 }
2016}