summaryrefslogtreecommitdiff
path: root/internal/executor/gemini.go
blob: 2db32182081a7a5959d60da48cfa4bd7805c9456 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package executor

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"syscall"

	"github.com/thepeterstone/claudomator/internal/storage"
	"github.com/thepeterstone/claudomator/internal/task"
)

// GeminiRunner spawns the `gemini` CLI in non-interactive mode.
type GeminiRunner struct {
	BinaryPath string // defaults to "gemini"
	Logger     *slog.Logger
	LogDir     string // base directory for execution logs
	APIURL     string // base URL of the Claudomator API, passed to subprocesses
}

// ExecLogDir returns the log directory for the given execution ID.
func (r *GeminiRunner) ExecLogDir(execID string) string {
	if r.LogDir == "" {
		return ""
	}
	return filepath.Join(r.LogDir, execID)
}

func (r *GeminiRunner) binaryPath() string {
	if r.BinaryPath != "" {
		return r.BinaryPath
	}
	return "gemini"
}

// Run executes a gemini <instructions> invocation, streaming output to log files.
func (r *GeminiRunner) Run(ctx context.Context, t *task.Task, e *storage.Execution) error {
	if t.Agent.ProjectDir != "" {
		if _, err := os.Stat(t.Agent.ProjectDir); err != nil {
			return fmt.Errorf("project_dir %q: %w", t.Agent.ProjectDir, err)
		}
	}

	logDir := r.ExecLogDir(e.ID)
	if logDir == "" {
		logDir = e.ID
	}
	if err := os.MkdirAll(logDir, 0700); err != nil {
		return fmt.Errorf("creating log dir: %w", err)
	}
	if e.StdoutPath == "" {
		e.StdoutPath = filepath.Join(logDir, "stdout.log")
		e.StderrPath = filepath.Join(logDir, "stderr.log")
		e.ArtifactDir = logDir
	}

	if e.SessionID == "" {
		e.SessionID = e.ID
	}

	questionFile := filepath.Join(logDir, "question.json")
	args := r.buildArgs(t, e, questionFile)

	// Gemini CLI doesn't necessarily have the same rate limiting behavior as Claude,
	// but we'll use a similar execution pattern.
	err := r.execOnce(ctx, args, t.Agent.ProjectDir, e)
	if err != nil {
		return err
	}

	// Check whether the agent left a question before exiting.
	data, readErr := os.ReadFile(questionFile)
	if readErr == nil {
		os.Remove(questionFile) // consumed
		return &BlockedError{QuestionJSON: strings.TrimSpace(string(data)), SessionID: e.SessionID}
	}
	return nil
}

func (r *GeminiRunner) execOnce(ctx context.Context, args []string, workingDir string, e *storage.Execution) error {
	cmd := exec.CommandContext(ctx, r.binaryPath(), args...)
	cmd.Env = append(os.Environ(),
		"CLAUDOMATOR_API_URL="+r.APIURL,
		"CLAUDOMATOR_TASK_ID="+e.TaskID,
		"CLAUDOMATOR_QUESTION_FILE="+filepath.Join(e.ArtifactDir, "question.json"),
	)
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	if workingDir != "" {
		cmd.Dir = workingDir
	}

	stdoutFile, err := os.Create(e.StdoutPath)
	if err != nil {
		return fmt.Errorf("creating stdout log: %w", err)
	}
	defer stdoutFile.Close()

	stderrFile, err := os.Create(e.StderrPath)
	if err != nil {
		return fmt.Errorf("creating stderr log: %w", err)
	}
	defer stderrFile.Close()

	stdoutR, stdoutW, err := os.Pipe()
	if err != nil {
		return fmt.Errorf("creating stdout pipe: %w", err)
	}
	cmd.Stdout = stdoutW
	cmd.Stderr = stderrFile

	if err := cmd.Start(); err != nil {
		stdoutW.Close()
		stdoutR.Close()
		return fmt.Errorf("starting gemini: %w", err)
	}
	stdoutW.Close()

	killDone := make(chan struct{})
	go func() {
		select {
		case <-ctx.Done():
			syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
		case <-killDone:
		}
	}()

	var costUSD float64
	var streamErr error
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		// Reusing parseStream as the JSONL format should be compatible
		costUSD, streamErr = parseStream(stdoutR, stdoutFile, r.Logger)
		stdoutR.Close()
	}()

	waitErr := cmd.Wait()
	close(killDone)
	wg.Wait()

	e.CostUSD = costUSD

	if waitErr != nil {
		if exitErr, ok := waitErr.(*exec.ExitError); ok {
			e.ExitCode = exitErr.ExitCode()
		}
		if tail := tailFile(e.StderrPath, 20); tail != "" {
			return fmt.Errorf("gemini exited with error: %w\nstderr:\n%s", waitErr, tail)
		}
		return fmt.Errorf("gemini exited with error: %w", waitErr)
	}

	e.ExitCode = 0
	if streamErr != nil {
		return streamErr
	}
	return nil
}

func (r *GeminiRunner) buildArgs(t *task.Task, e *storage.Execution, questionFile string) []string {
	// Gemini CLI uses a different command structure: gemini "instructions" [flags]
	
	instructions := t.Agent.Instructions
	if !t.Agent.SkipPlanning {
		instructions = withPlanningPreamble(instructions)
	}

	args := []string{
		"-p", instructions,
		"--output-format", "stream-json",
		"--yolo", // auto-approve all tools (equivalent to Claude's bypassPermissions)
	}

	// Note: Gemini CLI flags might differ from Claude CLI.
	// Assuming common flags for now, but these may need adjustment.
	if t.Agent.Model != "" {
		args = append(args, "--model", t.Agent.Model)
	}
	
	// Gemini CLI doesn't use --session-id for the first run in the same way,
	// or it might use it differently. For now we assume compatibility.
	if e.SessionID != "" {
		// If it's a resume, it might use different flags.
		if e.ResumeSessionID != "" {
			// This is a placeholder for Gemini's resume logic
		}
	}

	return args
}