probe-code 0.6.0

AI-friendly, fully local, semantic code search tool for large codebases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# Probe AI Integration

Probe offers powerful AI integration capabilities that allow you to leverage large language models (LLMs) to understand and navigate your codebase more effectively. This document provides comprehensive information about Probe's AI features, including the AI chat mode, MCP server integration, and Node.js SDK for programmatic access.

## Table of Contents

- [Privacy Considerations]#privacy-considerations
- [AI Chat Mode]#ai-chat-mode
  - [Overview]#overview
  - [Installation and Setup]#installation-and-setup
  - [Features]#features
  - [Configuration Options]#configuration-options
  - [Advanced Usage]#advanced-usage
  - [Best Practices]#best-practices
- [MCP Server Integration]#mcp-server-integration
  - [Overview]#mcp-overview
  - [Setting Up the MCP Server]#setting-up-the-mcp-server
  - [Available Tools]#available-tools
  - [Integration with AI Assistants]#integration-with-ai-assistants
  - [Advanced Configuration]#advanced-configuration
  - [Troubleshooting]#troubleshooting
- [Node.js SDK]#nodejs-sdk
  - [Overview]#sdk-overview
  - [Installation]#sdk-installation
  - [Core Functions]#core-functions
  - [AI Tools Integration]#ai-tools-integration
  - [Examples]#examples
  - [API Reference]#api-reference

## Privacy Considerations {#privacy-considerations}

When using Probe's AI integration features, it's important to understand the privacy implications:

- **Local Search Engine**: Probe itself is a fully local semantic code search tool that doesn't require embedding generation or cloud indexing
- **Works Like Elastic Search**: Probe functions like a full elastic search on top of your codebase or documentation, without requiring indexing
- **AI Service Integration**: When using Probe with external AI services (Anthropic, OpenAI, Google, etc.), code snippets found by Probe are sent to those services
- **Data Transmission**: The following data may be transmitted to external AI providers:
  - Your natural language queries
  - Code snippets and context found by Probe's search
  - Conversation history for contextual awareness
- **Provider Selection**: You can choose which AI provider to use based on your privacy requirements
- **Local Model Options**: For maximum privacy, Probe can be used with locally-running AI models, keeping all data on your machine

Consider these privacy aspects when choosing how to integrate Probe with AI services, especially when working with sensitive or proprietary code.

## AI Chat Mode {#ai-chat-mode}

### Overview {#overview}

Probe's AI Chat mode provides an interactive CLI interface where you can ask questions about your codebase and get AI-powered responses. This mode combines Probe's powerful code search capabilities with large language models to help you understand and navigate your codebase more effectively.

Key benefits:

- **Natural Language Understanding**: Ask questions about your code in plain English
- **Contextual Awareness**: The AI maintains conversation history for follow-up questions
- **Code-Aware Responses**: Get explanations that reference specific files and line numbers
- **Intelligent Search**: The AI automatically formulates optimal search queries based on your questions

### Installation and Setup {#installation-and-setup}

The AI chat functionality is available as a standalone npm package that can be run directly with npx.

#### Using npx (Recommended)

```bash
# Run directly with npx (no installation needed)
npx -y @buger/probe-chat@latest

# Set your API key first
export ANTHROPIC_API_KEY=your_api_key
# Or for OpenAI
# export OPENAI_API_KEY=your_api_key
# Or for Google
# export GOOGLE_API_KEY=your_api_key

# Or specify a directory to search
npx -y @buger/probe-chat@latest /path/to/your/project
```

#### Using the npm package

```bash
# Install globally
npm install -g @buger/probe-chat@latest

# Start the chat interface
probe-chat
```

#### Using the example code

```bash
# Navigate to the examples directory
cd examples/chat

# Install dependencies
npm install

# Set your API key
export ANTHROPIC_API_KEY=your_api_key
# Or for OpenAI
# export OPENAI_API_KEY=your_api_key
# Or for Google
# export GOOGLE_API_KEY=your_api_key

# Start the chat interface
node index.js
```

### Features {#features}

#### AI-Powered Search

The AI Chat mode uses large language models to understand your questions and search your codebase intelligently. It can:

- Find relevant code based on natural language descriptions
- Explain how different parts of your codebase work together
- Identify patterns and architectural decisions
- Help you understand complex code

#### Multi-Model Support

Probe's AI Chat mode supports multiple AI providers:

- **Anthropic Claude**: Provides excellent code understanding and explanation capabilities
- **OpenAI GPT**: Offers strong general-purpose capabilities
- **Google Gemini**: Delivers fast responses and efficient code search

The default model is selected based on which API key you provide, or you can force a specific provider using the `--force-provider` option or the `FORCE_PROVIDER` environment variable.

#### Force Provider Option

You can force the chat to use a specific provider regardless of which API keys are available:

```bash
# Force using Anthropic Claude
probe-chat --force-provider anthropic

# Force using OpenAI
probe-chat --force-provider openai

# Force using Google Gemini
probe-chat --force-provider google
```

This is useful when you have multiple API keys configured but want to use a specific provider for certain tasks.

#### Token Tracking

The AI Chat mode monitors token usage for both requests and responses, helping you keep track of your API usage:

```
Token Usage: Request: 1245 Response: 1532 (Current message only: ~1532)
Total: 2777 tokens (Cumulative for entire session)
```

#### Conversation History

The chat maintains context across multiple interactions, allowing for follow-up questions and deeper exploration of topics. The history is managed efficiently to prevent context overflow:

- Maintains up to 20 previous messages by default
- Automatically trims older messages when the limit is reached
- Preserves context for follow-up questions

#### Session-Based Caching

The AI Chat mode uses a session-based caching system to avoid showing the same code blocks multiple times in a conversation:

- Each chat instance generates a unique session ID
- The session ID is used to track which code blocks have already been shown
- This prevents redundant information in responses
- The cache is maintained for the duration of the chat session

#### Colored Output

The terminal interface provides user-friendly colored output with syntax highlighting for code blocks, making it easier to read and understand the AI's responses.

### Configuration Options {#configuration-options}

You can configure the AI Chat mode using environment variables:

#### Model Selection

```bash
# Override the default model
export MODEL_NAME=claude-3-opus-20240229
probe-chat

# For Google models
export MODEL_NAME=gemini-2.0-flash
probe-chat
```

#### Force Provider

```bash
# Force a specific provider
export FORCE_PROVIDER=anthropic  # Options: anthropic, openai, google
probe-chat
```

#### API URLs

```bash
# Override API URLs (useful for proxies or enterprise deployments)
export ANTHROPIC_API_URL=https://your-anthropic-proxy.com
export OPENAI_API_URL=https://your-openai-proxy.com/v1
export GOOGLE_API_URL=https://your-google-proxy.com
probe-chat
```

#### Debug Mode

```bash
# Enable debug mode for detailed logging
export DEBUG=1 probe-chat
```

#### Allowed Folders

```bash
# Specify which folders the AI can search
export ALLOWED_FOLDERS=/path/to/project1,/path/to/project2
probe-chat
```

### Advanced Usage {#advanced-usage}

#### Programmatic Usage in Node.js

You can also use the AI Chat functionality programmatically in your Node.js applications:

```javascript
import { ProbeChat } from '@buger/probe-chat';
import { StreamingTextResponse } from 'ai';

// Create a chat instance
const chat = new ProbeChat({
  model: 'claude-3-sonnet-20240229',
  anthropicApiKey: process.env.ANTHROPIC_API_KEY,
  // Or use OpenAI
  // openaiApiKey: process.env.OPENAI_API_KEY,
  // Or use Google
  // googleApiKey: process.env.GOOGLE_API_KEY,
  // Force a specific provider
  // forceProvider: 'anthropic', // Options: 'anthropic', 'openai', 'google'
  allowedFolders: ['/path/to/your/project']
});

// In an API route or Express handler
export async function POST(req) {
  const { messages } = await req.json();
  const userMessage = messages[messages.length - 1].content;
  
  // Get a streaming response from the AI
  const stream = await chat.chat(userMessage, { stream: true });
  
  // Return a streaming response
  return new StreamingTextResponse(stream);
}

// Or use it in a non-streaming way
const response = await chat.chat('How is authentication implemented?');
console.log(response);
```

#### Custom System Messages

You can customize the system message to provide specific instructions to the AI:

```javascript
const chat = new ProbeChat({
  model: 'claude-3-sonnet-20240229',
  anthropicApiKey: process.env.ANTHROPIC_API_KEY,
  // Or use a different provider
  // forceProvider: 'google',
  // googleApiKey: process.env.GOOGLE_API_KEY,
  allowedFolders: ['/path/to/your/project'],
  systemMessage: 'You are a code expert focusing on security issues. When analyzing code, prioritize identifying security vulnerabilities.'
});
```

#### Experimental Thinking

For Claude 3.7 models, you can enable the experimental thinking feature for more detailed reasoning:

```javascript
const chat = new ProbeChat({
  model: 'claude-3-7-sonnet-latest',
  anthropicApiKey: process.env.ANTHROPIC_API_KEY,
  allowedFolders: ['/path/to/your/project'],
  experimentalThinking: {
    enabled: true,
    budget: 8000
  }
});
```

### Best Practices {#best-practices}

1. **Be Specific**: Ask specific questions about your codebase for more targeted answers
2. **Start with Overview Questions**: Begin with high-level questions to understand the structure before diving into details
3. **Follow Up**: Use follow-up questions to explore topics in more depth
4. **Reference Files**: Mention specific files or directories if you want to focus on a particular area
5. **Ask for Explanations**: The AI is particularly good at explaining complex code or concepts
6. **Request Examples**: Ask for examples if you're trying to understand how to use a particular feature or API
7. **Use Multiple Queries**: If you don't find what you're looking for, try reformulating your question
8. **Combine with CLI**: Use the AI chat for exploration and understanding, then switch to the CLI for specific searches

## MCP Server Integration {#mcp-server-integration}

### Overview {#mcp-overview}

The Model Context Protocol (MCP) server mode allows Probe to integrate seamlessly with AI editors and assistants. This mode exposes Probe's powerful search capabilities through a standardized interface that AI tools can use to search and understand your codebase.

Key benefits:

- **Seamless AI Integration**: Allows AI assistants to search and analyze your code
- **Standardized Protocol**: Uses the Model Context Protocol for compatibility with various AI tools
- **Enhanced AI Capabilities**: Gives AI assistants code-aware capabilities
- **Secure Access**: Provides controlled access to your codebase

### Setting Up the MCP Server {#setting-up-the-mcp-server}

#### Using NPX (Recommended)

The easiest way to use Probe's MCP server is through NPX:

```json
{
  "mcpServers": {
    "probe": {
      "command": "npx",
      "args": [
        "-y",
        "@buger/probe-mcp@latest"
      ]
    }
  }
}
```

Add this configuration to your AI editor's MCP configuration file. The exact location depends on your editor, but common locations include:

- For Cline: `.cline/mcp_config.json` in your project directory
- For other editors: Check your editor's documentation for MCP configuration

#### Manual Installation

If you prefer to install the MCP server manually:

1. Install the NPM package globally:
   ```bash
   npm install -g @buger/probe-mcp@latest
   ```

2. Configure your AI editor to use the installed package:
   ```json
   {
     "mcpServers": {
       "probe": {
         "command": "probe-mcp"
       }
     }
   }
   ```

#### Technical Implementation

The Probe MCP server:

- Implements the Model Context Protocol specification
- Uses stdio for communication with AI editors
- Automatically downloads and manages the Probe binary
- Provides three main tools: search_code, query_code, and extract_code
- Handles tool execution and error reporting

### Available Tools {#available-tools}

The Probe MCP server provides the following tools:

#### search_code

Search code in a specified directory using Elasticsearch-like query syntax with session-based caching.

```json
{
  "path": "/path/to/your/project",
  "query": "authentication flow",
  "maxTokens": 20000
}
```

The search tool supports Elasticsearch-like query syntax with the following features:
- Basic term searching: "config" or "search"
- Field-specific searching: "field:value" (e.g., "function:parse")
- Required terms with + prefix: "+required"
- Excluded terms with - prefix: "-excluded"
- Logical operators: "term1 AND term2", "term1 OR term2"
- Grouping with parentheses: "(term1 OR term2) AND term3"

#### query_code

Find specific code structures (functions, classes, etc.) using tree-sitter patterns.

```json
{
  "path": "/path/to/your/project",
  "pattern": "fn $NAME($$$PARAMS) $$$BODY",
  "language": "rust"
}
```

Pattern syntax:
- `$NAME`: Matches an identifier (e.g., function name)
- `$$$PARAMS`: Matches parameter lists
- `$$$BODY`: Matches function bodies
- `$$$FIELDS`: Matches struct/class fields
- `$$$METHODS`: Matches class methods

#### extract_code

Extract code blocks from files based on file paths and optional line numbers.

```json
{
  "path": "/path/to/your/project",
  "files": ["/path/to/your/project/src/main.rs:42"]
}
```

### Integration with AI Assistants {#integration-with-ai-assistants}

Once configured, you can ask your AI assistant to search your codebase with natural language queries. The AI will translate your request into appropriate Probe commands and display the results.

#### Example Queries

Here are some examples of natural language queries you can use:

- "Do the probe and search my codebase for implementations of the ranking algorithm"
- "Using probe find all functions related to error handling in the src directory"
- "Search for code that handles user authentication"
- "Find all instances where we're using the BM25 algorithm"
- "Look for functions that process query parameters"

#### How It Works

1. You ask a question about your codebase to your AI assistant
2. The AI assistant recognizes that Probe can help answer this question
3. The assistant formulates an appropriate search query and parameters
4. The MCP server executes the Probe search command
5. The results are returned to the AI assistant
6. The assistant analyzes the code and provides you with an answer

#### Technical Details

The MCP server:

- Receives tool call requests from the AI assistant
- Parses the request parameters
- Executes the appropriate Probe command
- Returns the results to the AI assistant
- Handles errors and provides appropriate error messages
- Maintains session-based caching to avoid duplicate results

### Advanced Configuration {#advanced-configuration}

#### Custom Search Paths

You can configure the MCP server to search specific directories by default:

```json
{
  "mcpServers": {
    "probe": {
      "command": "npx",
      "args": [
        "-y",
        "@buger/probe-mcp@latest"
      ],
      "env": {
        "PROBE_DEFAULT_PATHS": "/path/to/project1,/path/to/project2"
      }
    }
  }
}
```

#### Limiting Results

You can set default limits for search results:

```json
{
  "mcpServers": {
    "probe": {
      "command": "npx",
      "args": [
        "-y",
        "@buger/probe-mcp@latest"
      ],
      "env": {
        "PROBE_MAX_TOKENS": "20000"
      }
    }
  }
}
```

#### Custom Binary Path

If you have a custom build of the Probe binary, you can specify its path:

```json
{
  "mcpServers": {
    "probe": {
      "command": "npx",
      "args": [
        "-y",
        "@buger/probe-mcp@latest"
      ],
      "env": {
        "PROBE_PATH": "/path/to/custom/probe"
      }
    }
  }
}
```

#### Debug Mode

Enable debug mode for detailed logging:

```json
{
  "mcpServers": {
    "probe": {
      "command": "npx",
      "args": [
        "-y",
        "@buger/probe-mcp@latest"
      ],
      "env": {
        "DEBUG": "1"
      }
    }
  }
}
```

### Troubleshooting {#troubleshooting}

If you encounter issues with the MCP server:

1. **Check Installation**: Ensure the Probe binary was downloaded correctly during package installation
2. **Verify Configuration**: Double-check your MCP configuration file for errors
3. **Check Permissions**: Make sure the AI editor has permission to execute the MCP server
4. **Check Logs**: Look for error messages in your AI editor's logs
5. **Update Packages**: Ensure you're using the latest version of the `@buger/probe-mcp@latest` package
6. **Manual Binary Download**: If the automatic download failed, you can manually download the binary from [GitHub Releases]https://github.com/buger/probe/releases and place it in the `node_modules/@buger/probe-mcp/bin` directory

#### Common Issues and Solutions

| Issue | Solution |
|-------|----------|
| "Binary not found" error | Set the `PROBE_PATH` environment variable to the location of your Probe binary |
| "Permission denied" error | Make sure the binary is executable (`chmod +x /path/to/probe`) |
| Tool calls timeout | Increase the timeout value in your AI editor's configuration |
| Empty search results | Check your query syntax and try a simpler query |
| "Network error" during binary download | Check your internet connection and firewall settings |

## Node.js SDK {#nodejs-sdk}

### Overview {#sdk-overview}

The Node.js SDK provides programmatic access to Probe's powerful code search capabilities. It allows you to integrate Probe into your Node.js applications, build custom tools, and create AI-powered code assistants.

Key benefits:

- **Programmatic Access**: Use Probe's capabilities directly from your Node.js code
- **AI Integration**: Ready-to-use tools for Vercel AI SDK, LangChain, and other AI frameworks
- **Cross-Platform**: Works on Windows, macOS, and Linux
- **Automatic Binary Management**: Handles downloading and managing the Probe binary
- **Type Safety**: Includes TypeScript type definitions

### Installation {#sdk-installation}

#### Local Installation

```bash
npm install @buger/probe@latest
```

#### Global Installation

```bash
npm install -g @buger/probe@latest
```

During installation, the package will automatically download the appropriate probe binary for your platform.

### Core Functions {#core-functions}

The SDK provides three main functions:

#### search

Search for patterns in your codebase using Elasticsearch-like query syntax.

```javascript
import { search } from '@buger/probe';

const searchResults = await search({
  path: '/path/to/your/project',
  query: 'function',
  maxResults: 10
});
```

#### query

Find specific code structures using tree-sitter patterns.

```javascript
import { query } from '@buger/probe';

const queryResults = await query({
  path: '/path/to/your/project',
  pattern: 'function $NAME($$$PARAMS) $$$BODY',
  language: 'javascript'
});
```

#### extract

Extract code blocks from files based on file paths and line numbers.

```javascript
import { extract } from '@buger/probe';

const extractResults = await extract({
  files: ['/path/to/your/project/src/main.js:42']
});
```

### AI Tools Integration {#ai-tools-integration}

The SDK provides built-in tools for integrating with AI frameworks:

#### Vercel AI SDK Integration

```javascript
import { generateText } from 'ai';
import { tools } from '@buger/probe';

// Use the pre-built tools with Vercel AI SDK
async function chatWithAI(userMessage) {
  const result = await generateText({
    model: provider(modelName),
    messages: [{ role: 'user', content: userMessage }],
    system: "You are a code intelligence assistant. Use the provided tools to search and analyze code.",
    tools: {
      search: tools.searchTool,
      query: tools.queryTool,
      extract: tools.extractTool
    },
    maxSteps: 15,
    temperature: 0.7
  });
  
  return result.text;
}
```

#### LangChain Integration

```javascript
import { ChatOpenAI } from '@langchain/openai';
import { tools } from '@buger/probe';

// Create the LangChain tools
const searchTool = tools.createSearchTool();
const queryTool = tools.createQueryTool();
const extractTool = tools.createExtractTool();

// Create a ChatOpenAI instance with tools
const model = new ChatOpenAI({
  modelName: "gpt-4o",
  temperature: 0.7
}).withTools([searchTool, queryTool, extractTool]);

// Use the model with tools
async function chatWithAI(userMessage) {
  const result = await model.invoke([
    { role: "system", content: "You are a code intelligence assistant. Use the provided tools to search and analyze code." },
    { role: "user", content: userMessage }
  ]);
  
  return result.content;
}
```

#### Default System Message

The package provides a default system message that you can use with your AI assistants:

```javascript
import { tools } from '@buger/probe';

// Use the default system message in your AI application
const systemMessage = tools.DEFAULT_SYSTEM_MESSAGE;

// Example with Vercel AI SDK
const result = await generateText({
  model: provider(modelName),
  messages: [{ role: 'user', content: userMessage }],
  system: tools.DEFAULT_SYSTEM_MESSAGE,
  tools: {
    search: tools.searchTool,
    query: tools.queryTool,
    extract: tools.extractTool
  }
});
```

### Examples {#examples}

#### Basic Search Example

```javascript
import { search } from '@buger/probe';

async function basicSearchExample() {
  try {
    const results = await search({
      path: '/path/to/your/project',
      query: 'function',
      maxResults: 5
    });
    
    console.log('Search results:');
    console.log(results);
  } catch (error) {
    console.error('Search error:', error);
  }
}
```

#### Advanced Search with Multiple Options

```javascript
import { search } from '@buger/probe';

async function advancedSearchExample() {
  try {
    const results = await search({
      path: '/path/to/your/project',
      query: 'config AND (parse OR tokenize)',
      ignore: ['node_modules', 'dist'],
      reranker: 'hybrid',
      frequencySearch: true,
      maxResults: 10,
      maxTokens: 20000,
      allowTests: false
    });
    
    console.log('Advanced search results:');
    console.log(results);
  } catch (error) {
    console.error('Advanced search error:', error);
  }
}
```

#### Query for Specific Code Structures

```javascript
import { query } from '@buger/probe';

async function queryExample() {
  try {
    // Find all JavaScript functions
    const jsResults = await query({
      path: '/path/to/your/project',
      pattern: 'function $NAME($$$PARAMS) $$$BODY',
      language: 'javascript',
      maxResults: 5
    });
    
    console.log('JavaScript functions:');
    console.log(jsResults);
    
    // Find all Rust structs
    const rustResults = await query({
      path: '/path/to/your/project',
      pattern: 'struct $NAME $$$BODY',
      language: 'rust',
      maxResults: 5
    });
    
    console.log('Rust structs:');
    console.log(rustResults);
  } catch (error) {
    console.error('Query error:', error);
  }
}
```

#### Extract Code Blocks

```javascript
import { extract } from '@buger/probe';

async function extractExample() {
  try {
    const results = await extract({
      files: [
        '/path/to/your/project/src/main.js',
        '/path/to/your/project/src/utils.js:42'  // Extract from line 42
      ],
      contextLines: 2,
      format: 'markdown'
    });
    
    console.log('Extracted code:');
    console.log(results);
  } catch (error) {
    console.error('Extract error:', error);
  }
}
```

#### Building a Custom AI Assistant

```javascript
import { search, query, extract } from '@buger/probe';
import { ChatOpenAI } from '@langchain/openai';
import { PromptTemplate } from '@langchain/core/prompts';
import { StringOutputParser } from '@langchain/core/output_parsers';

// Create a custom AI assistant that can search code
async function createCodeAssistant() {
  // Create a chat model
  const model = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0.7
  });
  
  // Create a prompt template
  const promptTemplate = PromptTemplate.fromTemplate(`
    You are a code assistant. I'll provide you with a question and some code search results.
    Please analyze the code and answer the question.
    
    Question: {question}
    
    Code search results:
    {searchResults}
    
    Your analysis:
  `);
  
  // Create a chain
  const chain = promptTemplate
    .pipe(model)
    .pipe(new StringOutputParser());
  
  // Function to answer questions about code
  async function answerCodeQuestion(question, codebasePath) {
    // Search for relevant code
    const searchResults = await search({
      path: codebasePath,
      query: question,
      maxResults: 5,
      maxTokens: 10000
    });
    
    // Get the answer from the AI
    const answer = await chain.invoke({
      question,
      searchResults
    });
    
    return answer;
  }
  
  return { answerCodeQuestion };
}

// Usage
const assistant = await createCodeAssistant();
const answer = await assistant.answerCodeQuestion(
  "How is authentication implemented?",
  "/path/to/your/project"
);
console.log(answer);
```

### API Reference {#api-reference}

#### Search

```javascript
import { search } from '@buger/probe';

const results = await search({
  path: '/path/to/your/project',
  query: 'function',
  // Optional parameters
  filesOnly: false,
  ignore: ['node_modules', 'dist'],
  excludeFilenames: false,
  reranker: 'hybrid',
  frequencySearch: true,
  exact: false,
  maxResults: 10,
  maxBytes: 1000000,
  maxTokens: 40000,
  allowTests: false,
  noMerge: false,
  mergeThreshold: 5,
  json: false,
  binaryOptions: {
    forceDownload: false,
    version: '1.0.0'
  }
});
```

##### Parameters

- `path` (required): Path to search in
- `query` (required): Search query or queries (string or array of strings)
- `filesOnly`: Only output file paths
- `ignore`: Patterns to ignore (array of strings)
- `excludeFilenames`: Exclude filenames from search
- `reranker`: Reranking method ('hybrid', 'hybrid2', 'bm25', 'tfidf')
- `frequencySearch`: Use frequency-based search
- `exact`: Use exact matching
- `maxResults`: Maximum number of results
- `maxBytes`: Maximum bytes to return
- `maxTokens`: Maximum tokens to return
- `allowTests`: Include test files
- `noMerge`: Don't merge adjacent blocks
- `mergeThreshold`: Merge threshold
- `json`: Return results as parsed JSON instead of string
- `binaryOptions`: Options for getting the binary
  - `forceDownload`: Force download even if binary exists
  - `version`: Specific version to download

#### Query

```javascript
import { query } from '@buger/probe';

const results = await query({
  path: '/path/to/your/project',
  pattern: 'function $NAME($$$PARAMS) $$$BODY',
  // Optional parameters
  language: 'javascript',
  ignore: ['node_modules', 'dist'],
  allowTests: false,
  maxResults: 10,
  format: 'markdown',
  json: false,
  binaryOptions: {
    forceDownload: false,
    version: '1.0.0'
  }
});
```

##### Parameters

- `path` (required): Path to search in
- `pattern` (required): The ast-grep pattern to search for
- `language`: Programming language to search in
- `ignore`: Patterns to ignore (array of strings)
- `allowTests`: Include test files
- `maxResults`: Maximum number of results
- `format`: Output format ('markdown', 'plain', 'json', 'color')
- `json`: Return results as parsed JSON instead of string
- `binaryOptions`: Options for getting the binary
  - `forceDownload`: Force download even if binary exists
  - `version`: Specific version to download

#### Extract

```javascript
import { extract } from '@buger/probe';

const results = await extract({
  files: [
    '/path/to/your/project/src/main.js',
    '/path/to/your/project/src/utils.js:42'  // Extract from line 42
  ],
  // Optional parameters
  allowTests: false,
  contextLines: 2,
  format: 'markdown',
  json: false,
  binaryOptions: {
    forceDownload: false,
    version: '1.0.0'
  }
});
```

##### Parameters

- `files` (required): Files to extract from (can include line numbers with colon, e.g., "/path/to/file.rs:10")
- `allowTests`: Include test files
- `contextLines`: Number of context lines to include
- `format`: Output format ('markdown', 'plain', 'json')
- `prompt`: System prompt template for LLM models ('engineer', 'architect', or path to file)
- `instructions`: User instructions for LLM models
- `json`: Return results as parsed JSON instead of string
- `binaryOptions`: Options for getting the binary
  - `forceDownload`: Force download even if binary exists
  - `version`: Specific version to download

#### LLM Integration with Extract

```javascript
import { extract } from '@buger/probe';

// Extract code with engineer prompt template
const results = await extract({
  files: ['/path/to/your/project/src/auth.js#authenticate'],
  prompt: 'engineer',
  instructions: 'Explain this authentication function',
  format: 'json'
});

// Extract code with architect prompt template
const results = await extract({
  files: ['/path/to/your/project/src/auth.js'],
  prompt: 'architect',
  instructions: 'Analyze this authentication module',
  format: 'json'
});

// Extract code with custom prompt template
const results = await extract({
  files: ['/path/to/your/project/src/api.js:42'],
  prompt: '/path/to/custom/prompt.txt',
  instructions: 'Refactor this code',
  format: 'json'
});
```

The `prompt` and `instructions` parameters are particularly useful for AI integration workflows, as they allow you to include standardized prompts and specific instructions in the extraction output. This makes it easier to create consistent AI prompting patterns and provide context for code analysis.

#### Binary Management

```javascript
import { getBinaryPath, setBinaryPath } from '@buger/probe';

// Get the path to the probe binary
const binaryPath = await getBinaryPath({
  forceDownload: false,
  version: '1.0.0'
});

// Manually set the path to the probe binary
setBinaryPath('/path/to/probe/binary');
```

#### AI Tools

```javascript
import { tools } from '@buger/probe';

// Vercel AI SDK tools
const { searchTool, queryTool, extractTool } = tools;

// LangChain tools
const searchLangChainTool = tools.createSearchTool();
const queryLangChainTool = tools.createQueryTool();
const extractLangChainTool = tools.createExtractTool();

// Access schemas
const { searchSchema, querySchema, extractSchema } = tools;

// Access default system message
const systemMessage = tools.DEFAULT_SYSTEM_MESSAGE;