sourcegraph.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package tools
  2. import (
  3. "bytes"
  4. "context"
  5. _ "embed"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. type SourcegraphParams struct {
  14. Query string `json:"query"`
  15. Count int `json:"count,omitempty"`
  16. ContextWindow int `json:"context_window,omitempty"`
  17. Timeout int `json:"timeout,omitempty"`
  18. }
  19. type SourcegraphResponseMetadata struct {
  20. NumberOfMatches int `json:"number_of_matches"`
  21. Truncated bool `json:"truncated"`
  22. }
  23. type sourcegraphTool struct {
  24. client *http.Client
  25. }
  26. const SourcegraphToolName = "sourcegraph"
  27. //go:embed sourcegraph.md
  28. var sourcegraphDescription []byte
  29. func NewSourcegraphTool() BaseTool {
  30. return &sourcegraphTool{
  31. client: &http.Client{
  32. Timeout: 30 * time.Second,
  33. Transport: &http.Transport{
  34. MaxIdleConns: 100,
  35. MaxIdleConnsPerHost: 10,
  36. IdleConnTimeout: 90 * time.Second,
  37. },
  38. },
  39. }
  40. }
  41. func (t *sourcegraphTool) Name() string {
  42. return SourcegraphToolName
  43. }
  44. func (t *sourcegraphTool) Info() ToolInfo {
  45. return ToolInfo{
  46. Name: SourcegraphToolName,
  47. Description: string(sourcegraphDescription),
  48. Parameters: map[string]any{
  49. "query": map[string]any{
  50. "type": "string",
  51. "description": "The Sourcegraph search query",
  52. },
  53. "count": map[string]any{
  54. "type": "number",
  55. "description": "Optional number of results to return (default: 10, max: 20)",
  56. },
  57. "context_window": map[string]any{
  58. "type": "number",
  59. "description": "The context around the match to return (default: 10 lines)",
  60. },
  61. "timeout": map[string]any{
  62. "type": "number",
  63. "description": "Optional timeout in seconds (max 120)",
  64. },
  65. },
  66. Required: []string{"query"},
  67. }
  68. }
  69. func (t *sourcegraphTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  70. var params SourcegraphParams
  71. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  72. return NewTextErrorResponse("Failed to parse sourcegraph parameters: " + err.Error()), nil
  73. }
  74. if params.Query == "" {
  75. return NewTextErrorResponse("Query parameter is required"), nil
  76. }
  77. if params.Count <= 0 {
  78. params.Count = 10
  79. } else if params.Count > 20 {
  80. params.Count = 20 // Limit to 20 results
  81. }
  82. if params.ContextWindow <= 0 {
  83. params.ContextWindow = 10 // Default context window
  84. }
  85. // Handle timeout with context
  86. requestCtx := ctx
  87. if params.Timeout > 0 {
  88. maxTimeout := 120 // 2 minutes
  89. if params.Timeout > maxTimeout {
  90. params.Timeout = maxTimeout
  91. }
  92. var cancel context.CancelFunc
  93. requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
  94. defer cancel()
  95. }
  96. type graphqlRequest struct {
  97. Query string `json:"query"`
  98. Variables struct {
  99. Query string `json:"query"`
  100. } `json:"variables"`
  101. }
  102. request := graphqlRequest{
  103. Query: "query Search($query: String!) { search(query: $query, version: V2, patternType: keyword ) { results { matchCount, limitHit, resultCount, approximateResultCount, missing { name }, timedout { name }, indexUnavailable, results { __typename, ... on FileMatch { repository { name }, file { path, url, content }, lineMatches { preview, lineNumber, offsetAndLengths } } } } } }",
  104. }
  105. request.Variables.Query = params.Query
  106. graphqlQueryBytes, err := json.Marshal(request)
  107. if err != nil {
  108. return ToolResponse{}, fmt.Errorf("failed to marshal GraphQL request: %w", err)
  109. }
  110. graphqlQuery := string(graphqlQueryBytes)
  111. req, err := http.NewRequestWithContext(
  112. requestCtx,
  113. "POST",
  114. "https://sourcegraph.com/.api/graphql",
  115. bytes.NewBuffer([]byte(graphqlQuery)),
  116. )
  117. if err != nil {
  118. return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
  119. }
  120. req.Header.Set("Content-Type", "application/json")
  121. req.Header.Set("User-Agent", "crush/1.0")
  122. resp, err := t.client.Do(req)
  123. if err != nil {
  124. return ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
  125. }
  126. defer resp.Body.Close()
  127. if resp.StatusCode != http.StatusOK {
  128. body, _ := io.ReadAll(resp.Body)
  129. if len(body) > 0 {
  130. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
  131. }
  132. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
  133. }
  134. body, err := io.ReadAll(resp.Body)
  135. if err != nil {
  136. return ToolResponse{}, fmt.Errorf("failed to read response body: %w", err)
  137. }
  138. var result map[string]any
  139. if err = json.Unmarshal(body, &result); err != nil {
  140. return ToolResponse{}, fmt.Errorf("failed to unmarshal response: %w", err)
  141. }
  142. formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
  143. if err != nil {
  144. return NewTextErrorResponse("Failed to format results: " + err.Error()), nil
  145. }
  146. return NewTextResponse(formattedResults), nil
  147. }
  148. func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
  149. var buffer strings.Builder
  150. if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
  151. buffer.WriteString("## Sourcegraph API Error\n\n")
  152. for _, err := range errors {
  153. if errMap, ok := err.(map[string]any); ok {
  154. if message, ok := errMap["message"].(string); ok {
  155. buffer.WriteString(fmt.Sprintf("- %s\n", message))
  156. }
  157. }
  158. }
  159. return buffer.String(), nil
  160. }
  161. data, ok := result["data"].(map[string]any)
  162. if !ok {
  163. return "", fmt.Errorf("invalid response format: missing data field")
  164. }
  165. search, ok := data["search"].(map[string]any)
  166. if !ok {
  167. return "", fmt.Errorf("invalid response format: missing search field")
  168. }
  169. searchResults, ok := search["results"].(map[string]any)
  170. if !ok {
  171. return "", fmt.Errorf("invalid response format: missing results field")
  172. }
  173. matchCount, _ := searchResults["matchCount"].(float64)
  174. resultCount, _ := searchResults["resultCount"].(float64)
  175. limitHit, _ := searchResults["limitHit"].(bool)
  176. buffer.WriteString("# Sourcegraph Search Results\n\n")
  177. buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
  178. if limitHit {
  179. buffer.WriteString("(Result limit reached, try a more specific query)\n")
  180. }
  181. buffer.WriteString("\n")
  182. results, ok := searchResults["results"].([]any)
  183. if !ok || len(results) == 0 {
  184. buffer.WriteString("No results found. Try a different query.\n")
  185. return buffer.String(), nil
  186. }
  187. maxResults := 10
  188. if len(results) > maxResults {
  189. results = results[:maxResults]
  190. }
  191. for i, res := range results {
  192. fileMatch, ok := res.(map[string]any)
  193. if !ok {
  194. continue
  195. }
  196. typeName, _ := fileMatch["__typename"].(string)
  197. if typeName != "FileMatch" {
  198. continue
  199. }
  200. repo, _ := fileMatch["repository"].(map[string]any)
  201. file, _ := fileMatch["file"].(map[string]any)
  202. lineMatches, _ := fileMatch["lineMatches"].([]any)
  203. if repo == nil || file == nil {
  204. continue
  205. }
  206. repoName, _ := repo["name"].(string)
  207. filePath, _ := file["path"].(string)
  208. fileURL, _ := file["url"].(string)
  209. fileContent, _ := file["content"].(string)
  210. buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
  211. if fileURL != "" {
  212. buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
  213. }
  214. if len(lineMatches) > 0 {
  215. for _, lm := range lineMatches {
  216. lineMatch, ok := lm.(map[string]any)
  217. if !ok {
  218. continue
  219. }
  220. lineNumber, _ := lineMatch["lineNumber"].(float64)
  221. preview, _ := lineMatch["preview"].(string)
  222. if fileContent != "" {
  223. lines := strings.Split(fileContent, "\n")
  224. buffer.WriteString("```\n")
  225. startLine := max(1, int(lineNumber)-contextWindow)
  226. for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
  227. if j >= 0 {
  228. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  229. }
  230. }
  231. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  232. endLine := int(lineNumber) + contextWindow
  233. for j := int(lineNumber); j < endLine && j < len(lines); j++ {
  234. if j < len(lines) {
  235. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  236. }
  237. }
  238. buffer.WriteString("```\n\n")
  239. } else {
  240. buffer.WriteString("```\n")
  241. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  242. buffer.WriteString("```\n\n")
  243. }
  244. }
  245. }
  246. }
  247. return buffer.String(), nil
  248. }