sourcegraph.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. - For more details on query syntax, visit: https://docs.sourcegraph.com/code_search/queries`
  104. )
  105. func NewSourcegraphTool() BaseTool {
  106. return &sourcegraphTool{
  107. client: &http.Client{
  108. Timeout: 30 * time.Second,
  109. },
  110. }
  111. }
  112. func (t *sourcegraphTool) Info() ToolInfo {
  113. return ToolInfo{
  114. Name: SourcegraphToolName,
  115. Description: sourcegraphToolDescription,
  116. Parameters: map[string]any{
  117. "query": map[string]any{
  118. "type": "string",
  119. "description": "The Sourcegraph search query",
  120. },
  121. "count": map[string]any{
  122. "type": "number",
  123. "description": "Optional number of results to return (default: 10, max: 20)",
  124. },
  125. "context_window": map[string]any{
  126. "type": "number",
  127. "description": "The context around the match to return (default: 10 lines)",
  128. },
  129. "timeout": map[string]any{
  130. "type": "number",
  131. "description": "Optional timeout in seconds (max 120)",
  132. },
  133. },
  134. Required: []string{"query"},
  135. }
  136. }
  137. func (t *sourcegraphTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  138. var params SourcegraphParams
  139. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  140. return NewTextErrorResponse("Failed to parse sourcegraph parameters: " + err.Error()), nil
  141. }
  142. if params.Query == "" {
  143. return NewTextErrorResponse("Query parameter is required"), nil
  144. }
  145. if params.Count <= 0 {
  146. params.Count = 10
  147. } else if params.Count > 20 {
  148. params.Count = 20 // Limit to 20 results
  149. }
  150. if params.ContextWindow <= 0 {
  151. params.ContextWindow = 10 // Default context window
  152. }
  153. client := t.client
  154. if params.Timeout > 0 {
  155. maxTimeout := 120 // 2 minutes
  156. if params.Timeout > maxTimeout {
  157. params.Timeout = maxTimeout
  158. }
  159. client = &http.Client{
  160. Timeout: time.Duration(params.Timeout) * time.Second,
  161. }
  162. }
  163. type graphqlRequest struct {
  164. Query string `json:"query"`
  165. Variables struct {
  166. Query string `json:"query"`
  167. } `json:"variables"`
  168. }
  169. request := graphqlRequest{
  170. 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 } } } } } }",
  171. }
  172. request.Variables.Query = params.Query
  173. graphqlQueryBytes, err := json.Marshal(request)
  174. if err != nil {
  175. return NewTextErrorResponse("Failed to create GraphQL request: " + err.Error()), nil
  176. }
  177. graphqlQuery := string(graphqlQueryBytes)
  178. req, err := http.NewRequestWithContext(
  179. ctx,
  180. "POST",
  181. "https://sourcegraph.com/.api/graphql",
  182. bytes.NewBuffer([]byte(graphqlQuery)),
  183. )
  184. if err != nil {
  185. return NewTextErrorResponse("Failed to create request: " + err.Error()), nil
  186. }
  187. req.Header.Set("Content-Type", "application/json")
  188. req.Header.Set("User-Agent", "termai/1.0")
  189. resp, err := client.Do(req)
  190. if err != nil {
  191. return NewTextErrorResponse("Failed to execute request: " + err.Error()), nil
  192. }
  193. defer resp.Body.Close()
  194. if resp.StatusCode != http.StatusOK {
  195. body, _ := io.ReadAll(resp.Body)
  196. if len(body) > 0 {
  197. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
  198. }
  199. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
  200. }
  201. body, err := io.ReadAll(resp.Body)
  202. if err != nil {
  203. return NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
  204. }
  205. var result map[string]any
  206. if err = json.Unmarshal(body, &result); err != nil {
  207. return NewTextErrorResponse("Failed to parse response: " + err.Error()), nil
  208. }
  209. formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
  210. if err != nil {
  211. return NewTextErrorResponse("Failed to format results: " + err.Error()), nil
  212. }
  213. return NewTextResponse(formattedResults), nil
  214. }
  215. func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
  216. var buffer strings.Builder
  217. if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
  218. buffer.WriteString("## Sourcegraph API Error\n\n")
  219. for _, err := range errors {
  220. if errMap, ok := err.(map[string]any); ok {
  221. if message, ok := errMap["message"].(string); ok {
  222. buffer.WriteString(fmt.Sprintf("- %s\n", message))
  223. }
  224. }
  225. }
  226. return buffer.String(), nil
  227. }
  228. data, ok := result["data"].(map[string]any)
  229. if !ok {
  230. return "", fmt.Errorf("invalid response format: missing data field")
  231. }
  232. search, ok := data["search"].(map[string]any)
  233. if !ok {
  234. return "", fmt.Errorf("invalid response format: missing search field")
  235. }
  236. searchResults, ok := search["results"].(map[string]any)
  237. if !ok {
  238. return "", fmt.Errorf("invalid response format: missing results field")
  239. }
  240. matchCount, _ := searchResults["matchCount"].(float64)
  241. resultCount, _ := searchResults["resultCount"].(float64)
  242. limitHit, _ := searchResults["limitHit"].(bool)
  243. buffer.WriteString("# Sourcegraph Search Results\n\n")
  244. buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
  245. if limitHit {
  246. buffer.WriteString("(Result limit reached, try a more specific query)\n")
  247. }
  248. buffer.WriteString("\n")
  249. results, ok := searchResults["results"].([]any)
  250. if !ok || len(results) == 0 {
  251. buffer.WriteString("No results found. Try a different query.\n")
  252. return buffer.String(), nil
  253. }
  254. maxResults := 10
  255. if len(results) > maxResults {
  256. results = results[:maxResults]
  257. }
  258. for i, res := range results {
  259. fileMatch, ok := res.(map[string]any)
  260. if !ok {
  261. continue
  262. }
  263. typeName, _ := fileMatch["__typename"].(string)
  264. if typeName != "FileMatch" {
  265. continue
  266. }
  267. repo, _ := fileMatch["repository"].(map[string]any)
  268. file, _ := fileMatch["file"].(map[string]any)
  269. lineMatches, _ := fileMatch["lineMatches"].([]any)
  270. if repo == nil || file == nil {
  271. continue
  272. }
  273. repoName, _ := repo["name"].(string)
  274. filePath, _ := file["path"].(string)
  275. fileURL, _ := file["url"].(string)
  276. fileContent, _ := file["content"].(string)
  277. buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
  278. if fileURL != "" {
  279. buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
  280. }
  281. if len(lineMatches) > 0 {
  282. for _, lm := range lineMatches {
  283. lineMatch, ok := lm.(map[string]any)
  284. if !ok {
  285. continue
  286. }
  287. lineNumber, _ := lineMatch["lineNumber"].(float64)
  288. preview, _ := lineMatch["preview"].(string)
  289. if fileContent != "" {
  290. lines := strings.Split(fileContent, "\n")
  291. buffer.WriteString("```\n")
  292. startLine := max(1, int(lineNumber)-contextWindow)
  293. for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
  294. if j >= 0 {
  295. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  296. }
  297. }
  298. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  299. endLine := int(lineNumber) + contextWindow
  300. for j := int(lineNumber); j < endLine && j < len(lines); j++ {
  301. if j < len(lines) {
  302. buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
  303. }
  304. }
  305. buffer.WriteString("```\n\n")
  306. } else {
  307. buffer.WriteString("```\n")
  308. buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
  309. buffer.WriteString("```\n\n")
  310. }
  311. }
  312. }
  313. }
  314. return buffer.String(), nil
  315. }