sourcegraph.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package tools
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. type SourcegraphParams struct {
  13. Query string `json:"query"`
  14. Count int `json:"count,omitempty"`
  15. ContextWindow int `json:"context_window,omitempty"`
  16. Timeout int `json:"timeout,omitempty"`
  17. }
  18. type sourcegraphTool struct {
  19. client *http.Client
  20. }
  21. const (
  22. SourcegraphToolName = "sourcegraph"
  23. sourcegraphToolDescription = `Search code across public repositories using Sourcegraph's GraphQL API.
  24. WHEN TO USE THIS TOOL:
  25. - Use when you need to find code examples or implementations across public repositories
  26. - Helpful for researching how others have solved similar problems
  27. - Useful for discovering patterns and best practices in open source code
  28. HOW TO USE:
  29. - Provide a search query using Sourcegraph's query syntax
  30. - Optionally specify the number of results to return (default: 10)
  31. - Optionally set a timeout for the request
  32. QUERY SYNTAX:
  33. - Basic search: "fmt.Println" searches for exact matches
  34. - File filters: "file:.go fmt.Println" limits to Go files
  35. - Repository filters: "repo:^github\.com/golang/go$ fmt.Println" limits to specific repos
  36. - Language filters: "lang:go fmt.Println" limits to Go code
  37. - Boolean operators: "fmt.Println AND log.Fatal" for combined terms
  38. - Regular expressions: "fmt\.(Print|Printf|Println)" for pattern matching
  39. - Quoted strings: "\"exact phrase\"" for exact phrase matching
  40. - Exclude filters: "-file:test" or "-repo:forks" to exclude matches
  41. ADVANCED FILTERS:
  42. - Repository filters:
  43. * "repo:name" - Match repositories with name containing "name"
  44. * "repo:^github\.com/org/repo$" - Exact repository match
  45. * "repo:org/repo@branch" - Search specific branch
  46. * "repo:org/repo rev:branch" - Alternative branch syntax
  47. * "-repo:name" - Exclude repositories
  48. * "fork:yes" or "fork:only" - Include or only show forks
  49. * "archived:yes" or "archived:only" - Include or only show archived repos
  50. * "visibility:public" or "visibility:private" - Filter by visibility
  51. - File filters:
  52. * "file:\.js$" - Files with .js extension
  53. * "file:internal/" - Files in internal directory
  54. * "-file:test" - Exclude test files
  55. * "file:has.content(Copyright)" - Files containing "Copyright"
  56. * "file:has.contributor([email protected])" - Files with specific contributor
  57. - Content filters:
  58. * "content:\"exact string\"" - Search for exact string
  59. * "-content:\"unwanted\"" - Exclude files with unwanted content
  60. * "case:yes" - Case-sensitive search
  61. - Type filters:
  62. * "type:symbol" - Search for symbols (functions, classes, etc.)
  63. * "type:file" - Search file content only
  64. * "type:path" - Search filenames only
  65. * "type:diff" - Search code changes
  66. * "type:commit" - Search commit messages
  67. - Commit/diff search:
  68. * "after:\"1 month ago\"" - Commits after date
  69. * "before:\"2023-01-01\"" - Commits before date
  70. * "author:name" - Commits by author
  71. * "message:\"fix bug\"" - Commits with message
  72. - Result selection:
  73. * "select:repo" - Show only repository names
  74. * "select:file" - Show only file paths
  75. * "select:content" - Show only matching content
  76. * "select:symbol" - Show only matching symbols
  77. - Result control:
  78. * "count:100" - Return up to 100 results
  79. * "count:all" - Return all results
  80. * "timeout:30s" - Set search timeout
  81. EXAMPLES:
  82. - "file:.go context.WithTimeout" - Find Go code using context.WithTimeout
  83. - "lang:typescript useState type:symbol" - Find TypeScript React useState hooks
  84. - "repo:^github\.com/kubernetes/kubernetes$ pod list type:file" - Find Kubernetes files related to pod listing
  85. - "repo:sourcegraph/sourcegraph$ after:\"3 months ago\" type:diff database" - Recent changes to database code
  86. - "file:Dockerfile (alpine OR ubuntu) -content:alpine:latest" - Dockerfiles with specific base images
  87. - "repo:has.path(\.py) file:requirements.txt tensorflow" - Python projects using TensorFlow
  88. BOOLEAN OPERATORS:
  89. - "term1 AND term2" - Results containing both terms
  90. - "term1 OR term2" - Results containing either term
  91. - "term1 NOT term2" - Results with term1 but not term2
  92. - "term1 and (term2 or term3)" - Grouping with parentheses
  93. LIMITATIONS:
  94. - Only searches public repositories
  95. - Rate limits may apply
  96. - Complex queries may take longer to execute
  97. - Maximum of 20 results per query
  98. TIPS:
  99. - Use specific file extensions to narrow results
  100. - Add repo: filters for more targeted searches
  101. - Use type:symbol to find function/method definitions
  102. - Use type:file to find relevant files`
  103. )
  104. func NewSourcegraphTool() BaseTool {
  105. return &sourcegraphTool{
  106. client: &http.Client{
  107. Timeout: 30 * time.Second,
  108. },
  109. }
  110. }
  111. func (t *sourcegraphTool) Info() ToolInfo {
  112. return ToolInfo{
  113. Name: SourcegraphToolName,
  114. Description: sourcegraphToolDescription,
  115. Parameters: map[string]any{
  116. "query": map[string]any{
  117. "type": "string",
  118. "description": "The Sourcegraph search query",
  119. },
  120. "count": map[string]any{
  121. "type": "number",
  122. "description": "Optional number of results to return (default: 10, max: 20)",
  123. },
  124. "context_window": map[string]any{
  125. "type": "number",
  126. "description": "The context around the match to return (default: 10 lines)",
  127. },
  128. "timeout": map[string]any{
  129. "type": "number",
  130. "description": "Optional timeout in seconds (max 120)",
  131. },
  132. },
  133. Required: []string{"query"},
  134. }
  135. }
  136. func (t *sourcegraphTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  137. var params SourcegraphParams
  138. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  139. return NewTextErrorResponse("Failed to parse sourcegraph parameters: " + err.Error()), nil
  140. }
  141. if params.Query == "" {
  142. return NewTextErrorResponse("Query parameter is required"), nil
  143. }
  144. if params.Count <= 0 {
  145. params.Count = 10
  146. } else if params.Count > 20 {
  147. params.Count = 20 // Limit to 20 results
  148. }
  149. if params.ContextWindow <= 0 {
  150. params.ContextWindow = 10 // Default context window
  151. }
  152. client := t.client
  153. if params.Timeout > 0 {
  154. maxTimeout := 120 // 2 minutes
  155. if params.Timeout > maxTimeout {
  156. params.Timeout = maxTimeout
  157. }
  158. client = &http.Client{
  159. Timeout: time.Duration(params.Timeout) * time.Second,
  160. }
  161. }
  162. type graphqlRequest struct {
  163. Query string `json:"query"`
  164. Variables struct {
  165. Query string `json:"query"`
  166. } `json:"variables"`
  167. }
  168. request := graphqlRequest{
  169. 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 } } } } } }",
  170. }
  171. request.Variables.Query = params.Query
  172. graphqlQueryBytes, err := json.Marshal(request)
  173. if err != nil {
  174. return NewTextErrorResponse("Failed to create GraphQL request: " + err.Error()), nil
  175. }
  176. graphqlQuery := string(graphqlQueryBytes)
  177. req, err := http.NewRequestWithContext(
  178. ctx,
  179. "POST",
  180. "https://sourcegraph.com/.api/graphql",
  181. bytes.NewBuffer([]byte(graphqlQuery)),
  182. )
  183. if err != nil {
  184. return NewTextErrorResponse("Failed to create request: " + err.Error()), nil
  185. }
  186. req.Header.Set("Content-Type", "application/json")
  187. req.Header.Set("User-Agent", "termai/1.0")
  188. resp, err := client.Do(req)
  189. if err != nil {
  190. return NewTextErrorResponse("Failed to execute request: " + err.Error()), nil
  191. }
  192. defer resp.Body.Close()
  193. if resp.StatusCode != http.StatusOK {
  194. body, _ := io.ReadAll(resp.Body)
  195. if len(body) > 0 {
  196. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
  197. }
  198. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
  199. }
  200. body, err := io.ReadAll(resp.Body)
  201. if err != nil {
  202. return NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
  203. }
  204. var result map[string]any
  205. if err = json.Unmarshal(body, &result); err != nil {
  206. return NewTextErrorResponse("Failed to parse response: " + err.Error()), nil
  207. }
  208. formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
  209. if err != nil {
  210. return NewTextErrorResponse("Failed to format results: " + err.Error()), nil
  211. }
  212. return NewTextResponse(formattedResults), nil
  213. }
  214. func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
  215. var buffer strings.Builder
  216. if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
  217. buffer.WriteString("## Sourcegraph API Error\n\n")
  218. for _, err := range errors {
  219. if errMap, ok := err.(map[string]any); ok {
  220. if message, ok := errMap["message"].(string); ok {
  221. buffer.WriteString(fmt.Sprintf("- %s\n", message))
  222. }
  223. }
  224. }
  225. return buffer.String(), nil
  226. }
  227. data, ok := result["data"].(map[string]any)
  228. if !ok {
  229. return "", fmt.Errorf("invalid response format: missing data field")
  230. }
  231. search, ok := data["search"].(map[string]any)
  232. if !ok {
  233. return "", fmt.Errorf("invalid response format: missing search field")
  234. }
  235. searchResults, ok := search["results"].(map[string]any)
  236. if !ok {
  237. return "", fmt.Errorf("invalid response format: missing results field")
  238. }
  239. matchCount, _ := searchResults["matchCount"].(float64)
  240. resultCount, _ := searchResults["resultCount"].(float64)
  241. limitHit, _ := searchResults["limitHit"].(bool)
  242. buffer.WriteString("# Sourcegraph Search Results\n\n")
  243. buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
  244. if limitHit {
  245. buffer.WriteString("(Result limit reached, try a more specific query)\n")
  246. }
  247. buffer.WriteString("\n")
  248. results, ok := searchResults["results"].([]any)
  249. if !ok || len(results) == 0 {
  250. buffer.WriteString("No results found. Try a different query.\n")
  251. return buffer.String(), nil
  252. }
  253. maxResults := 10
  254. if len(results) > maxResults {
  255. results = results[:maxResults]
  256. }
  257. for i, res := range results {
  258. fileMatch, ok := res.(map[string]any)
  259. if !ok {
  260. continue
  261. }
  262. typeName, _ := fileMatch["__typename"].(string)
  263. if typeName != "FileMatch" {
  264. continue
  265. }
  266. repo, _ := fileMatch["repository"].(map[string]any)
  267. file, _ := fileMatch["file"].(map[string]any)
  268. lineMatches, _ := fileMatch["lineMatches"].([]any)
  269. if repo == nil || file == nil {
  270. continue
  271. }
  272. repoName, _ := repo["name"].(string)
  273. filePath, _ := file["path"].(string)
  274. fileURL, _ := file["url"].(string)
  275. fileContent, _ := file["content"].(string)
  276. buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
  277. if fileURL != "" {
  278. buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
  279. }
  280. if len(lineMatches) > 0 {
  281. for _, lm := range lineMatches {
  282. lineMatch, ok := lm.(map[string]any)
  283. if !ok {
  284. continue
  285. }
  286. lineNumber, _ := lineMatch["lineNumber"].(float64)
  287. preview, _ := lineMatch["preview"].(string)
  288. if fileContent != "" {
  289. lines := strings.Split(fileContent, "\n")
  290. buffer.WriteString("```\n")
  291. startLine := max(1, int(lineNumber)-contextWindow)
  292. for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
  293. if j >= 0 {
  294. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  295. }
  296. }
  297. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  298. endLine := int(lineNumber) + contextWindow
  299. for j := int(lineNumber); j < endLine && j < len(lines); j++ {
  300. if j < len(lines) {
  301. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  302. }
  303. }
  304. buffer.WriteString("```\n\n")
  305. } else {
  306. buffer.WriteString("```\n")
  307. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  308. buffer.WriteString("```\n\n")
  309. }
  310. }
  311. }
  312. }
  313. return buffer.String(), nil
  314. }