1package tools
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "sync"
8 "time"
9)
10
11type (
12 sessionIDContextKey string
13 messageIDContextKey string
14)
15
16const (
17 MaxOutputLength = 30000
18 MaxReadSize = 250 * 1024
19 DefaultReadLimit = 2000
20 MaxLineLength = 2000
21
22 SessionIDContextKey sessionIDContextKey = "session_id"
23 MessageIDContextKey messageIDContextKey = "message_id"
24)
25
26func truncateOutput(content string) string {
27 if len(content) <= MaxOutputLength {
28 return content
29 }
30
31 halfLength := MaxOutputLength / 2
32 start := content[:halfLength]
33 end := content[len(content)-halfLength:]
34
35 truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
36 return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
37}
38
39func countLines(s string) int {
40 if s == "" {
41 return 0
42 }
43 return len(strings.Split(s, "\n"))
44}
45
46func GetContextValues(ctx context.Context) (string, string) {
47 sessionID := ctx.Value(SessionIDContextKey)
48 messageID := ctx.Value(MessageIDContextKey)
49 if sessionID == nil {
50 return "", ""
51 }
52 if messageID == nil {
53 return sessionID.(string), ""
54 }
55 return sessionID.(string), messageID.(string)
56}
57
58// File record to track when files were read/written
59type fileRecord struct {
60 path string
61 readTime time.Time
62 writeTime time.Time
63}
64
65var (
66 fileRecords = make(map[string]fileRecord)
67 fileRecordMutex sync.RWMutex
68)
69
70func recordFileRead(path string) {
71 fileRecordMutex.Lock()
72 defer fileRecordMutex.Unlock()
73
74 record, exists := fileRecords[path]
75 if !exists {
76 record = fileRecord{path: path}
77 }
78 record.readTime = time.Now()
79 fileRecords[path] = record
80}
81
82func getLastReadTime(path string) time.Time {
83 fileRecordMutex.RLock()
84 defer fileRecordMutex.RUnlock()
85
86 record, exists := fileRecords[path]
87 if !exists {
88 return time.Time{}
89 }
90 return record.readTime
91}
92
93func recordFileWrite(path string) {
94 fileRecordMutex.Lock()
95 defer fileRecordMutex.Unlock()
96
97 record, exists := fileRecords[path]
98 if !exists {
99 record = fileRecord{path: path}
100 }
101 record.writeTime = time.Now()
102 fileRecords[path] = record
103}