17type SourcegraphParams struct {
18 Query string `json:"query" description:"The Sourcegraph search query"`
19 Count int `json:"count,omitempty" description:"Optional number of results to return (default: 10, max: 20)"`
20 ContextWindow int `json:"context_window,omitempty" description:"The context around the match to return (default: 10 lines)"`
21 Timeout int `json:"timeout,omitempty" description:"Optional timeout in seconds (max 120)"`
24type SourcegraphResponseMetadata struct {
25 NumberOfMatches int `json:"number_of_matches"`
26 Truncated bool `json:"truncated"`
29const SourcegraphToolName = "sourcegraph"
31//go:embed sourcegraph.md
32var sourcegraphDescription []byte
34func NewSourcegraphTool(client *http.Client) fantasy.AgentTool {
36 transport := http.DefaultTransport.(*http.Transport).Clone()
37 transport.MaxIdleConns = 100
38 transport.MaxIdleConnsPerHost = 10
39 transport.IdleConnTimeout = 90 * time.Second
41 client = &http.Client{
42 Timeout: 30 * time.Second,
46 return fantasy.NewParallelAgentTool(
48 FirstLineDescription(sourcegraphDescription),
49 func(ctx context.Context, params SourcegraphParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
50 if params.Query == "" {
51 return fantasy.NewTextErrorResponse("Query parameter is required"), nil
54 if params.Count <= 0 {
56 } else if params.Count > 20 {
57 params.Count = 20 // Limit to 20 results
60 if params.ContextWindow <= 0 {
61 params.ContextWindow = 10 // Default context window
64 // Handle timeout with context
66 if params.Timeout > 0 {
67 maxTimeout := 120 // 2 minutes
68 if params.Timeout > maxTimeout {
69 params.Timeout = maxTimeout
71 var cancel context.CancelFunc
72 requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
76 type graphqlRequest struct {
77 Query string `json:"query"`
79 Query string `json:"query"`
83 request := graphqlRequest{
84 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 } } } } } }",
86 request.Variables.Query = params.Query
88 graphqlQueryBytes, err := json.Marshal(request)
90 return fantasy.ToolResponse{}, fmt.Errorf("failed to marshal GraphQL request: %w", err)
92 graphqlQuery := string(graphqlQueryBytes)
94 req, err := http.NewRequestWithContext(
97 "https://sourcegraph.com/.api/graphql",
98 bytes.NewBuffer([]byte(graphqlQuery)),
101 return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
104 req.Header.Set("Content-Type", "application/json")
105 req.Header.Set("User-Agent", "crush/1.0")
107 resp, err := client.Do(req)
109 return fantasy.ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
111 defer resp.Body.Close()
113 if resp.StatusCode != http.StatusOK {
114 body, _ := io.ReadAll(resp.Body)
116 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
119 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
121 body, err := io.ReadAll(resp.Body)
123 return fantasy.ToolResponse{}, fmt.Errorf("failed to read response body: %w", err)
126 var result map[string]any
127 if err = json.Unmarshal(body, &result); err != nil {
128 return fantasy.ToolResponse{}, fmt.Errorf("failed to unmarshal response: %w", err)
131 formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
133 return fantasy.NewTextErrorResponse("Failed to format results: " + err.Error()), nil
136 return fantasy.NewTextResponse(formattedResults), nil
140func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
141 var buffer strings.Builder
143 if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
144 buffer.WriteString("## Sourcegraph API Error\n\n")
145 for _, err := range errors {
146 if errMap, ok := err.(map[string]any); ok {
147 if message, ok := errMap["message"].(string); ok {
148 fmt.Fprintf(&buffer, "- %s\n", message)
152 return buffer.String(), nil
155 data, ok := result["data"].(map[string]any)
157 return "", fmt.Errorf("invalid response format: missing data field")
160 search, ok := data["search"].(map[string]any)
162 return "", fmt.Errorf("invalid response format: missing search field")
165 searchResults, ok := search["results"].(map[string]any)
167 return "", fmt.Errorf("invalid response format: missing results field")
170 matchCount, _ := searchResults["matchCount"].(float64)
171 resultCount, _ := searchResults["resultCount"].(float64)
172 limitHit, _ := searchResults["limitHit"].(bool)
174 buffer.WriteString("# Sourcegraph Search Results\n\n")
175 fmt.Fprintf(&buffer, "Found %d matches across %d results\n", int(matchCount), int(resultCount))
178 buffer.WriteString("(Result limit reached, try a more specific query)\n")
181 buffer.WriteString("\n")
183 results, ok := searchResults["results"].([]any)
184 if !ok || len(results) == 0 {
185 buffer.WriteString("No results found. Try a different query.\n")
186 return buffer.String(), nil
190 if len(results) > maxResults {
191 results = results[:maxResults]
194 for i, res := range results {
195 fileMatch, ok := res.(map[string]any)
200 typeName, _ := fileMatch["__typename"].(string)
201 if typeName != "FileMatch" {
205 repo, _ := fileMatch["repository"].(map[string]any)
206 file, _ := fileMatch["file"].(map[string]any)
207 lineMatches, _ := fileMatch["lineMatches"].([]any)
209 if repo == nil || file == nil {
213 repoName, _ := repo["name"].(string)
214 filePath, _ := file["path"].(string)
215 fileURL, _ := file["url"].(string)
216 fileContent, _ := file["content"].(string)
218 fmt.Fprintf(&buffer, "## Result %d: %s/%s\n\n", i+1, repoName, filePath)
221 fmt.Fprintf(&buffer, "URL: %s\n\n", fileURL)
224 if len(lineMatches) > 0 {
225 for _, lm := range lineMatches {
226 lineMatch, ok := lm.(map[string]any)
231 lineNumber, _ := lineMatch["lineNumber"].(float64)
232 preview, _ := lineMatch["preview"].(string)
234 if fileContent != "" {
235 lines := strings.Split(fileContent, "\n")
237 buffer.WriteString("```\n")
239 startLine := max(1, int(lineNumber)-contextWindow)
241 for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
243 fmt.Fprintf(&buffer, "%d| %s\n", j+1, lines[j])
247 fmt.Fprintf(&buffer, "%d| %s\n", int(lineNumber), preview)
249 endLine := int(lineNumber) + contextWindow
251 for j := int(lineNumber); j < endLine && j < len(lines); j++ {
253 fmt.Fprintf(&buffer, "%d| %s\n", j+1, lines[j])
257 buffer.WriteString("```\n\n")
259 buffer.WriteString("```\n")
260 fmt.Fprintf(&buffer, "%d| %s\n", int(lineNumber), preview)
261 buffer.WriteString("```\n\n")
267 return buffer.String(), nil
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list