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 client = &http.Client{
37 Timeout: 30 * time.Second,
38 Transport: &http.Transport{
40 MaxIdleConnsPerHost: 10,
41 IdleConnTimeout: 90 * time.Second,
45 return fantasy.NewParallelAgentTool(
47 string(sourcegraphDescription),
48 func(ctx context.Context, params SourcegraphParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
49 if params.Query == "" {
50 return fantasy.NewTextErrorResponse("Query parameter is required"), nil
53 if params.Count <= 0 {
55 } else if params.Count > 20 {
56 params.Count = 20 // Limit to 20 results
59 if params.ContextWindow <= 0 {
60 params.ContextWindow = 10 // Default context window
63 // Handle timeout with context
65 if params.Timeout > 0 {
66 maxTimeout := 120 // 2 minutes
67 if params.Timeout > maxTimeout {
68 params.Timeout = maxTimeout
70 var cancel context.CancelFunc
71 requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
75 type graphqlRequest struct {
76 Query string `json:"query"`
78 Query string `json:"query"`
82 request := graphqlRequest{
83 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 } } } } } }",
85 request.Variables.Query = params.Query
87 graphqlQueryBytes, err := json.Marshal(request)
89 return fantasy.ToolResponse{}, fmt.Errorf("failed to marshal GraphQL request: %w", err)
91 graphqlQuery := string(graphqlQueryBytes)
93 req, err := http.NewRequestWithContext(
96 "https://sourcegraph.com/.api/graphql",
97 bytes.NewBuffer([]byte(graphqlQuery)),
100 return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
103 req.Header.Set("Content-Type", "application/json")
104 req.Header.Set("User-Agent", "crush/1.0")
106 resp, err := client.Do(req)
108 return fantasy.ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
110 defer resp.Body.Close()
112 if resp.StatusCode != http.StatusOK {
113 body, _ := io.ReadAll(resp.Body)
115 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d, response: %s", resp.StatusCode, string(body))), nil
118 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
120 body, err := io.ReadAll(resp.Body)
122 return fantasy.ToolResponse{}, fmt.Errorf("failed to read response body: %w", err)
125 var result map[string]any
126 if err = json.Unmarshal(body, &result); err != nil {
127 return fantasy.ToolResponse{}, fmt.Errorf("failed to unmarshal response: %w", err)
130 formattedResults, err := formatSourcegraphResults(result, params.ContextWindow)
132 return fantasy.NewTextErrorResponse("Failed to format results: " + err.Error()), nil
135 return fantasy.NewTextResponse(formattedResults), nil
139func formatSourcegraphResults(result map[string]any, contextWindow int) (string, error) {
140 var buffer strings.Builder
142 if errors, ok := result["errors"].([]any); ok && len(errors) > 0 {
143 buffer.WriteString("## Sourcegraph API Error\n\n")
144 for _, err := range errors {
145 if errMap, ok := err.(map[string]any); ok {
146 if message, ok := errMap["message"].(string); ok {
147 buffer.WriteString(fmt.Sprintf("- %s\n", message))
151 return buffer.String(), nil
154 data, ok := result["data"].(map[string]any)
156 return "", fmt.Errorf("invalid response format: missing data field")
159 search, ok := data["search"].(map[string]any)
161 return "", fmt.Errorf("invalid response format: missing search field")
164 searchResults, ok := search["results"].(map[string]any)
166 return "", fmt.Errorf("invalid response format: missing results field")
169 matchCount, _ := searchResults["matchCount"].(float64)
170 resultCount, _ := searchResults["resultCount"].(float64)
171 limitHit, _ := searchResults["limitHit"].(bool)
173 buffer.WriteString("# Sourcegraph Search Results\n\n")
174 buffer.WriteString(fmt.Sprintf("Found %d matches across %d results\n", int(matchCount), int(resultCount)))
177 buffer.WriteString("(Result limit reached, try a more specific query)\n")
180 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
189 if len(results) > maxResults {
190 results = results[:maxResults]
193 for i, res := range results {
194 fileMatch, ok := res.(map[string]any)
199 typeName, _ := fileMatch["__typename"].(string)
200 if typeName != "FileMatch" {
204 repo, _ := fileMatch["repository"].(map[string]any)
205 file, _ := fileMatch["file"].(map[string]any)
206 lineMatches, _ := fileMatch["lineMatches"].([]any)
208 if repo == nil || file == nil {
212 repoName, _ := repo["name"].(string)
213 filePath, _ := file["path"].(string)
214 fileURL, _ := file["url"].(string)
215 fileContent, _ := file["content"].(string)
217 buffer.WriteString(fmt.Sprintf("## Result %d: %s/%s\n\n", i+1, repoName, filePath))
220 buffer.WriteString(fmt.Sprintf("URL: %s\n\n", fileURL))
223 if len(lineMatches) > 0 {
224 for _, lm := range lineMatches {
225 lineMatch, ok := lm.(map[string]any)
230 lineNumber, _ := lineMatch["lineNumber"].(float64)
231 preview, _ := lineMatch["preview"].(string)
233 if fileContent != "" {
234 lines := strings.Split(fileContent, "\n")
236 buffer.WriteString("```\n")
238 startLine := max(1, int(lineNumber)-contextWindow)
240 for j := startLine - 1; j < int(lineNumber)-1 && j < len(lines); j++ {
242 buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
246 buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
248 endLine := int(lineNumber) + contextWindow
250 for j := int(lineNumber); j < endLine && j < len(lines); j++ {
252 buffer.WriteString(fmt.Sprintf("%d| %s\n", j+1, lines[j]))
256 buffer.WriteString("```\n\n")
258 buffer.WriteString("```\n")
259 buffer.WriteString(fmt.Sprintf("%d| %s\n", int(lineNumber), preview))
260 buffer.WriteString("```\n\n")
266 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