-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.go
More file actions
501 lines (428 loc) · 13 KB
/
utils.go
File metadata and controls
501 lines (428 loc) · 13 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"golang.org/x/term"
)
// expandHomePath expands the ~ character in a path to the user's home directory
func expandHomePath(path string) string {
if strings.HasPrefix(path, "~") {
homeDir, err := os.UserHomeDir()
if err != nil {
return path // Return original path if we can't get home dir
}
return filepath.Join(homeDir, path[1:])
}
return path
}
// CacheError represents errors related to cache directory operations
type CacheError struct {
Operation string
Path string
Err error
}
func (e *CacheError) Error() string {
return fmt.Sprintf("cache %s failed for path '%s': %v", e.Operation, e.Path, e.Err)
}
// FileError represents errors related to file operations
type FileError struct {
Operation string
Path string
Err error
}
func (e *FileError) Error() string {
return fmt.Sprintf("file %s failed for path '%s': %v", e.Operation, e.Path, e.Err)
}
// wrapCacheError wraps an error with cache context
func wrapCacheError(operation, path string, err error) error {
if err == nil {
return nil
}
return &CacheError{Operation: operation, Path: path, Err: err}
}
// wrapFileError wraps an error with file context
func wrapFileError(operation, path string, err error) error {
if err == nil {
return nil
}
return &FileError{Operation: operation, Path: path, Err: err}
}
// confirmResponse represents the response type from a confirmation prompt
type confirmResponse struct {
approved bool
message string
}
// openTTY opens /dev/tty for interactive prompts, bypassing piped stdin
func openTTY() (*os.File, error) {
return os.OpenFile("/dev/tty", os.O_RDWR, 0)
}
// confirm prompts the user for confirmation with yes/no/message options
func confirm(prompt string) confirmResponse {
cyan := color.New(color.FgCyan).SprintFunc()
fmt.Fprintf(os.Stderr, "%s %s (m/y/N): ", cyan("[?]"), prompt)
// Open /dev/tty for interactive input to bypass piped stdin
tty, err := openTTY()
if err != nil {
// Fallback to os.Stdin if /dev/tty is not available
tty = os.Stdin
} else {
defer tty.Close()
}
oldState, _ := term.MakeRaw(int(tty.Fd()))
reader := bufio.NewReader(tty)
char, err := reader.ReadByte()
if err != nil {
return confirmResponse{approved: false, message: ""}
}
response := strings.ToLower(string(char))
fmt.Fprintf(os.Stderr, "%s\n\r", response)
term.Restore(int(tty.Fd()), oldState)
if response == "m" {
fmt.Fprintf(os.Stderr, "%s Enter message: ", cyan("[?]"))
reader := bufio.NewReader(tty)
message, _ := reader.ReadString('\n')
message = strings.TrimSuffix(message, "\n")
return confirmResponse{approved: false, message: message}
}
return confirmResponse{approved: response == "y", message: ""}
}
// setupCacheDir ensures the cache directory exists and returns its path.
func setupCacheDir() (string, error) {
cacheDir, err := os.UserCacheDir()
if err != nil {
return "", wrapCacheError("get user cache directory", "", err)
}
esaDir := filepath.Join(cacheDir, "esa")
if err := os.MkdirAll(esaDir, 0755); err != nil {
return "", wrapCacheError("create directory", esaDir, err)
}
return esaDir, nil
}
// setupCacheDirWithFallback ensures the cache directory exists and handles errors gracefully
func setupCacheDirWithFallback() string {
cacheDir, err := setupCacheDir()
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not setup cache directory: %v\n", err)
// Fallback to temp directory
return filepath.Join(os.TempDir(), "esa")
}
return cacheDir
}
func createNewHistoryFile(cacheDir string, agentName string, conversation string) string {
if agentName == "" {
agentName = "default"
}
timestamp := time.Now().Format(historyTimeFormat)
if _, ok := getConversationIndex(conversation); ok {
return filepath.Join(cacheDir, fmt.Sprintf("---%s-%s.json", agentName, timestamp))
}
return filepath.Join(cacheDir, fmt.Sprintf("%s---%s-%s.json", conversation, agentName, timestamp))
}
func getConversationIndex(conversation string) (int, bool) {
val, err := strconv.Atoi(conversation)
if err != nil || val < 0 {
return 0, false
}
return val - 1, true
}
func findHistoryFile(cacheDir string, conversation string) (string, error) {
entries, err := os.ReadDir(cacheDir)
if err != nil {
return "", err
}
type fileEntry struct {
name string
modTime time.Time
}
index, isIndex := getConversationIndex(conversation)
var files []fileEntry
for _, entry := range entries {
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
info, err := entry.Info()
if err != nil {
continue
}
files = append(files, fileEntry{
name: entry.Name(),
modTime: info.ModTime(),
})
}
}
if len(files) == 0 {
return "", fmt.Errorf("no history files found")
}
if isIndex {
sort.Slice(files, func(i, j int) bool {
return files[i].modTime.After(files[j].modTime)
})
if index < 0 || index >= len(files) {
return "", fmt.Errorf("history file index %d out of range (0-%d)", index, len(files)-1)
}
return filepath.Join(cacheDir, files[index].name), nil
} else {
// Read the conversation ID from the json file and return file with that id
for _, file := range files {
if strings.HasPrefix(file.name, conversation+"---") {
return filepath.Join(cacheDir, file.name), nil
}
}
return "", fmt.Errorf("no history file found for conversation %s", conversation)
}
}
func getHistoryFilePath(cacheDir string, opts *CLIOptions) (string, bool) {
if !opts.ContinueChat && !opts.RetryChat {
cacheDir = setupCacheDirWithFallback()
return createNewHistoryFile(cacheDir, opts.AgentName, opts.Conversation), false
}
if filePath, err := findHistoryFile(cacheDir, opts.Conversation); err == nil {
return filePath, true
}
cacheDir = setupCacheDirWithFallback()
return createNewHistoryFile(cacheDir, opts.AgentName, opts.Conversation), false
}
// Read stdin if exists. Used to detect if input is piped and read it if so
func readStdin() string {
var input bytes.Buffer
stat, err := os.Stdin.Stat()
if err == nil && (stat.Mode()&os.ModeCharDevice) == 0 {
if _, err := io.Copy(&input, os.Stdin); err != nil {
return ""
}
}
return input.String()
}
func readUserInput(prompt string, multiline bool) (string, error) {
// Open /dev/tty for interactive input to bypass piped stdin
tty, err := openTTY()
var reader *bufio.Reader
if err != nil {
// Fallback to os.Stdin if /dev/tty is not available
reader = bufio.NewReader(os.Stdin)
} else {
defer tty.Close()
reader = bufio.NewReader(tty)
}
if prompt != "" {
color.New(color.FgBlue).Fprint(os.Stderr, prompt)
color.New(color.FgHiWhite, color.Italic).Fprint(os.Stderr, " (ctrl+d on empty line to complete)\n")
}
var result strings.Builder
for {
line, err := reader.ReadString('\n')
if err != nil {
if err.Error() == "EOF" {
// Ctrl+D pressed
break
}
return "", err
}
// Return if we just want a single line
if !multiline {
return line, nil
}
// Remove the trailing newline and add to result
line = strings.TrimSuffix(line, "\n")
if result.Len() > 0 {
result.WriteByte('\n')
}
result.WriteString(line)
// Check if line is empty and we got EOF (Ctrl+D)
if line == "" {
nextByte, err := reader.ReadByte()
if err != nil && err.Error() == "EOF" {
break
}
if err == nil {
// Put the byte back by creating a new reader with it
result.WriteByte('\n')
remaining, _ := reader.ReadString('\n')
result.WriteString(string(nextByte) + remaining)
}
}
}
return result.String(), nil
}
// parseHistoryFilename extracts conversation ID, agent name, and timestamp
// from a history filename. Filenames follow the format:
//
// {conversation}---{agent}-{YYYYMMDD}-{HHMMSS}.json
// ---{agent}-{YYYYMMDD}-{HHMMSS}.json (no conversation ID)
func parseHistoryFilename(fileName string) (conversation, agentName, timestampStr string) {
base := strings.TrimSuffix(fileName, ".json")
// Split on "---" to separate conversation from the rest
parts := strings.SplitN(base, "---", 2)
if len(parts) != 2 {
return "", "unknown", "unknown"
}
conversation = parts[0]
rest := parts[1] // e.g. "agent-20060102-150405"
// The rest is "{agent}-{YYYYMMDD}-{HHMMSS}"
// Split from the right: find last two dash-separated segments for the timestamp
segments := strings.Split(rest, "-")
if len(segments) >= 3 {
// Last two segments are date and time
timestampStr = segments[len(segments)-2] + "-" + segments[len(segments)-1]
agentName = strings.Join(segments[:len(segments)-2], "-")
} else {
agentName = rest
timestampStr = "unknown"
}
if agentName == "" {
agentName = "unknown"
}
return conversation, agentName, timestampStr
}
// getSortedHistoryFiles retrieves and sorts history files by modification time.
func getSortedHistoryFiles() ([]string, map[string]os.FileInfo, error) {
cacheDir, err := setupCacheDir()
if err != nil {
return nil, nil, err
}
// Check if the directory exists
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
return nil, nil, wrapCacheError("access", cacheDir, fmt.Errorf("directory does not exist"))
}
// Read all .json files in the directory
files, err := os.ReadDir(cacheDir)
if err != nil {
return nil, nil, wrapCacheError("read", cacheDir, err)
}
historyItems := make(map[string]os.FileInfo) // Store file info to sort by mod time later
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") {
info, err := file.Info()
if err != nil {
continue // Skip files we can't get info for
}
historyItems[file.Name()] = info
}
}
if len(historyItems) == 0 {
return nil, nil, wrapCacheError("find history files", cacheDir, fmt.Errorf("no history files found"))
}
// Sort files by modification time (most recent first)
sortedFiles := make([]string, 0, len(historyItems))
for name := range historyItems {
sortedFiles = append(sortedFiles, name)
}
// Custom sort function
sort.Slice(sortedFiles, func(i, j int) bool {
return historyItems[sortedFiles[i]].ModTime().After(historyItems[sortedFiles[j]].ModTime())
})
return sortedFiles, historyItems, nil
}
// defaultProviders maps provider names to their default configurations.
var defaultProviders = map[string]providerInfo{
"openai": {
baseURL: "https://api.openai.com/v1",
apiKeyEnvar: "OPENAI_API_KEY",
},
"openrouter": {
baseURL: "https://openrouter.ai/api/v1",
apiKeyEnvar: "OPENROUTER_API_KEY",
},
"groq": {
baseURL: "https://api.groq.com/openai/v1",
apiKeyEnvar: "GROQ_API_KEY",
},
"github": {
baseURL: "https://models.inference.ai.azure.com",
apiKeyEnvar: "GITHUB_MODELS_API_KEY",
},
"copilot": {
baseURL: "https://api.githubcopilot.com",
apiKeyEnvar: "COPILOT_API_KEY",
additionalHeaders: map[string]string{
"Content-Type": "application/json",
"Copilot-Integration-Id": "vscode-chat",
},
},
"anthropic": {
baseURL: "https://api.anthropic.com",
apiKeyEnvar: "ANTHROPIC_API_KEY",
},
}
// resolveOllamaHost returns the Ollama providerInfo with proper host URL normalization.
func resolveOllamaHost() providerInfo {
host := os.Getenv("OLLAMA_HOST")
if host == "" {
host = "http://localhost:11434"
}
if !strings.HasPrefix(host, "http://") && !strings.HasPrefix(host, "https://") {
host = "http://" + host
}
if !strings.HasSuffix(host, "/v1") {
host = strings.TrimSuffix(host, "/") + "/v1"
}
return providerInfo{
baseURL: host,
apiKeyEnvar: "OLLAMA_API_KEY",
apiKeyCanBeEmpty: true,
}
}
// applyConfigOverrides applies provider config overrides from the global config.
func (info *providerInfo) applyConfigOverrides(config *Config, provider string) {
if config == nil {
return
}
providerCfg, ok := config.Providers[provider]
if !ok {
return
}
if providerCfg.BaseURL != "" {
info.baseURL = providerCfg.BaseURL
}
if providerCfg.APIKeyEnvar != "" {
info.apiKeyEnvar = providerCfg.APIKeyEnvar
}
if len(providerCfg.AdditionalHeaders) > 0 {
if info.additionalHeaders == nil {
info.additionalHeaders = make(map[string]string)
}
for key, value := range providerCfg.AdditionalHeaders {
info.additionalHeaders[key] = value
}
}
}
func parseModel(modelStr string, agent Agent, config *Config) (provider string, model string, info providerInfo) {
if modelStr == "" {
if agent.DefaultModel != "" {
modelStr = agent.DefaultModel
} else if config.Settings.DefaultModel != "" {
modelStr = config.Settings.DefaultModel
} else {
modelStr = defaultModel
}
}
// Check if the model string is an alias
if config != nil {
if aliasedModel, ok := config.ModelAliases[modelStr]; ok {
modelStr = aliasedModel
}
}
parts := strings.SplitN(modelStr, "/", 2)
if len(parts) != 2 {
log.Fatalf("invalid model format %q - must be provider/model", modelStr)
}
provider = parts[0]
model = parts[1]
// Look up default provider info
if provider == "ollama" {
info = resolveOllamaHost()
} else if defaults, ok := defaultProviders[provider]; ok {
info = defaults
}
// Apply config overrides
info.applyConfigOverrides(config, provider)
return provider, model, info
}