blob: a130c967841aed33c21d11e7e370f2a63c5a1e73 [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"
9 "log/slog"
10 "net/http"
11 "os"
12 "os/exec"
13 "runtime/debug"
14 "slices"
15 "strings"
16 "sync"
17 "time"
18
19 "sketch.dev/ant"
20 "sketch.dev/claudetool"
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +000021 "sketch.dev/claudetool/bashkit"
Earl Lee2e463fb2025-04-17 11:22:22 -070022)
23
24const (
25 userCancelMessage = "user requested agent to stop handling responses"
26)
27
28type CodingAgent interface {
29 // Init initializes an agent inside a docker container.
30 Init(AgentInit) error
31
32 // Ready returns a channel closed after Init successfully called.
33 Ready() <-chan struct{}
34
35 // URL reports the HTTP URL of this agent.
36 URL() string
37
38 // UserMessage enqueues a message to the agent and returns immediately.
39 UserMessage(ctx context.Context, msg string)
40
41 // WaitForMessage blocks until the agent has a response to give.
42 // Use AgentMessage.EndOfTurn to help determine if you want to
43 // drain the agent.
44 WaitForMessage(ctx context.Context) AgentMessage
45
46 // Loop begins the agent loop returns only when ctx is cancelled.
47 Loop(ctx context.Context)
48
49 CancelInnerLoop(cause error)
50
51 CancelToolUse(toolUseID string, cause error) error
52
53 // Returns a subset of the agent's message history.
54 Messages(start int, end int) []AgentMessage
55
56 // Returns the current number of messages in the history
57 MessageCount() int
58
59 TotalUsage() ant.CumulativeUsage
60 OriginalBudget() ant.Budget
61
62 // WaitForMessageCount returns when the agent has at more than clientMessageCount messages or the context is done.
63 WaitForMessageCount(ctx context.Context, greaterThan int)
64
65 WorkingDir() string
66
67 // Diff returns a unified diff of changes made since the agent was instantiated.
68 // If commit is non-nil, it shows the diff for just that specific commit.
69 Diff(commit *string) (string, error)
70
71 // InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
72 InitialCommit() string
73
74 // Title returns the current title of the conversation.
75 Title() string
76
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000077 // BranchName returns the git branch name for the conversation.
78 BranchName() string
79
Earl Lee2e463fb2025-04-17 11:22:22 -070080 // OS returns the operating system of the client.
81 OS() string
Philip Zeyliger99a9a022025-04-27 15:15:25 +000082
Philip Zeyligerc72fff52025-04-29 20:17:54 +000083 // SessionID returns the unique session identifier.
84 SessionID() string
85
Philip Zeyliger99a9a022025-04-27 15:15:25 +000086 // OutstandingLLMCallCount returns the number of outstanding LLM calls.
87 OutstandingLLMCallCount() int
88
89 // OutstandingToolCalls returns the names of outstanding tool calls.
90 OutstandingToolCalls() []string
Philip Zeyliger18532b22025-04-23 21:11:46 +000091 OutsideOS() string
92 OutsideHostname() string
93 OutsideWorkingDir() string
Philip Zeyligerd1402952025-04-23 03:54:37 +000094 GitOrigin() string
Earl Lee2e463fb2025-04-17 11:22:22 -070095}
96
97type CodingAgentMessageType string
98
99const (
100 UserMessageType CodingAgentMessageType = "user"
101 AgentMessageType CodingAgentMessageType = "agent"
102 ErrorMessageType CodingAgentMessageType = "error"
103 BudgetMessageType CodingAgentMessageType = "budget" // dedicated for "out of budget" errors
104 ToolUseMessageType CodingAgentMessageType = "tool"
105 CommitMessageType CodingAgentMessageType = "commit" // for displaying git commits
106 AutoMessageType CodingAgentMessageType = "auto" // for automated notifications like autoformatting
107
108 cancelToolUseMessage = "Stop responding to my previous message. Wait for me to ask you something else before attempting to use any more tools."
109)
110
111type AgentMessage struct {
112 Type CodingAgentMessageType `json:"type"`
113 // EndOfTurn indicates that the AI is done working and is ready for the next user input.
114 EndOfTurn bool `json:"end_of_turn"`
115
116 Content string `json:"content"`
117 ToolName string `json:"tool_name,omitempty"`
118 ToolInput string `json:"input,omitempty"`
119 ToolResult string `json:"tool_result,omitempty"`
120 ToolError bool `json:"tool_error,omitempty"`
121 ToolCallId string `json:"tool_call_id,omitempty"`
122
123 // ToolCalls is a list of all tool calls requested in this message (name and input pairs)
124 ToolCalls []ToolCall `json:"tool_calls,omitempty"`
125
Sean McCulloughd9f13372025-04-21 15:08:49 -0700126 // ToolResponses is a list of all responses to tool calls requested in this message (name and input pairs)
127 ToolResponses []AgentMessage `json:"toolResponses,omitempty"`
128
Earl Lee2e463fb2025-04-17 11:22:22 -0700129 // Commits is a list of git commits for a commit message
130 Commits []*GitCommit `json:"commits,omitempty"`
131
132 Timestamp time.Time `json:"timestamp"`
133 ConversationID string `json:"conversation_id"`
134 ParentConversationID *string `json:"parent_conversation_id,omitempty"`
135 Usage *ant.Usage `json:"usage,omitempty"`
136
137 // Message timing information
138 StartTime *time.Time `json:"start_time,omitempty"`
139 EndTime *time.Time `json:"end_time,omitempty"`
140 Elapsed *time.Duration `json:"elapsed,omitempty"`
141
142 // Turn duration - the time taken for a complete agent turn
143 TurnDuration *time.Duration `json:"turnDuration,omitempty"`
144
145 Idx int `json:"idx"`
146}
147
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700148// SetConvo sets m.ConversationID and m.ParentConversationID based on convo.
149func (m *AgentMessage) SetConvo(convo *ant.Convo) {
150 if convo == nil {
151 m.ConversationID = ""
152 m.ParentConversationID = nil
153 return
154 }
155 m.ConversationID = convo.ID
156 if convo.Parent != nil {
157 m.ParentConversationID = &convo.Parent.ID
158 }
159}
160
Earl Lee2e463fb2025-04-17 11:22:22 -0700161// GitCommit represents a single git commit for a commit message
162type GitCommit struct {
163 Hash string `json:"hash"` // Full commit hash
164 Subject string `json:"subject"` // Commit subject line
165 Body string `json:"body"` // Full commit message body
166 PushedBranch string `json:"pushed_branch,omitempty"` // If set, this commit was pushed to this branch
167}
168
169// ToolCall represents a single tool call within an agent message
170type ToolCall struct {
Sean McCulloughd9f13372025-04-21 15:08:49 -0700171 Name string `json:"name"`
172 Input string `json:"input"`
173 ToolCallId string `json:"tool_call_id"`
174 ResultMessage *AgentMessage `json:"result_message,omitempty"`
175 Args string `json:"args,omitempty"`
176 Result string `json:"result,omitempty"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700177}
178
179func (a *AgentMessage) Attr() slog.Attr {
180 var attrs []any = []any{
181 slog.String("type", string(a.Type)),
182 }
183 if a.EndOfTurn {
184 attrs = append(attrs, slog.Bool("end_of_turn", a.EndOfTurn))
185 }
186 if a.Content != "" {
187 attrs = append(attrs, slog.String("content", a.Content))
188 }
189 if a.ToolName != "" {
190 attrs = append(attrs, slog.String("tool_name", a.ToolName))
191 }
192 if a.ToolInput != "" {
193 attrs = append(attrs, slog.String("tool_input", a.ToolInput))
194 }
195 if a.Elapsed != nil {
196 attrs = append(attrs, slog.Int64("elapsed", a.Elapsed.Nanoseconds()))
197 }
198 if a.TurnDuration != nil {
199 attrs = append(attrs, slog.Int64("turnDuration", a.TurnDuration.Nanoseconds()))
200 }
201 if a.ToolResult != "" {
202 attrs = append(attrs, slog.String("tool_result", a.ToolResult))
203 }
204 if a.ToolError {
205 attrs = append(attrs, slog.Bool("tool_error", a.ToolError))
206 }
207 if len(a.ToolCalls) > 0 {
208 toolCallAttrs := make([]any, 0, len(a.ToolCalls))
209 for i, tc := range a.ToolCalls {
210 toolCallAttrs = append(toolCallAttrs, slog.Group(
211 fmt.Sprintf("tool_call_%d", i),
212 slog.String("name", tc.Name),
213 slog.String("input", tc.Input),
214 ))
215 }
216 attrs = append(attrs, slog.Group("tool_calls", toolCallAttrs...))
217 }
218 if a.ConversationID != "" {
219 attrs = append(attrs, slog.String("convo_id", a.ConversationID))
220 }
221 if a.ParentConversationID != nil {
222 attrs = append(attrs, slog.String("parent_convo_id", *a.ParentConversationID))
223 }
224 if a.Usage != nil && !a.Usage.IsZero() {
225 attrs = append(attrs, a.Usage.Attr())
226 }
227 // TODO: timestamp, convo ids, idx?
228 return slog.Group("agent_message", attrs...)
229}
230
231func errorMessage(err error) AgentMessage {
232 // It's somewhat unknowable whether error messages are "end of turn" or not, but it seems like the best approach.
233 if os.Getenv(("DEBUG")) == "1" {
234 return AgentMessage{Type: ErrorMessageType, Content: err.Error() + " Stacktrace: " + string(debug.Stack()), EndOfTurn: true}
235 }
236
237 return AgentMessage{Type: ErrorMessageType, Content: err.Error(), EndOfTurn: true}
238}
239
240func budgetMessage(err error) AgentMessage {
241 return AgentMessage{Type: BudgetMessageType, Content: err.Error(), EndOfTurn: true}
242}
243
244// ConvoInterface defines the interface for conversation interactions
245type ConvoInterface interface {
246 CumulativeUsage() ant.CumulativeUsage
247 ResetBudget(ant.Budget)
248 OverBudget() error
249 SendMessage(message ant.Message) (*ant.MessageResponse, error)
250 SendUserTextMessage(s string, otherContents ...ant.Content) (*ant.MessageResponse, error)
251 ToolResultContents(ctx context.Context, resp *ant.MessageResponse) ([]ant.Content, error)
252 ToolResultCancelContents(resp *ant.MessageResponse) ([]ant.Content, error)
253 CancelToolUse(toolUseID string, cause error) error
254}
255
256type Agent struct {
257 convo ConvoInterface
258 config AgentConfig // config for this agent
259 workingDir string
260 repoRoot string // workingDir may be a subdir of repoRoot
261 url string
262 lastHEAD string // hash of the last HEAD that was pushed to the host (only when under docker)
263 initialCommit string // hash of the Git HEAD when the agent was instantiated or Init()
264 gitRemoteAddr string // HTTP URL of the host git repo (only when under docker)
265 ready chan struct{} // closed when the agent is initialized (only when under docker)
266 startedAt time.Time
267 originalBudget ant.Budget
268 title string
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700269 branchName string
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 codereview *claudetool.CodeReviewer
Philip Zeyliger18532b22025-04-23 21:11:46 +0000271 // Outside information
272 outsideHostname string
273 outsideOS string
274 outsideWorkingDir string
Philip Zeyligerd1402952025-04-23 03:54:37 +0000275 // URL of the git remote 'origin' if it exists
276 gitOrigin string
Earl Lee2e463fb2025-04-17 11:22:22 -0700277
278 // Time when the current turn started (reset at the beginning of InnerLoop)
279 startOfTurn time.Time
280
281 // Inbox - for messages from the user to the agent.
282 // sent on by UserMessage
283 // . e.g. when user types into the chat textarea
284 // read from by GatherMessages
285 inbox chan string
286
287 // Outbox
288 // sent on by pushToOutbox
289 // via OnToolResult and OnResponse callbacks
290 // read from by WaitForMessage
291 // called by termui inside its repl loop.
292 outbox chan AgentMessage
293
294 // protects cancelInnerLoop
295 cancelInnerLoopMu sync.Mutex
296 // cancels potentially long-running tool_use calls or chains of them
297 cancelInnerLoop context.CancelCauseFunc
298
299 // protects following
300 mu sync.Mutex
301
302 // Stores all messages for this agent
303 history []AgentMessage
304
305 listeners []chan struct{}
306
307 // Track git commits we've already seen (by hash)
308 seenCommits map[string]bool
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000309
310 // Track outstanding LLM call IDs
311 outstandingLLMCalls map[string]struct{}
312
313 // Track outstanding tool calls by ID with their names
314 outstandingToolCalls map[string]string
Earl Lee2e463fb2025-04-17 11:22:22 -0700315}
316
317func (a *Agent) URL() string { return a.url }
318
319// Title returns the current title of the conversation.
320// If no title has been set, returns an empty string.
321func (a *Agent) Title() string {
322 a.mu.Lock()
323 defer a.mu.Unlock()
324 return a.title
325}
326
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000327// BranchName returns the git branch name for the conversation.
328func (a *Agent) BranchName() string {
329 a.mu.Lock()
330 defer a.mu.Unlock()
331 return a.branchName
332}
333
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000334// OutstandingLLMCallCount returns the number of outstanding LLM calls.
335func (a *Agent) OutstandingLLMCallCount() int {
336 a.mu.Lock()
337 defer a.mu.Unlock()
338 return len(a.outstandingLLMCalls)
339}
340
341// OutstandingToolCalls returns the names of outstanding tool calls.
342func (a *Agent) OutstandingToolCalls() []string {
343 a.mu.Lock()
344 defer a.mu.Unlock()
345
346 tools := make([]string, 0, len(a.outstandingToolCalls))
347 for _, toolName := range a.outstandingToolCalls {
348 tools = append(tools, toolName)
349 }
350 return tools
351}
352
Earl Lee2e463fb2025-04-17 11:22:22 -0700353// OS returns the operating system of the client.
354func (a *Agent) OS() string {
355 return a.config.ClientGOOS
356}
357
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000358func (a *Agent) SessionID() string {
359 return a.config.SessionID
360}
361
Philip Zeyliger18532b22025-04-23 21:11:46 +0000362// OutsideOS returns the operating system of the outside system.
363func (a *Agent) OutsideOS() string {
364 return a.outsideOS
Philip Zeyligerd1402952025-04-23 03:54:37 +0000365}
366
Philip Zeyliger18532b22025-04-23 21:11:46 +0000367// OutsideHostname returns the hostname of the outside system.
368func (a *Agent) OutsideHostname() string {
369 return a.outsideHostname
Philip Zeyligerd1402952025-04-23 03:54:37 +0000370}
371
Philip Zeyliger18532b22025-04-23 21:11:46 +0000372// OutsideWorkingDir returns the working directory on the outside system.
373func (a *Agent) OutsideWorkingDir() string {
374 return a.outsideWorkingDir
Philip Zeyligerd1402952025-04-23 03:54:37 +0000375}
376
377// GitOrigin returns the URL of the git remote 'origin' if it exists.
378func (a *Agent) GitOrigin() string {
379 return a.gitOrigin
380}
381
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700382// SetTitleBranch sets the title and branch name of the conversation.
383func (a *Agent) SetTitleBranch(title, branchName string) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700384 a.mu.Lock()
385 defer a.mu.Unlock()
386 a.title = title
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700387 a.branchName = branchName
Earl Lee2e463fb2025-04-17 11:22:22 -0700388 // Notify all listeners that the state has changed
389 for _, ch := range a.listeners {
390 close(ch)
391 }
392 a.listeners = a.listeners[:0]
393}
394
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000395// OnToolCall implements ant.Listener and tracks the start of a tool call.
396func (a *Agent) OnToolCall(ctx context.Context, convo *ant.Convo, id string, toolName string, toolInput json.RawMessage, content ant.Content) {
397 // Track the tool call
398 a.mu.Lock()
399 a.outstandingToolCalls[id] = toolName
400 a.mu.Unlock()
401}
402
Earl Lee2e463fb2025-04-17 11:22:22 -0700403// OnToolResult implements ant.Listener.
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000404func (a *Agent) OnToolResult(ctx context.Context, convo *ant.Convo, toolID string, toolName string, toolInput json.RawMessage, content ant.Content, result *string, err error) {
405 // Remove the tool call from outstanding calls
406 a.mu.Lock()
407 delete(a.outstandingToolCalls, toolID)
408 a.mu.Unlock()
409
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 m := AgentMessage{
411 Type: ToolUseMessageType,
412 Content: content.Text,
413 ToolResult: content.ToolResult,
414 ToolError: content.ToolError,
415 ToolName: toolName,
416 ToolInput: string(toolInput),
417 ToolCallId: content.ToolUseID,
418 StartTime: content.StartTime,
419 EndTime: content.EndTime,
420 }
421
422 // Calculate the elapsed time if both start and end times are set
423 if content.StartTime != nil && content.EndTime != nil {
424 elapsed := content.EndTime.Sub(*content.StartTime)
425 m.Elapsed = &elapsed
426 }
427
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700428 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700429 a.pushToOutbox(ctx, m)
430}
431
432// OnRequest implements ant.Listener.
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000433func (a *Agent) OnRequest(ctx context.Context, convo *ant.Convo, id string, msg *ant.Message) {
434 a.mu.Lock()
435 defer a.mu.Unlock()
436 a.outstandingLLMCalls[id] = struct{}{}
Earl Lee2e463fb2025-04-17 11:22:22 -0700437 // We already get tool results from the above. We send user messages to the outbox in the agent loop.
438}
439
440// OnResponse implements ant.Listener. Responses contain messages from the LLM
441// that need to be displayed (as well as tool calls that we send along when
442// they're done). (It would be reasonable to also mention tool calls when they're
443// started, but we don't do that yet.)
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000444func (a *Agent) OnResponse(ctx context.Context, convo *ant.Convo, id string, resp *ant.MessageResponse) {
445 // Remove the LLM call from outstanding calls
446 a.mu.Lock()
447 delete(a.outstandingLLMCalls, id)
448 a.mu.Unlock()
449
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700450 if resp == nil {
451 // LLM API call failed
452 m := AgentMessage{
453 Type: ErrorMessageType,
454 Content: "API call failed, type 'continue' to try again",
455 }
456 m.SetConvo(convo)
457 a.pushToOutbox(ctx, m)
458 return
459 }
460
Earl Lee2e463fb2025-04-17 11:22:22 -0700461 endOfTurn := false
462 if resp.StopReason != ant.StopReasonToolUse {
463 endOfTurn = true
464 }
465 m := AgentMessage{
466 Type: AgentMessageType,
467 Content: collectTextContent(resp),
468 EndOfTurn: endOfTurn,
469 Usage: &resp.Usage,
470 StartTime: resp.StartTime,
471 EndTime: resp.EndTime,
472 }
473
474 // Extract any tool calls from the response
475 if resp.StopReason == ant.StopReasonToolUse {
476 var toolCalls []ToolCall
477 for _, part := range resp.Content {
478 if part.Type == "tool_use" {
479 toolCalls = append(toolCalls, ToolCall{
480 Name: part.ToolName,
481 Input: string(part.ToolInput),
482 ToolCallId: part.ID,
483 })
484 }
485 }
486 m.ToolCalls = toolCalls
487 }
488
489 // Calculate the elapsed time if both start and end times are set
490 if resp.StartTime != nil && resp.EndTime != nil {
491 elapsed := resp.EndTime.Sub(*resp.StartTime)
492 m.Elapsed = &elapsed
493 }
494
Josh Bleecher Snyder50a1d622025-04-29 09:59:03 -0700495 m.SetConvo(convo)
Earl Lee2e463fb2025-04-17 11:22:22 -0700496 a.pushToOutbox(ctx, m)
497}
498
499// WorkingDir implements CodingAgent.
500func (a *Agent) WorkingDir() string {
501 return a.workingDir
502}
503
504// MessageCount implements CodingAgent.
505func (a *Agent) MessageCount() int {
506 a.mu.Lock()
507 defer a.mu.Unlock()
508 return len(a.history)
509}
510
511// Messages implements CodingAgent.
512func (a *Agent) Messages(start int, end int) []AgentMessage {
513 a.mu.Lock()
514 defer a.mu.Unlock()
515 return slices.Clone(a.history[start:end])
516}
517
518func (a *Agent) OriginalBudget() ant.Budget {
519 return a.originalBudget
520}
521
522// AgentConfig contains configuration for creating a new Agent.
523type AgentConfig struct {
524 Context context.Context
525 AntURL string
526 APIKey string
527 HTTPC *http.Client
528 Budget ant.Budget
529 GitUsername string
530 GitEmail string
531 SessionID string
532 ClientGOOS string
533 ClientGOARCH string
534 UseAnthropicEdit bool
Philip Zeyliger18532b22025-04-23 21:11:46 +0000535 // Outside information
536 OutsideHostname string
537 OutsideOS string
538 OutsideWorkingDir string
Earl Lee2e463fb2025-04-17 11:22:22 -0700539}
540
541// NewAgent creates a new Agent.
542// It is not usable until Init() is called.
543func NewAgent(config AgentConfig) *Agent {
544 agent := &Agent{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000545 config: config,
546 ready: make(chan struct{}),
547 inbox: make(chan string, 100),
548 outbox: make(chan AgentMessage, 100),
549 startedAt: time.Now(),
550 originalBudget: config.Budget,
551 seenCommits: make(map[string]bool),
552 outsideHostname: config.OutsideHostname,
553 outsideOS: config.OutsideOS,
554 outsideWorkingDir: config.OutsideWorkingDir,
555 outstandingLLMCalls: make(map[string]struct{}),
556 outstandingToolCalls: make(map[string]string),
Earl Lee2e463fb2025-04-17 11:22:22 -0700557 }
558 return agent
559}
560
561type AgentInit struct {
562 WorkingDir string
563 NoGit bool // only for testing
564
565 InDocker bool
566 Commit string
567 GitRemoteAddr string
568 HostAddr string
569}
570
571func (a *Agent) Init(ini AgentInit) error {
Josh Bleecher Snyder9c07e1d2025-04-28 19:25:37 -0700572 if a.convo != nil {
573 return fmt.Errorf("Agent.Init: already initialized")
574 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700575 ctx := a.config.Context
576 if ini.InDocker {
577 cmd := exec.CommandContext(ctx, "git", "stash")
578 cmd.Dir = ini.WorkingDir
579 if out, err := cmd.CombinedOutput(); err != nil {
580 return fmt.Errorf("git stash: %s: %v", out, err)
581 }
Philip Zeyligerd0ac1ea2025-04-21 20:04:19 -0700582 cmd = exec.CommandContext(ctx, "git", "remote", "add", "sketch-host", ini.GitRemoteAddr)
583 cmd.Dir = ini.WorkingDir
584 if out, err := cmd.CombinedOutput(); err != nil {
585 return fmt.Errorf("git remote add: %s: %v", out, err)
586 }
587 cmd = exec.CommandContext(ctx, "git", "fetch", "sketch-host")
Earl Lee2e463fb2025-04-17 11:22:22 -0700588 cmd.Dir = ini.WorkingDir
589 if out, err := cmd.CombinedOutput(); err != nil {
590 return fmt.Errorf("git fetch: %s: %w", out, err)
591 }
592 cmd = exec.CommandContext(ctx, "git", "checkout", "-f", ini.Commit)
593 cmd.Dir = ini.WorkingDir
594 if out, err := cmd.CombinedOutput(); err != nil {
595 return fmt.Errorf("git checkout %s: %s: %w", ini.Commit, out, err)
596 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700597 a.lastHEAD = ini.Commit
598 a.gitRemoteAddr = ini.GitRemoteAddr
599 a.initialCommit = ini.Commit
600 if ini.HostAddr != "" {
601 a.url = "http://" + ini.HostAddr
602 }
603 }
604 a.workingDir = ini.WorkingDir
605
606 if !ini.NoGit {
607 repoRoot, err := repoRoot(ctx, a.workingDir)
608 if err != nil {
609 return fmt.Errorf("repoRoot: %w", err)
610 }
611 a.repoRoot = repoRoot
612
613 commitHash, err := resolveRef(ctx, a.repoRoot, "HEAD")
614 if err != nil {
615 return fmt.Errorf("resolveRef: %w", err)
616 }
617 a.initialCommit = commitHash
618
619 codereview, err := claudetool.NewCodeReviewer(ctx, a.repoRoot, a.initialCommit)
620 if err != nil {
621 return fmt.Errorf("Agent.Init: claudetool.NewCodeReviewer: %w", err)
622 }
623 a.codereview = codereview
Philip Zeyligerd1402952025-04-23 03:54:37 +0000624
625 a.gitOrigin = getGitOrigin(ctx, ini.WorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700626 }
627 a.lastHEAD = a.initialCommit
628 a.convo = a.initConvo()
629 close(a.ready)
630 return nil
631}
632
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700633//go:embed agent_system_prompt.txt
634var agentSystemPrompt string
635
Earl Lee2e463fb2025-04-17 11:22:22 -0700636// initConvo initializes the conversation.
637// It must not be called until all agent fields are initialized,
638// particularly workingDir and git.
639func (a *Agent) initConvo() *ant.Convo {
640 ctx := a.config.Context
641 convo := ant.NewConvo(ctx, a.config.APIKey)
642 if a.config.HTTPC != nil {
643 convo.HTTPC = a.config.HTTPC
644 }
645 if a.config.AntURL != "" {
646 convo.URL = a.config.AntURL
647 }
648 convo.PromptCaching = true
649 convo.Budget = a.config.Budget
650
651 var editPrompt string
652 if a.config.UseAnthropicEdit {
653 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."
654 } else {
655 editPrompt = "Then use the patch tool to make those edits. Combine all edits to any given file into a single patch tool call."
656 }
657
Josh Bleecher Snyderdbe02302025-04-29 16:44:23 -0700658 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 -0700659
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000660 // Define a permission callback for the bash tool to check if the branch name is set before allowing git commits
661 bashPermissionCheck := func(command string) error {
662 // Check if branch name is set
663 a.mu.Lock()
664 branchSet := a.branchName != ""
665 a.mu.Unlock()
666
667 // If branch is set, all commands are allowed
668 if branchSet {
669 return nil
670 }
671
672 // If branch is not set, check if this is a git commit command
673 willCommit, err := bashkit.WillRunGitCommit(command)
674 if err != nil {
675 // If there's an error checking, we should allow the command to proceed
676 return nil
677 }
678
679 // If it's a git commit and branch is not set, return an error
680 if willCommit {
681 return fmt.Errorf("you must use the title tool before making git commits")
682 }
683
684 return nil
685 }
686
687 // Create a custom bash tool with the permission check
688 bashTool := claudetool.NewBashTool(bashPermissionCheck)
689
Earl Lee2e463fb2025-04-17 11:22:22 -0700690 // Register all tools with the conversation
691 // When adding, removing, or modifying tools here, double-check that the termui tool display
692 // template in termui/termui.go has pretty-printing support for all tools.
693 convo.Tools = []*ant.Tool{
Josh Bleecher Snyderd499fd62025-04-30 01:31:29 +0000694 bashTool, claudetool.Keyword,
Earl Lee2e463fb2025-04-17 11:22:22 -0700695 claudetool.Think, a.titleTool(), makeDoneTool(a.codereview, a.config.GitUsername, a.config.GitEmail),
696 a.codereview.Tool(),
697 }
698 if a.config.UseAnthropicEdit {
699 convo.Tools = append(convo.Tools, claudetool.AnthropicEditTool)
700 } else {
701 convo.Tools = append(convo.Tools, claudetool.Patch)
702 }
703 convo.Listener = a
704 return convo
705}
706
707func (a *Agent) titleTool() *ant.Tool {
Earl Lee2e463fb2025-04-17 11:22:22 -0700708 title := &ant.Tool{
709 Name: "title",
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700710 Description: `Sets the conversation title and creates a git branch for tracking work. MANDATORY: You must use this tool before making any git commits.`,
Earl Lee2e463fb2025-04-17 11:22:22 -0700711 InputSchema: json.RawMessage(`{
712 "type": "object",
713 "properties": {
714 "title": {
715 "type": "string",
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700716 "description": "A concise, descriptive title summarizing what this conversation is about"
717 },
718 "branch_name": {
719 "type": "string",
720 "description": "A 2-3 word alphanumeric hyphenated slug for the git branch name"
Earl Lee2e463fb2025-04-17 11:22:22 -0700721 }
722 },
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700723 "required": ["title", "branch_name"]
Earl Lee2e463fb2025-04-17 11:22:22 -0700724}`),
725 Run: func(ctx context.Context, input json.RawMessage) (string, error) {
726 var params struct {
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700727 Title string `json:"title"`
728 BranchName string `json:"branch_name"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700729 }
730 if err := json.Unmarshal(input, &params); err != nil {
731 return "", err
732 }
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -0700733 // It's unfortunate to not allow title changes,
734 // but it avoids having multiple branches.
735 t := a.Title()
736 if t != "" {
737 return "", fmt.Errorf("title already set to: %s", t)
738 }
739
740 if params.BranchName == "" {
741 return "", fmt.Errorf("branch_name parameter cannot be empty")
742 }
743 if params.Title == "" {
744 return "", fmt.Errorf("title parameter cannot be empty")
745 }
746
747 branchName := "sketch/" + cleanBranchName(params.BranchName)
748 a.SetTitleBranch(params.Title, branchName)
749
750 response := fmt.Sprintf("Title set to %q, branch name set to %q", params.Title, branchName)
751 return response, nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700752 },
753 }
754 return title
755}
756
757func (a *Agent) Ready() <-chan struct{} {
758 return a.ready
759}
760
761func (a *Agent) UserMessage(ctx context.Context, msg string) {
762 a.pushToOutbox(ctx, AgentMessage{Type: UserMessageType, Content: msg})
763 a.inbox <- msg
764}
765
766func (a *Agent) WaitForMessage(ctx context.Context) AgentMessage {
767 // TODO: Should this drain any outbox messages in case there are multiple?
768 select {
769 case msg := <-a.outbox:
770 return msg
771 case <-ctx.Done():
772 return errorMessage(ctx.Err())
773 }
774}
775
776func (a *Agent) CancelToolUse(toolUseID string, cause error) error {
777 return a.convo.CancelToolUse(toolUseID, cause)
778}
779
780func (a *Agent) CancelInnerLoop(cause error) {
781 a.cancelInnerLoopMu.Lock()
782 defer a.cancelInnerLoopMu.Unlock()
783 if a.cancelInnerLoop != nil {
784 a.cancelInnerLoop(cause)
785 }
786}
787
788func (a *Agent) Loop(ctxOuter context.Context) {
789 for {
790 select {
791 case <-ctxOuter.Done():
792 return
793 default:
794 ctxInner, cancel := context.WithCancelCause(ctxOuter)
795 a.cancelInnerLoopMu.Lock()
796 // Set .cancelInnerLoop so the user can cancel whatever is happening
797 // inside InnerLoop(ctxInner) without canceling this outer Loop execution.
798 // This CancelInnerLoop func is intended be called from other goroutines,
799 // hence the mutex.
800 a.cancelInnerLoop = cancel
801 a.cancelInnerLoopMu.Unlock()
802 a.InnerLoop(ctxInner)
803 cancel(nil)
804 }
805 }
806}
807
808func (a *Agent) pushToOutbox(ctx context.Context, m AgentMessage) {
809 if m.Timestamp.IsZero() {
810 m.Timestamp = time.Now()
811 }
812
813 // If this is an end-of-turn message, calculate the turn duration and add it to the message
814 if m.EndOfTurn && m.Type == AgentMessageType {
815 turnDuration := time.Since(a.startOfTurn)
816 m.TurnDuration = &turnDuration
817 slog.InfoContext(ctx, "Turn completed", "turnDuration", turnDuration)
818 }
819
820 slog.InfoContext(ctx, "agent message", m.Attr())
821
822 a.mu.Lock()
823 defer a.mu.Unlock()
824 m.Idx = len(a.history)
825 a.history = append(a.history, m)
826 a.outbox <- m
827
828 // Notify all listeners:
829 for _, ch := range a.listeners {
830 close(ch)
831 }
832 a.listeners = a.listeners[:0]
833}
834
835func (a *Agent) GatherMessages(ctx context.Context, block bool) ([]ant.Content, error) {
836 var m []ant.Content
837 if block {
838 select {
839 case <-ctx.Done():
840 return m, ctx.Err()
841 case msg := <-a.inbox:
842 m = append(m, ant.Content{Type: "text", Text: msg})
843 }
844 }
845 for {
846 select {
847 case msg := <-a.inbox:
848 m = append(m, ant.Content{Type: "text", Text: msg})
849 default:
850 return m, nil
851 }
852 }
853}
854
855func (a *Agent) InnerLoop(ctx context.Context) {
856 // Reset the start of turn time
857 a.startOfTurn = time.Now()
858
859 // Wait for at least one message from the user.
860 msgs, err := a.GatherMessages(ctx, true)
861 if err != nil { // e.g. the context was canceled while blocking in GatherMessages
862 return
863 }
864 // We do this as we go, but let's also do it at the end of the turn
865 defer func() {
866 if _, err := a.handleGitCommits(ctx); err != nil {
867 // Just log the error, don't stop execution
868 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
869 }
870 }()
871
872 userMessage := ant.Message{
873 Role: "user",
874 Content: msgs,
875 }
876 // convo.SendMessage does the actual network call to send this to anthropic. This blocks until the response is ready.
877 // TODO: pass ctx to SendMessage, and figure out how to square that ctx with convo's own .Ctx. Who owns the scope of this call?
878 resp, err := a.convo.SendMessage(userMessage)
879 if err != nil {
880 a.pushToOutbox(ctx, errorMessage(err))
881 return
882 }
883 for {
884 // TODO: here and below where we check the budget,
885 // we should review the UX: is it clear what happened?
886 // is it clear how to resume?
887 // should we let the user set a new budget?
888 if err := a.overBudget(ctx); err != nil {
889 return
890 }
891 if resp.StopReason != ant.StopReasonToolUse {
892 break
893 }
894 var results []ant.Content
895 cancelled := false
896 select {
897 case <-ctx.Done():
898 // Don't actually run any of the tools, but rather build a response
899 // for each tool_use message letting the LLM know that user canceled it.
900 results, err = a.convo.ToolResultCancelContents(resp)
901 if err != nil {
902 a.pushToOutbox(ctx, errorMessage(err))
903 }
904 cancelled = true
905 default:
906 ctx = claudetool.WithWorkingDir(ctx, a.workingDir)
907 // fall-through, when the user has not canceled the inner loop:
908 results, err = a.convo.ToolResultContents(ctx, resp)
909 if ctx.Err() != nil { // e.g. the user canceled the operation
910 cancelled = true
911 } else if err != nil {
912 a.pushToOutbox(ctx, errorMessage(err))
913 }
914 }
915
916 // Check for git commits. Currently we do this here, after we collect
917 // tool results, since that's when we know commits could have happened.
918 // We could instead do this when the turn ends, but I think it makes sense
919 // to do this as we go.
920 newCommits, err := a.handleGitCommits(ctx)
921 if err != nil {
922 // Just log the error, don't stop execution
923 slog.WarnContext(ctx, "Failed to check for new git commits", "error", err)
924 }
925 var autoqualityMessages []string
926 if len(newCommits) == 1 {
927 formatted := a.codereview.Autoformat(ctx)
928 if len(formatted) > 0 {
929 msg := fmt.Sprintf(`
930I ran autoformatters and they updated these files:
931
932%s
933
934Please amend your latest git commit with these changes and then continue with what you were doing.`,
935 strings.Join(formatted, "\n"),
936 )[1:]
937 a.pushToOutbox(ctx, AgentMessage{
938 Type: AutoMessageType,
939 Content: msg,
940 Timestamp: time.Now(),
941 })
942 autoqualityMessages = append(autoqualityMessages, msg)
943 }
944 }
945
946 if err := a.overBudget(ctx); err != nil {
947 return
948 }
949
950 // Include, along with the tool results (which must go first for whatever reason),
951 // any messages that the user has sent along while the tool_use was executing concurrently.
952 msgs, err = a.GatherMessages(ctx, false)
953 if err != nil {
954 return
955 }
956 // Inject any auto-generated messages from quality checks.
957 for _, msg := range autoqualityMessages {
958 msgs = append(msgs, ant.Content{Type: "text", Text: msg})
959 }
960 if cancelled {
961 msgs = append(msgs, ant.Content{Type: "text", Text: cancelToolUseMessage})
962 // EndOfTurn is false here so that the client of this agent keeps processing
963 // messages from WaitForMessage() and gets the response from the LLM (usually
964 // something like "okay, I'll wait further instructions", but the user should
965 // be made aware of it regardless).
966 a.pushToOutbox(ctx, AgentMessage{Type: ErrorMessageType, Content: userCancelMessage, EndOfTurn: false})
967 } else if err := a.convo.OverBudget(); err != nil {
968 budgetMsg := "We've exceeded our budget. Please ask the user to confirm before continuing by ending the turn."
969 msgs = append(msgs, ant.Content{Type: "text", Text: budgetMsg})
970 a.pushToOutbox(ctx, budgetMessage(fmt.Errorf("warning: %w (ask to keep trying, if you'd like)", err)))
971 }
972 results = append(results, msgs...)
973 resp, err = a.convo.SendMessage(ant.Message{
974 Role: "user",
975 Content: results,
976 })
977 if err != nil {
978 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("error: failed to continue conversation: %s", err.Error())))
979 break
980 }
981 if cancelled {
982 return
983 }
984 }
985}
986
987func (a *Agent) overBudget(ctx context.Context) error {
988 if err := a.convo.OverBudget(); err != nil {
989 m := budgetMessage(err)
990 m.Content = m.Content + "\n\nBudget reset."
991 a.pushToOutbox(ctx, budgetMessage(err))
992 a.convo.ResetBudget(a.originalBudget)
993 return err
994 }
995 return nil
996}
997
998func collectTextContent(msg *ant.MessageResponse) string {
999 // Collect all text content
1000 var allText strings.Builder
1001 for _, content := range msg.Content {
1002 if content.Type == "text" && content.Text != "" {
1003 if allText.Len() > 0 {
1004 allText.WriteString("\n\n")
1005 }
1006 allText.WriteString(content.Text)
1007 }
1008 }
1009 return allText.String()
1010}
1011
1012func (a *Agent) TotalUsage() ant.CumulativeUsage {
1013 a.mu.Lock()
1014 defer a.mu.Unlock()
1015 return a.convo.CumulativeUsage()
1016}
1017
1018// WaitForMessageCount returns when the agent has at more than clientMessageCount messages or the context is done.
1019func (a *Agent) WaitForMessageCount(ctx context.Context, greaterThan int) {
1020 for a.MessageCount() <= greaterThan {
1021 a.mu.Lock()
1022 ch := make(chan struct{})
1023 // Deletion happens when we notify.
1024 a.listeners = append(a.listeners, ch)
1025 a.mu.Unlock()
1026
1027 select {
1028 case <-ctx.Done():
1029 return
1030 case <-ch:
1031 continue
1032 }
1033 }
1034}
1035
1036// Diff returns a unified diff of changes made since the agent was instantiated.
1037func (a *Agent) Diff(commit *string) (string, error) {
1038 if a.initialCommit == "" {
1039 return "", fmt.Errorf("no initial commit reference available")
1040 }
1041
1042 // Find the repository root
1043 ctx := context.Background()
1044
1045 // If a specific commit hash is provided, show just that commit's changes
1046 if commit != nil && *commit != "" {
1047 // Validate that the commit looks like a valid git SHA
1048 if !isValidGitSHA(*commit) {
1049 return "", fmt.Errorf("invalid git commit SHA format: %s", *commit)
1050 }
1051
1052 // Get the diff for just this commit
1053 cmd := exec.CommandContext(ctx, "git", "show", "--unified=10", *commit)
1054 cmd.Dir = a.repoRoot
1055 output, err := cmd.CombinedOutput()
1056 if err != nil {
1057 return "", fmt.Errorf("failed to get diff for commit %s: %w - %s", *commit, err, string(output))
1058 }
1059 return string(output), nil
1060 }
1061
1062 // Otherwise, get the diff between the initial commit and the current state using exec.Command
1063 cmd := exec.CommandContext(ctx, "git", "diff", "--unified=10", a.initialCommit)
1064 cmd.Dir = a.repoRoot
1065 output, err := cmd.CombinedOutput()
1066 if err != nil {
1067 return "", fmt.Errorf("failed to get diff: %w - %s", err, string(output))
1068 }
1069
1070 return string(output), nil
1071}
1072
1073// InitialCommit returns the Git commit hash that was saved when the agent was instantiated.
1074func (a *Agent) InitialCommit() string {
1075 return a.initialCommit
1076}
1077
1078// handleGitCommits() highlights new commits to the user. When running
1079// under docker, new HEADs are pushed to a branch according to the title.
1080func (a *Agent) handleGitCommits(ctx context.Context) ([]*GitCommit, error) {
1081 if a.repoRoot == "" {
1082 return nil, nil
1083 }
1084
1085 head, err := resolveRef(ctx, a.repoRoot, "HEAD")
1086 if err != nil {
1087 return nil, err
1088 }
1089 if head == a.lastHEAD {
1090 return nil, nil // nothing to do
1091 }
1092 defer func() {
1093 a.lastHEAD = head
1094 }()
1095
1096 // Get new commits. Because it's possible that the agent does rebases, fixups, and
1097 // so forth, we use, as our fixed point, the "initialCommit", and we limit ourselves
1098 // to the last 100 commits.
1099 var commits []*GitCommit
1100
1101 // Get commits since the initial commit
1102 // Format: <hash>\0<subject>\0<body>\0
1103 // This uses NULL bytes as separators to avoid issues with newlines in commit messages
1104 // Limit to 100 commits to avoid overwhelming the user
1105 cmd := exec.CommandContext(ctx, "git", "log", "-n", "100", "--pretty=format:%H%x00%s%x00%b%x00", "^"+a.initialCommit, head)
1106 cmd.Dir = a.repoRoot
1107 output, err := cmd.Output()
1108 if err != nil {
1109 return nil, fmt.Errorf("failed to get git log: %w", err)
1110 }
1111
1112 // Parse git log output and filter out already seen commits
1113 parsedCommits := parseGitLog(string(output))
1114
1115 var headCommit *GitCommit
1116
1117 // Filter out commits we've already seen
1118 for _, commit := range parsedCommits {
1119 if commit.Hash == head {
1120 headCommit = &commit
1121 }
1122
1123 // Skip if we've seen this commit before. If our head has changed, always include that.
1124 if a.seenCommits[commit.Hash] && commit.Hash != head {
1125 continue
1126 }
1127
1128 // Mark this commit as seen
1129 a.seenCommits[commit.Hash] = true
1130
1131 // Add to our list of new commits
1132 commits = append(commits, &commit)
1133 }
1134
1135 if a.gitRemoteAddr != "" {
1136 if headCommit == nil {
1137 // I think this can only happen if we have a bug or if there's a race.
1138 headCommit = &GitCommit{}
1139 headCommit.Hash = head
1140 headCommit.Subject = "unknown"
1141 commits = append(commits, headCommit)
1142 }
1143
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001144 branch := cmp.Or(a.branchName, "sketch/"+a.config.SessionID)
Earl Lee2e463fb2025-04-17 11:22:22 -07001145
1146 // TODO: I don't love the force push here. We could see if the push is a fast-forward, and,
1147 // if it's not, we could make a backup with a unique name (perhaps append a timestamp) and
1148 // then use push with lease to replace.
1149 cmd = exec.Command("git", "push", "--force", a.gitRemoteAddr, "HEAD:refs/heads/"+branch)
1150 cmd.Dir = a.workingDir
1151 if out, err := cmd.CombinedOutput(); err != nil {
1152 a.pushToOutbox(ctx, errorMessage(fmt.Errorf("git push to host: %s: %v", out, err)))
1153 } else {
1154 headCommit.PushedBranch = branch
1155 }
1156 }
1157
1158 // If we found new commits, create a message
1159 if len(commits) > 0 {
1160 msg := AgentMessage{
1161 Type: CommitMessageType,
1162 Timestamp: time.Now(),
1163 Commits: commits,
1164 }
1165 a.pushToOutbox(ctx, msg)
1166 }
1167 return commits, nil
1168}
1169
Josh Bleecher Snydera9b38222025-04-29 18:05:06 -07001170func cleanBranchName(s string) string {
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001171 return strings.Map(func(r rune) rune {
1172 // lowercase
1173 if r >= 'A' && r <= 'Z' {
1174 return r + 'a' - 'A'
Earl Lee2e463fb2025-04-17 11:22:22 -07001175 }
Josh Bleecher Snyder1ae976b2025-04-30 00:06:43 +00001176 // replace spaces with dashes
1177 if r == ' ' {
1178 return '-'
1179 }
1180 // allow alphanumerics and dashes
1181 if (r >= 'a' && r <= 'z') || r == '-' || (r >= '0' && r <= '9') {
1182 return r
1183 }
1184 return -1
1185 }, s)
Earl Lee2e463fb2025-04-17 11:22:22 -07001186}
1187
1188// parseGitLog parses the output of git log with format '%H%x00%s%x00%b%x00'
1189// and returns an array of GitCommit structs.
1190func parseGitLog(output string) []GitCommit {
1191 var commits []GitCommit
1192
1193 // No output means no commits
1194 if len(output) == 0 {
1195 return commits
1196 }
1197
1198 // Split by NULL byte
1199 parts := strings.Split(output, "\x00")
1200
1201 // Process in triplets (hash, subject, body)
1202 for i := 0; i < len(parts); i++ {
1203 // Skip empty parts
1204 if parts[i] == "" {
1205 continue
1206 }
1207
1208 // This should be a hash
1209 hash := strings.TrimSpace(parts[i])
1210
1211 // Make sure we have at least a subject part available
1212 if i+1 >= len(parts) {
1213 break // No more parts available
1214 }
1215
1216 // Get the subject
1217 subject := strings.TrimSpace(parts[i+1])
1218
1219 // Get the body if available
1220 body := ""
1221 if i+2 < len(parts) {
1222 body = strings.TrimSpace(parts[i+2])
1223 }
1224
1225 // Skip to the next triplet
1226 i += 2
1227
1228 commits = append(commits, GitCommit{
1229 Hash: hash,
1230 Subject: subject,
1231 Body: body,
1232 })
1233 }
1234
1235 return commits
1236}
1237
1238func repoRoot(ctx context.Context, dir string) (string, error) {
1239 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
1240 stderr := new(strings.Builder)
1241 cmd.Stderr = stderr
1242 cmd.Dir = dir
1243 out, err := cmd.Output()
1244 if err != nil {
1245 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1246 }
1247 return strings.TrimSpace(string(out)), nil
1248}
1249
1250func resolveRef(ctx context.Context, dir, refName string) (string, error) {
1251 cmd := exec.CommandContext(ctx, "git", "rev-parse", refName)
1252 stderr := new(strings.Builder)
1253 cmd.Stderr = stderr
1254 cmd.Dir = dir
1255 out, err := cmd.Output()
1256 if err != nil {
1257 return "", fmt.Errorf("git rev-parse failed: %w\n%s", err, stderr)
1258 }
1259 // TODO: validate that out is valid hex
1260 return strings.TrimSpace(string(out)), nil
1261}
1262
1263// isValidGitSHA validates if a string looks like a valid git SHA hash.
1264// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1265func isValidGitSHA(sha string) bool {
1266 // Git SHA must be a hexadecimal string with at least 4 characters
1267 if len(sha) < 4 || len(sha) > 40 {
1268 return false
1269 }
1270
1271 // Check if the string only contains hexadecimal characters
1272 for _, char := range sha {
1273 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1274 return false
1275 }
1276 }
1277
1278 return true
1279}
Philip Zeyligerd1402952025-04-23 03:54:37 +00001280
1281// getGitOrigin returns the URL of the git remote 'origin' if it exists
1282func getGitOrigin(ctx context.Context, dir string) string {
1283 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1284 cmd.Dir = dir
1285 stderr := new(strings.Builder)
1286 cmd.Stderr = stderr
1287 out, err := cmd.Output()
1288 if err != nil {
1289 return ""
1290 }
1291 return strings.TrimSpace(string(out))
1292}