Elffuss BraidHub

kikocis/continue public

Merge branch 'main' of https://github.com/continuedev/continue into hotfix-250613
Changeset4f3a19ed99cfe3423acf4db9155e4b9cc93db6b0286fae6f9a7dc612fd196529
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-13 15:12 -04:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-07-13 15:12 -04:00
Parents74b433c67270, d30610f7e942

Browse the files at this changeset

More than 300 files changed

added .continue/mcpServers/continue-docs-mcp.yaml +11 −0
@@ -0,0 +1,11 @@
1+name: Continue Documentation MCP
2+version: 0.0.1
3+schema: v1
4+mcpServers:
5+ - name: Continue Docs Search
6+ type: stdio
7+ command: npx
8+ args:
9+ - mint-mcp
10+ - add
11+ - continue-docs
added .continue/rules/continue-pun.md +9 −0
@@ -0,0 +1,9 @@
1+---
2+name: Add Continue pun easter eggs
3+description: Adds an easter egg whenever the "continue" keyword
4+pattern: "continue"
5+---
6+
7+Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
8+
9+Do not add a comment if the use of "continue" is not in a code continue statement
added .continue/rules/css-units.md +5 −0
@@ -0,0 +1,5 @@
1+---
2+globs: "gui/**/*.tsx"
3+---
4+
5+You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`.
added .continue/rules/dev-data-guide.md +200 −0
@@ -0,0 +1,200 @@
1+---
2+alwaysApply: false
3+---
4+
5+# Continue Development Data (Dev Data) Guide
6+
7+## Overview
8+
9+Development data (dev data) captures detailed information about how developers interact with LLM-aided development tools. Unlike basic telemetry, dev data includes lots of details into the complete software development workflow, including code context, user interactions, and development patterns.
10+
11+## Core Architecture
12+
13+### Primary Implementation Files
14+
15+- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission
16+- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types
17+
18+### Storage Locations
19+
20+- **Default storage**: `~/.continue/dev_data/`
21+- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl`
22+
23+## Event Types and Schemas
24+
25+### Core Event Types
26+
27+1. **`tokensGenerated`**: LLM token usage tracking
28+2. **`autocomplete`**: Code completion interactions
29+3. **`chatInteraction`**: Chat-based development assistance
30+4. **`editInteraction`**: Code editing sessions
31+5. **`editOutcome`**: Results of edit operations
32+6. **`nextEditOutcome`**: Next Edit feature outcomes
33+7. **`chatFeedback`**: User feedback on AI responses
34+8. **`toolUsage`**: Tool interaction statistics
35+9. **`quickEdit`**: Quick edit functionality usage
36+
37+### Schema Versioning
38+
39+- **Version 0.1.0**: Initial schema implementation
40+- **Version 0.2.0**: Current schema with expanded fields and metadata
41+- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/`
42+
43+### Base Schema Structure
44+
45+All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`):
46+
47+```typescript
48+{
49+ eventName: string,
50+ schema: string,
51+ timestamp: string,
52+ userId: string,
53+ userAgent: string,
54+ selectedProfileId: string
55+}
56+```
57+
58+## Key Integration Points
59+
60+### Autocomplete System
61+
62+- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts`
63+- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits
64+- **Integration**: Called from autocomplete engine when completions are shown/accepted
65+
66+### Chat Interface
67+
68+- **Integration**: Chat interactions logged through `DataLogger.logDevData()`
69+- **Data**: Includes prompts, responses, context, and user feedback
70+- **Privacy**: Can be configured to exclude code content
71+
72+### Edit Features
73+
74+- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts`
75+- **Purpose**: Track edit suggestions, acceptance rates, and outcomes
76+- **Integration**: Embedded in edit workflow to capture user decisions
77+
78+### LLM Token Tracking
79+
80+- **File**: `/core/llm/index.ts`
81+- **Purpose**: Track token usage across all LLM providers
82+- **Storage**: SQLite database for efficient querying and reporting
83+
84+## Configuration and Customization
85+
86+### Configuration Structure
87+
88+Dev data is configured through `data` blocks in your Continue config:
89+
90+```yaml
91+data:
92+ - name: "Local Development Data"
93+ destination: "file:///Users/developer/.continue/dev_data"
94+ schema: "0.2.0"
95+ level: "all"
96+ events: ["autocomplete", "chatInteraction", "editOutcome"]
97+
98+ - name: "Team Analytics"
99+ destination: "https://analytics.yourcompany.com/api/events"
100+ schema: "0.2.0"
101+ level: "noCode"
102+ apiKey: "your-api-key-here"
103+ events: ["tokensGenerated", "toolUsage"]
104+```
105+
106+### Configuration Options
107+
108+- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote)
109+- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`)
110+- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content)
111+- **`events`**: Array of event types to collect
112+- **`apiKey`**: Authentication for remote endpoints
113+
114+### Privacy Controls
115+
116+- **`"all"` level**: Includes code content (prefixes, suffixes, completions)
117+- **`"noCode"` level**: Excludes code content, only metadata and metrics
118+- **Local-first**: Data is always stored locally, remote transmission is optional
119+
120+## Making Changes to Dev Data
121+
122+### Adding New Event Types
123+
124+1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/`
125+2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts`
126+3. **Implement logging**: Add logging calls in relevant service files
127+4. **Update version**: Consider schema version bump if breaking changes
128+
129+### Modifying Existing Events
130+
131+1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/`
132+2. **Backward compatibility**: Ensure changes don't break existing data consumers
133+3. **Version management**: Increment schema version for breaking changes
134+4. **Test thoroughly**: Validate schema changes with existing data
135+
136+### Adding New Logging Points
137+
138+1. **Import DataLogger**: `import { DataLogger } from "core/data/log"`
139+2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)`
140+3. **Follow patterns**: Use existing logging services as examples
141+4. **Validate data**: Ensure logged data matches schema requirements
142+
143+### Debugging Dev Data Issues
144+
145+1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/`
146+2. **Validate schemas**: Ensure event data matches expected schema format
147+3. **Review configuration**: Check `data` blocks in Continue config
148+4. **Test endpoints**: Verify remote endpoints are reachable and accepting data
149+
150+## Best Practices
151+
152+### When Adding New Events
153+
154+- Follow existing naming conventions for event types
155+- Include sufficient context for analysis without oversharing sensitive data
156+- Consider privacy implications and respect user configuration levels
157+- Add appropriate error handling and logging
158+
159+### When Modifying Schemas
160+
161+- Maintain backward compatibility when possible
162+- Document schema changes thoroughly
163+- Consider impact on existing data consumers
164+- Test with real development data
165+
166+### When Integrating Logging
167+
168+- Use the singleton pattern: `DataLogger.getInstance()`
169+- Log events at appropriate points in user workflow
170+- Respect user privacy settings and configuration
171+- Handle errors gracefully without disrupting user experience
172+
173+## Common Patterns
174+
175+### Service-Based Logging
176+
177+Most dev data logging follows a service pattern:
178+
179+```typescript
180+export class FeatureLoggingService {
181+ private dataLogger = DataLogger.getInstance();
182+
183+ logFeatureUsage(data: FeatureUsageData) {
184+ this.dataLogger.logDevData("featureUsage", data);
185+ }
186+}
187+```
188+
189+### Event-Driven Logging
190+
191+Events are typically logged at key interaction points:
192+
193+```typescript
194+// When user accepts autocomplete
195+onAutocompleteAccepted(completion: CompletionData) {
196+ AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion);
197+}
198+```
199+
200+This guide provides the foundation for understanding and working with Continue's dev data system. Always prioritize user privacy and follow established patterns when making changes.
modified .continue/rules/documentation-standards.md +105 −10
@@ -1,16 +1,111 @@
11 ---
2-globs: docs/**/*.{md,mdx}
3-description: Standards for writing and maintaining Continue Docs
2+globs: docs/\*_/_.{md,mdx}
3+description: This style guide should be used as a reference for maintaining consistency across all Continue documentation
4+alwaysApply: false
45 ---
56
6-# Continue Docs Standards
7+# Continue Documentation Style Guide
8+
9+## Overview
10+
11+## Writing Tone & Voice
12+
13+### Conversational and Direct
714
815 - Follow Docusaurus documentation standards
9-- Include YAML frontmatter with title, description, and keywords
10-- Use consistent heading hierarchy starting with h2 (##)
11-- Include relevant Admonition components for tips, warnings, and info
12-- Use descriptive alt text for images
13-- Include cross-references to related documentation
14-- Reference other docs with relative paths
16+- Use simple, conversational language that gets straight to the point
17+- Avoid overly technical jargon when simpler terms work
18+- Write as if speaking directly to the developer using the tool
1519 - Keep paragraphs concise and scannable
16-- Use code blocks with appropriate language tags
20+
21+**Example:**
22+✅ "You send it a question, and it replies with an answer"
23+❌ "The system processes user queries and generates corresponding responses"
24+
25+### Helpful and Instructional
26+
27+- Focus on helping users accomplish their goals
28+- Use active voice and imperative mood for instructions
29+- Assume users want to get things done quickly
30+- Include relevant Admonition components for tips, warnings, and info
31+
32+**Example:**
33+✅ "Press cmd/ctrl + L to begin a new session"
34+❌ "A new session can be initiated by pressing cmd/ctrl + L"
35+
36+### Practical and Task-Oriented
37+
38+- Emphasize what users can accomplish with each feature
39+- Lead with benefits and use cases before diving into mechanics
40+- Keep explanations grounded in real-world scenarios
41+
42+## Content Structure
43+
44+### Page Organization
45+
46+1. **Visual Introduction**: Lead with GIFs or images showing the feature in action
47+2. **Purpose Statement**: Brief explanation of what the feature does and when to use it
48+3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts
49+4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed
50+5. **Additional Tips**: Advanced usage or troubleshooting notes
51+
52+### Section Headers
53+
54+- Use consistent heading hierarchy starting with h2 (##)
55+- Include YAML frontmatter with title, description, and keywords
56+- Use action-oriented headers that describe what users will do
57+- Format: "Verb + object" (e.g., "Type a request and press enter")
58+- Keep headers concise but descriptive
59+- Use title case
60+
61+**Examples:**
62+✅ "Highlight code and activate"
63+✅ "Accept or reject changes"
64+✅ "Switch between different models"
65+
66+### Lists and Steps
67+
68+- Use numbered lists for sequential steps
69+- Use bullet points for feature lists or options
70+- Keep list items parallel in structure
71+- Start action items with verbs
72+
73+## Technical Writing Standards
74+
75+### Code and Keyboard Shortcuts
76+
77+- Use `backticks` for inline code elements
78+- Format keyboard shortcuts consistently: `cmd/ctrl + L`
79+- Always provide shortcuts for Mac/Windows/Linux
80+- Use code blocks for configuration examples with proper syntax highlighting
81+
82+### Cross-References
83+
84+- Link to related sections using descriptive anchor text
85+- Use relative links to other documentation pages
86+- Format: `[descriptive text](/path/to/page)`
87+
88+### Platform Differences
89+
90+- Always address both VS Code and JetBrains when applicable
91+- Use clear subheadings to separate platform-specific instructions
92+- Lead with the more common platform (typically VS Code) when both are covered
93+
94+## Language Conventions
95+
96+### Terminology
97+
98+- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places)
99+- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue)
100+- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete)
101+
102+### Abbreviations
103+
104+- Spell out acronyms on first use, then use abbreviation consistently
105+- Common abbreviations: LLM, IDE, API, URL
106+
107+### Pronouns
108+
109+- Use "you" to address the user directly
110+- Use "it" to refer to the tool/model
111+- Avoid "we" unless referring to the Continue team
added .continue/rules/edit-aggregator-singleton-rule.md +8 −0
@@ -0,0 +1,8 @@
1+---
2+patterns: ["EditAggregator", "processEdit"]
3+glob: "**/*.tsx"
4+name: "Enforce EditAggregator Singleton"
5+description: "Ensure that EditAggregator is used as a singleton in the codebase."
6+---
7+
8+When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator.
added .continue/rules/github-pr-documentation-updater.md +7 −0
@@ -0,0 +1,7 @@
1+---
2+name: Update docs from GitHub PR
3+description: Provide a PR link to update docs based on
4+alwaysApply: false
5+---
6+
7+When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.
added .continue/rules/migrate-styled-components-to-tailwind.md +5 −0
@@ -0,0 +1,5 @@
1+---
2+alwaysApply: false
3+---
4+
5+Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}`. For ternaries, you could use @cn.ts.
added .continue/rules/navigating-responses.md +4 −0
@@ -0,0 +1,4 @@
1+If the user's request is vague and you don't have enough information to confidently answer, you can either
2+
3+- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
4+- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.
added .continue/rules/new-protocol-message.md +35 −0
@@ -0,0 +1,35 @@
1+---
2+name: New protocol message
3+description: Create a new protocol message from core/gui/ide to core/gui/ide
4+---
5+
6+Create a new protocol message by taking the following steps:
7+
8+## 1. Define the message type
9+
10+Add your new message type definition to the appropriate file in the `protocol/` directory with correct TypeScript typing.
11+
12+## 2. Check for duplicates
13+
14+Verify that no existing message type already provides the same functionality.
15+
16+## 3. Add to passThrough (if webview ↔ core)
17+
18+If your message is between webview and core, add it to `core/protocol/passThrough.ts`.
19+
20+## 4. Add to IntelliJ constants (if webview ↔ core)
21+
22+If your message is between webview and core, add it to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`.
23+
24+## 5. Implement the message handler
25+
26+Implement the message in the appropriate location:
27+
28+- **Messages to core**: `core/core.ts`
29+- **Messages to GUI**: `useWebviewListener` hook
30+- **Messages to VS Code IDE**: `VsCodeMessenger.ts`
31+- **Messages to JetBrains IDE**: `IdeProtocolClient.kt`
32+
33+## 6. Test the implementation
34+
35+Verify that your message works correctly in both VS Code and JetBrains IDEs if applicable.
added .continue/rules/overeager.md +5 −0
@@ -0,0 +1,5 @@
1+---
2+name: Don't be overeager
3+---
4+
5+Avoid over-eagerly adding new features. You should solve the problem at hand and then can propose further work.
added .continue/rules/programming-principles.md +6 −0
@@ -0,0 +1,6 @@
1+---
2+name: Programming principles
3+description: Guidelines for coding fundamentals in this project
4+---
5+
6+Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.
added .continue/rules/pure-function-unit-tests.md +1 −0
@@ -0,0 +1,1 @@
1+Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.
added .continue/rules/test-running-guide.md +25 −0
@@ -0,0 +1,25 @@
1+---
2+globs: ["gui/**/*", "core/**/*"]
3+description: Provides test running instructions for GUI and core folders
4+alwaysApply: false
5+---
6+
7+When working with test files, use the following commands to run tests:
8+
9+GUI folder tests:
10+
11+- Run all tests: `cd gui && npm test`
12+
13+Core folder tests:
14+
15+- Run Jest tests: `cd core && npm test`
16+- Run Vitest tests: `cd core && npm run vitest`
17+
18+Test file patterns:
19+
20+- GUI: _.test.ts or_.test.tsx files use Vitest
21+- Core: _.test.ts files use Jest,_.vitest.ts files use Vitest
22+
23+Best practices:
24+
25+- We are transitioning to vitest, so use that when creating new tests
modified .continue/rules/unit-testing-rules.yaml +18 −20
@@ -6,25 +6,23 @@
66 rule: >-
77 For unit testing in this project:
88
9-
10- 1. The project uses Jest as the testing framework
11-
12- 2. Run tests using `npm test` from within the specific package/module
13- directory
14-
15- 3. Command structure: `cd [directory] && npm test -- [test file path]`
16-
17- 4. The test script uses experimental VM modules via NODE_OPTIONS flag
18-
19- 5. Test files follow the pattern `*.test.ts`
20-
21- 6. Tests must import Jest with `import { jest } from "@jest/globals";`
22-
23- 7. Run tests from within the specific package directory (e.g., `cd core`
24- for core module tests)
25-
26- 8. Write tests as top-level `test()` functions - DO NOT use `describe()`
9+ 1. The project uses Vitest and Jest for testing. Prefer Vitest
10+
11+ 2. Run tests from within the specific package directory (e.g., `cd core && ..`
12+
13+ 3. For vitest tests,
14+ - Test files follow the pattern `*.vitest.ts`
15+ - Run tests using `vitest` from within the specific package/module
16+ directory: `cd [directory] && vitest -- [test file path]`
17+
18+ 4. For jest tests,
19+ - Test files follow the pattern `*.test.ts`
20+ - Run tests using `npm test` from within the specific package/module
21+ directory: `cd [directory] && npm test -- [test file path]`
22+ - The test script uses experimental VM modules via NODE_OPTIONS flag
23+
24+ 5. For both
25+ - Write tests as top-level `test()` functions - DO NOT use `describe()`
2726 blocks
28-
29- 9. Include the function name being tested in the test description for
27+ - Include the function name being tested in the test description for
3028 clarity
added .continue/rules/vs-code-commands-helper-functions.md +5 −0
@@ -0,0 +1,5 @@
1+---
2+globs: "extensions/vscode/src/commands.ts"
3+---
4+
5+When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.
modified .eslintrc.shared.json +1 −0
@@ -10,6 +10,7 @@
1010 "@typescript-eslint/naming-convention": "off",
1111 "@typescript-eslint/no-floating-promises": "warn",
1212 "@typescript-eslint/semi": "warn",
13+ "@typescript-eslint/no-misused-promises": "error",
1314 "curly": "warn",
1415 "eqeqeq": "warn",
1516 "no-throw-literal": "warn",
modified .github/workflows/cla.yaml +2 −1
@@ -26,5 +26,6 @@
2626 path-to-signatures: "signatures/version1/cla.json"
2727 path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
2828 branch: cla-signatures
29- allowlist: dependabot[bot]
29+ # Bots and CLAs signed outside of GitHub
30+ allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
3031 signed-commit-message: "CLA signed in $pullRequestNo"
added .github/workflows/compliance.yaml +197 −0
@@ -0,0 +1,197 @@
1+name: PR Compliance Checks
2+
3+on:
4+ pull_request:
5+ types: [opened, synchronize, reopened, ready_for_review]
6+ branches: [main]
7+ workflow_dispatch:
8+
9+concurrency:
10+ group: ${{ github.workflow }}-${{ github.ref }}
11+ cancel-in-progress: true
12+
13+jobs:
14+ conventional-commits:
15+ name: Validate Conventional Commits (Warning Only)
16+ runs-on: ubuntu-latest
17+ if: ${{ !github.event.pull_request.draft }}
18+ continue-on-error: true
19+ permissions:
20+ pull-requests: write
21+ issues: write
22+ contents: read
23+ steps:
24+ - name: Checkout code
25+ uses: actions/checkout@v4
26+ with:
27+ fetch-depth: 0
28+
29+ - name: Validate conventional commits
30+ id: commitlint
31+ uses: wagoid/commitlint-github-action@v6
32+ with:
33+ configFile: .commitlintrc.warning.json
34+ continue-on-error: true
35+
36+ - name: Add commit message guidance comment
37+ if: steps.commitlint.outcome == 'failure'
38+ uses: actions/github-script@v7
39+ with:
40+ script: |
41+ const { data: comments } = await github.rest.issues.listComments({
42+ owner: context.repo.owner,
43+ repo: context.repo.repo,
44+ issue_number: context.issue.number,
45+ });
46+
47+ const botComment = comments.find(comment =>
48+ comment.user.type === 'Bot' &&
49+ comment.body.includes('Conventional Commit Format')
50+ );
51+
52+ if (!botComment) {
53+ await github.rest.issues.createComment({
54+ owner: context.repo.owner,
55+ repo: context.repo.repo,
56+ issue_number: context.issue.number,
57+ body: [
58+ "## ⚠️ Conventional Commit Format",
59+ "",
60+ "Your commit messages don't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
61+ "",
62+ "### Expected Format:",
63+ "```",
64+ "<type>[optional scope]: <description>",
65+ "",
66+ "[optional body]",
67+ "",
68+ "[optional footer(s)]",
69+ "```",
70+ "",
71+ "### Examples:",
72+ "- `feat: add changelog generation support`",
73+ "- `fix: resolve login redirect issue`",
74+ "- `docs: update README with new instructions`",
75+ "- `chore: update dependencies`",
76+ "",
77+ "### Valid Types:",
78+ "`feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`",
79+ "",
80+ "This helps with:",
81+ "- 📝 Automatic changelog generation",
82+ "- 🚀 Automated semantic versioning",
83+ "- 📊 Better project history tracking",
84+ "",
85+ "*This is a non-blocking warning - your PR can still be merged without fixing this.*"
86+ ].join('\n')
87+ });
88+ }
89+
90+ security-audit:
91+ name: Security Audit
92+ runs-on: ubuntu-latest
93+ if: ${{ !github.event.pull_request.draft }}
94+ permissions:
95+ security-events: write
96+ contents: read
97+ steps:
98+ - name: Checkout code
99+ uses: actions/checkout@v4
100+
101+ - name: Setup Node.js
102+ uses: actions/setup-node@v4
103+ with:
104+ node-version-file: ".nvmrc"
105+ cache: "npm"
106+
107+ - name: Install dependencies
108+ run: npm ci
109+
110+ - name: Fix vulnerabilities
111+ run: npm audit fix
112+
113+ - name: Run npm audit
114+ run: npm audit --audit-level=moderate
115+
116+ - name: Initialize CodeQL
117+ uses: github/codeql-action/init@v3
118+ with:
119+ languages: javascript
120+
121+ - name: Perform CodeQL Analysis
122+ uses: github/codeql-action/analyze@v3
123+
124+ # Use this for any files that we want to be certain exist
125+ # Basically creates a forcing function to discuss were anyone to want to remove them
126+ file-validation:
127+ name: Required Files Check
128+ runs-on: ubuntu-latest
129+ if: ${{ !github.event.pull_request.draft }}
130+ steps:
131+ - name: Checkout code
132+ uses: actions/checkout@v4
133+
134+ - name: Check required files
135+ run: |
136+ required_files=(
137+ "package.json"
138+ "package-lock.json"
139+ "README.md"
140+ "LICENSE"
141+ ".gitignore"
142+ "tsconfig.json"
143+ "SECURITY.md"
144+ "CONTRIBUTING.md"
145+ ".nvmrc"
146+ ".prettierrc"
147+ ".prettierignore"
148+ )
149+
150+ missing_files=()
151+ for file in "${required_files[@]}"; do
152+ if [[ ! -f "$file" ]]; then
153+ missing_files+=("$file")
154+ fi
155+ done
156+
157+ if [[ ${#missing_files[@]} -gt 0 ]]; then
158+ echo "❌ Missing required files:"
159+ printf '%s\n' "${missing_files[@]}"
160+ exit 1
161+ else
162+ echo "✅ All required files present"
163+ fi
164+
165+ compliance-summary:
166+ name: Compliance Summary
167+ runs-on: ubuntu-latest
168+ needs: [conventional-commits, security-audit, file-validation]
169+ if: always() && !github.event.pull_request.draft
170+ steps:
171+ - name: Check compliance status
172+ run: |
173+ echo "## 🔍 Compliance Check Results" >> $GITHUB_STEP_SUMMARY
174+ echo "" >> $GITHUB_STEP_SUMMARY
175+
176+ if [[ "${{ needs.conventional-commits.result }}" == "success" ]]; then
177+ echo "✅ Conventional Commits: PASSED" >> $GITHUB_STEP_SUMMARY
178+ elif [[ "${{ needs.conventional-commits.result }}" == "failure" ]]; then
179+ echo "⚠️ Conventional Commits: WARNING (non-blocking)" >> $GITHUB_STEP_SUMMARY
180+ else
181+ echo "❌ Conventional Commits: SKIPPED" >> $GITHUB_STEP_SUMMARY
182+ fi
183+
184+ if [[ "${{ needs.security-audit.result }}" == "success" ]]; then
185+ echo "✅ Security Audit: PASSED" >> $GITHUB_STEP_SUMMARY
186+ else
187+ echo "❌ Security Audit: FAILED" >> $GITHUB_STEP_SUMMARY
188+ fi
189+
190+ if [[ "${{ needs.file-validation.result }}" == "success" ]]; then
191+ echo "✅ File Validation: PASSED" >> $GITHUB_STEP_SUMMARY
192+ else
193+ echo "❌ File Validation: FAILED" >> $GITHUB_STEP_SUMMARY
194+ fi
195+
196+ echo "" >> $GITHUB_STEP_SUMMARY
197+ echo "📊 **Overall Status**: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY
added .github/workflows/docs.yml +32 −0
@@ -0,0 +1,32 @@
1+name: Docs Check
2+
3+on:
4+ push:
5+ paths:
6+ - 'docs2/**'
7+ pull_request:
8+ paths:
9+ - 'docs2/**'
10+
11+jobs:
12+ check-broken-links:
13+ runs-on: ubuntu-latest
14+
15+ steps:
16+ - name: Checkout repository
17+ uses: actions/checkout@v4
18+
19+ - name: Setup Node.js
20+ uses: actions/setup-node@v4
21+ with:
22+ node-version: '18'
23+ cache: 'npm'
24+ cache-dependency-path: docs2/package-lock.json
25+
26+ - name: Install dependencies
27+ working-directory: ./docs2
28+ run: npm ci
29+
30+ - name: Check for broken links
31+ working-directory: ./docs2
32+ run: npx mintlify broken-links
No newline at the end of the file
modified .github/workflows/jetbrains-release.yaml +2 −14
@@ -167,20 +167,8 @@
167167 path: gui/node_modules
168168 key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
169169
170- - uses: actions/cache@v4
171- id: config-yaml-cache
172- with:
173- path: packages/config-yaml/node_modules
174- key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
175-
176- - name: Build and check config-yaml
177- run: |
178- cd ../../packages/config-yaml
179- npm i
180- npx tsc --noEmit
181- # Tests are currently failing, commenting out for now
182- # npm test
183- npm run build
170+ - name: Build packages (Unix)
171+ run: cd ../.. && ./scripts/build-packages.sh
184172
185173 # npm install core
186174 - name: Install core node_modules
modified .github/workflows/main.yaml +8 −0
@@ -104,6 +104,14 @@
104104 path: gui/node_modules
105105 key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
106106
107+ - name: Build packages (Windows)
108+ run: ./scripts/build-packages.ps1
109+ if: matrix.os == 'windows-latest'
110+
111+ - name: Build packages (Unix)
112+ run: ./scripts/build-packages.sh
113+ if: matrix.os != 'windows-latest'
114+
107115 - name: Install extension Dependencies
108116 run: |
109117 cd extensions/vscode
modified .github/workflows/metrics.yaml +1 −1
@@ -50,7 +50,7 @@
5050 echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
5151
5252 - name: Post a message in a channel
53- uses: slackapi/slack-github-action@v2.1.0
53+ uses: slackapi/slack-github-action@v2.1.1
5454 with:
5555 webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
5656 webhook-type: incoming-webhook
modified .github/workflows/pr_checks.yaml +182 −12
@@ -75,6 +75,33 @@
7575 cd packages/config-yaml
7676 npm ci
7777
78+ install-openai-adapters:
79+ needs: install-root
80+ runs-on: ubuntu-latest
81+ steps:
82+ - uses: actions/checkout@v4
83+
84+ - uses: actions/setup-node@v4
85+ with:
86+ node-version-file: ".nvmrc"
87+
88+ - uses: actions/cache@v4
89+ with:
90+ path: node_modules
91+ key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
92+
93+ - uses: actions/cache@v4
94+ id: openai-adapters-cache
95+ with:
96+ path: packages/openai-adapters/node_modules
97+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
98+
99+ - name: Install openai-adapters dependencies
100+ if: steps.openai-adapters-cache.outputs.cache-hit != 'true'
101+ run: |
102+ cd packages/openai-adapters
103+ npm ci
104+
78105 config-yaml-checks:
79106 needs: install-config-yaml
80107 runs-on: ubuntu-latest
@@ -133,7 +160,7 @@
133160 npm ci
134161
135162 core-checks:
136- needs: [install-core, install-config-yaml]
163+ needs: [install-core, install-config-yaml, install-openai-adapters]
137164 runs-on: ubuntu-latest
138165 steps:
139166 - uses: actions/checkout@v4
@@ -160,11 +187,21 @@
160187 path: packages/config-yaml/node_modules
161188 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
162189
190+ - uses: actions/cache@v4
191+ id: openai-adapters-cache
192+ with:
193+ path: packages/openai-adapters/node_modules
194+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
195+
163196 - name: Build config-yaml
164197 run: |
165198 cd packages/config-yaml
166199 npm run build
167200
201+ - name: Build openai-adapters
202+ run: |
203+ cd packages/openai-adapters
204+ npm run build
168205 - name: Type check and lint
169206 run: |
170207 cd core
@@ -174,7 +211,8 @@
174211 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
175212
176213 install-gui:
177- needs: [install-root, install-core, install-config-yaml]
214+ needs:
215+ [install-root, install-core, install-config-yaml, install-openai-adapters]
178216 runs-on: ubuntu-latest
179217 steps:
180218 - uses: actions/checkout@v4
@@ -205,11 +243,22 @@
205243 path: packages/config-yaml/node_modules
206244 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
207245
246+ - uses: actions/cache@v4
247+ id: openai-adapters-cache
248+ with:
249+ path: packages/openai-adapters/node_modules
250+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
251+
208252 - name: Build config-yaml
209253 run: |
210254 cd packages/config-yaml
211255 npm run build
212256
257+ - name: Build openai-adapters
258+ run: |
259+ cd packages/openai-adapters
260+ npm run build
261+
213262 - name: Install gui dependencies
214263 if: steps.gui-cache.outputs.cache-hit != 'true'
215264 run: |
@@ -221,7 +270,6 @@
221270 runs-on: ubuntu-latest
222271 steps:
223272 - uses: actions/checkout@v4
224-
225273 - uses: actions/setup-node@v4
226274 with:
227275 node-version-file: ".nvmrc"
@@ -242,6 +290,12 @@
242290 path: gui/node_modules
243291 key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
244292
293+ - uses: actions/cache@v4
294+ id: openai-adapters-cache
295+ with:
296+ path: packages/openai-adapters/node_modules
297+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
298+
245299 - uses: actions/cache@v4
246300 id: config-yaml-cache
247301 with:
@@ -253,6 +307,11 @@
253307 cd packages/config-yaml
254308 npm run build
255309
310+ - name: Build openai-adapters
311+ run: |
312+ cd packages/openai-adapters
313+ npm run build
314+
256315 - name: Type check and lint
257316 run: |
258317 cd gui
@@ -260,7 +319,8 @@
260319 npm run lint
261320
262321 binary-checks:
263- needs: [install-root, install-core, install-config-yaml]
322+ needs:
323+ [install-root, install-core, install-config-yaml, install-openai-adapters]
264324 runs-on: ubuntu-latest
265325 steps:
266326 - uses: actions/checkout@v4
@@ -291,11 +351,22 @@
291351 path: packages/config-yaml/node_modules
292352 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
293353
354+ - uses: actions/cache@v4
355+ id: openai-adapters-cache
356+ with:
357+ path: packages/openai-adapters/node_modules
358+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
359+
294360 - name: Build config-yaml
295361 run: |
296362 cd packages/config-yaml
297363 npm run build
298364
365+ - name: Build openai-adapters
366+ run: |
367+ cd packages/openai-adapters
368+ npm run build
369+
299370 - name: Install binary dependencies
300371 if: steps.binary-cache.outputs.cache-hit != 'true'
301372 run: |
@@ -308,7 +379,8 @@
308379 npx tsc --noEmit
309380
310381 install-vscode:
311- needs: [install-root, install-core, install-config-yaml]
382+ needs:
383+ [install-root, install-core, install-config-yaml, install-openai-adapters]
312384 runs-on: ubuntu-latest
313385 steps:
314386 - uses: actions/checkout@v4
@@ -339,11 +411,22 @@
339411 path: packages/config-yaml/node_modules
340412 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
341413
414+ - uses: actions/cache@v4
415+ id: openai-adapters-cache
416+ with:
417+ path: packages/openai-adapters/node_modules
418+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
419+
342420 - name: Build config-yaml
343421 run: |
344422 cd packages/config-yaml
345423 npm run build
346424
425+ - name: Build openai-adapters
426+ run: |
427+ cd packages/openai-adapters
428+ npm run build
429+
347430 - name: Install vscode dependencies
348431 if: steps.vscode-cache.outputs.cache-hit != 'true'
349432 run: |
@@ -384,11 +467,22 @@
384467 path: packages/config-yaml/node_modules
385468 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
386469
470+ - uses: actions/cache@v4
471+ id: openai-adapters-cache
472+ with:
473+ path: packages/openai-adapters/node_modules
474+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
475+
387476 - name: Build config-yaml
388477 run: |
389478 cd packages/config-yaml
390479 npm run build
391480
481+ - name: Build openai-adapters
482+ run: |
483+ cd packages/openai-adapters
484+ npm run build
485+
392486 - name: Type check and lint
393487 run: |
394488 cd extensions/vscode
@@ -396,8 +490,13 @@
396490 npx tsc --noEmit
397491 npm run lint
398492
493+ - name: Run vitest tests
494+ run: |
495+ cd extensions/vscode
496+ npm run vitest
497+
399498 core-tests:
400- needs: [install-core, install-config-yaml]
499+ needs: [install-core, install-config-yaml, install-openai-adapters]
401500 runs-on: ubuntu-latest
402501 steps:
403502 - uses: actions/checkout@v4
@@ -417,11 +516,22 @@
417516 path: packages/config-yaml/node_modules
418517 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
419518
519+ - uses: actions/cache@v4
520+ id: openai-adapters-cache
521+ with:
522+ path: packages/openai-adapters/node_modules
523+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
524+
420525 - name: Build config-yaml
421526 run: |
422527 cd packages/config-yaml
423528 npm run build
424529
530+ - name: Build openai-adapters
531+ run: |
532+ cd packages/openai-adapters
533+ npm run build
534+
425535 - name: Run core tests
426536 run: |
427537 cd core
@@ -434,7 +544,7 @@
434544 GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
435545 MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
436546 AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
437- AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
547+ AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
438548 AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
439549 AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
440550
@@ -471,7 +581,7 @@
471581 - uses: actions/checkout@v4
472582
473583 - name: Cache node modules
474- uses: actions/cache@v3
584+ uses: actions/cache@v4
475585 with:
476586 path: extensions/vscode/node_modules
477587 key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
@@ -510,7 +620,13 @@
510620
511621 vscode-package-extension:
512622 runs-on: ubuntu-latest
513- needs: [install-vscode, install-core, install-config-yaml]
623+ needs:
624+ [
625+ install-vscode,
626+ install-core,
627+ install-config-yaml,
628+ install-openai-adapters,
629+ ]
514630 steps:
515631 - uses: actions/checkout@v4
516632
@@ -536,11 +652,22 @@
536652 path: packages/config-yaml/node_modules
537653 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
538654
655+ - uses: actions/cache@v4
656+ id: openai-adapters-cache
657+ with:
658+ path: packages/openai-adapters/node_modules
659+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
660+
539661 - name: Build config-yaml
540662 run: |
541663 cd packages/config-yaml
542664 npm run build
543665
666+ - name: Build openai-adapters
667+ run: |
668+ cd packages/openai-adapters
669+ npm run build
670+
544671 - name: Package extension
545672 run: |
546673 cd extensions/vscode
@@ -554,7 +681,13 @@
554681
555682 vscode-download-e2e-dependencies:
556683 runs-on: ubuntu-latest
557- needs: [install-vscode, install-core, install-config-yaml]
684+ needs:
685+ [
686+ install-vscode,
687+ install-core,
688+ install-config-yaml,
689+ install-openai-adapters,
690+ ]
558691 steps:
559692 - uses: actions/checkout@v4
560693
@@ -607,6 +740,7 @@
607740 install-vscode,
608741 install-core,
609742 install-config-yaml,
743+ install-openai-adapters,
610744 ]
611745 runs-on: ubuntu-latest
612746 # Tests requiring secrets need approval from maintainers
@@ -653,11 +787,22 @@
653787 path: packages/config-yaml/node_modules
654788 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
655789
790+ - uses: actions/cache@v4
791+ id: openai-adapters-cache
792+ with:
793+ path: packages/openai-adapters/node_modules
794+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
795+
656796 - name: Build config-yaml
657797 run: |
658798 cd packages/config-yaml
659799 npm run build
660800
801+ - name: Build openai-adapters
802+ run: |
803+ cd packages/openai-adapters
804+ npm run build
805+
661806 - name: Fix VSCode binary permissions
662807 run: |
663808 chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
@@ -721,7 +866,8 @@
721866 path: extensions/vscode/e2e.log
722867
723868 gui-tests:
724- needs: [install-gui, install-core, install-config-yaml]
869+ needs:
870+ [install-gui, install-core, install-config-yaml, install-openai-adapters]
725871 runs-on: ubuntu-latest
726872 steps:
727873 - uses: actions/checkout@v4
@@ -747,11 +893,22 @@
747893 path: packages/config-yaml/node_modules
748894 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
749895
896+ - uses: actions/cache@v4
897+ id: openai-adapters-cache
898+ with:
899+ path: packages/openai-adapters/node_modules
900+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
901+
750902 - name: Build config-yaml
751903 run: |
752904 cd packages/config-yaml
753905 npm run build
754906
907+ - name: Build openai-adapters
908+ run: |
909+ cd packages/openai-adapters
910+ npm run build
911+
755912 - name: Install GUI dependencies
756913 if: steps.gui-cache.outputs.cache-hit != 'true'
757914 run: cd gui && npm ci
@@ -764,7 +921,8 @@
764921 npm test
765922
766923 jetbrains-tests:
767- needs: [install-root, core-checks, install-config-yaml]
924+ needs:
925+ [install-root, core-checks, install-config-yaml, install-openai-adapters]
768926 runs-on: ubuntu-latest
769927 steps:
770928 - uses: actions/checkout@v4
@@ -779,11 +937,22 @@
779937 path: packages/config-yaml/node_modules
780938 key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
781939
940+ - uses: actions/cache@v4
941+ id: openai-adapters-cache
942+ with:
943+ path: packages/openai-adapters/node_modules
944+ key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
945+
782946 - name: Build config-yaml
783947 run: |
784948 cd packages/config-yaml
785949 npm run build
786950
951+ - name: Build openai-adapters
952+ run: |
953+ cd packages/openai-adapters
954+ npm run build
955+
787956 - name: Setup Java
788957 uses: actions/setup-java@v4.5.0
789958 with:
@@ -898,6 +1067,7 @@
8981067 - jetbrains-tests
8991068 - config-yaml-checks
9001069 - install-config-yaml
1070+ - install-openai-adapters
9011071
9021072 steps:
9031073 - name: Decide whether the needed jobs succeeded or failed
modified .github/workflows/preview.yaml +8 −0
@@ -99,6 +99,14 @@
9999 path: gui/node_modules
100100 key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
101101
102+ - name: Build packages (Windows)
103+ run: ./scripts/build-packages.ps1
104+ if: matrix.os == 'windows-latest'
105+
106+ - name: Build packages (Unix)
107+ run: ./scripts/build-packages.sh
108+ if: matrix.os != 'windows-latest'
109+
102110 - name: Install extension Dependencies
103111 run: |
104112 cd extensions/vscode
modified .github/workflows/release-config-yaml.yml +7 −35
@@ -9,38 +9,10 @@
99
1010 jobs:
1111 release:
12- name: Release
13- runs-on: ubuntu-latest
14- steps:
15- - name: Checkout
16- uses: actions/checkout@v4
17- with:
18- fetch-depth: 0
19-
20- - name: Use Node.js from .nvmrc
21- uses: actions/setup-node@v4
22- with:
23- node-version-file: ".nvmrc"
24-
25- - name: Install dependencies
26- run: |
27- cd packages/config-yaml
28- npm ci
29-
30- - name: Build
31- run: |
32- cd packages/config-yaml
33- npm run build
34-
35- - name: Run tests
36- run: |
37- cd packages/config-yaml
38- npm test
39-
40- - name: Release
41- env:
42- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
43- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
44- run: |
45- cd packages/config-yaml
46- npx semantic-release
12+ uses: ./.github/workflows/reusable-release.yml
13+ with:
14+ package-name: "config-yaml"
15+ package-path: "packages/config-yaml"
16+ secrets:
17+ SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
18+ SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
added .github/workflows/release-fetch.yml +18 −0
@@ -0,0 +1,18 @@
1+name: Release @continuedev/fetch
2+
3+on:
4+ push:
5+ branches:
6+ - main
7+ paths:
8+ - "packages/fetch/**"
9+
10+jobs:
11+ release:
12+ uses: ./.github/workflows/reusable-release.yml
13+ with:
14+ package-name: "fetch"
15+ package-path: "packages/fetch"
16+ secrets:
17+ SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
18+ SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
added .github/workflows/release-llm-info.yml +18 −0
@@ -0,0 +1,18 @@
1+name: Release @continuedev/llm-info
2+
3+on:
4+ push:
5+ branches:
6+ - main
7+ paths:
8+ - "packages/llm-info/**"
9+
10+jobs:
11+ release:
12+ uses: ./.github/workflows/reusable-release.yml
13+ with:
14+ package-name: "llm-info"
15+ package-path: "packages/llm-info"
16+ secrets:
17+ SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
18+ SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
added .github/workflows/release-openai-adapters.yml +18 −0
@@ -0,0 +1,18 @@
1+name: Release @continuedev/openai-adapters
2+
3+on:
4+ push:
5+ branches:
6+ - main
7+ paths:
8+ - "packages/openai-adapters/**"
9+
10+jobs:
11+ release:
12+ uses: ./.github/workflows/reusable-release.yml
13+ with:
14+ package-name: "openai-adapters"
15+ package-path: "packages/openai-adapters"
16+ secrets:
17+ SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
18+ SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
added .github/workflows/reusable-release.yml +55 −0
@@ -0,0 +1,55 @@
1+name: Reusable Release Workflow
2+
3+on:
4+ workflow_call:
5+ inputs:
6+ package-name:
7+ required: true
8+ type: string
9+ package-path:
10+ required: true
11+ type: string
12+ secrets:
13+ SEMANTIC_RELEASE_GITHUB_TOKEN:
14+ required: true
15+ SEMANTIC_RELEASE_NPM_TOKEN:
16+ required: true
17+
18+permissions:
19+ contents: write
20+ issues: write
21+ pull-requests: write
22+
23+jobs:
24+ release:
25+ name: Release ${{ inputs.package-name }}
26+ runs-on: ubuntu-latest
27+ defaults:
28+ run:
29+ working-directory: ${{ inputs.package-path }}
30+ steps:
31+ - name: Checkout
32+ uses: actions/checkout@v4
33+ with:
34+ fetch-depth: 0
35+
36+ - name: Use Node.js from .nvmrc
37+ uses: actions/setup-node@v4
38+ with:
39+ node-version-file: ".nvmrc"
40+
41+ - name: Install dependencies
42+ run: npm ci
43+
44+ - name: Build
45+ run: npm run build
46+
47+ - name: Run tests
48+ run: npm test
49+
50+ - name: Release
51+ env:
52+ GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
53+ NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
54+ NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
55+ run: npx semantic-release
No newline at the end of the file
modified .gitignore +2 −1
@@ -67,8 +67,9 @@
6767 # Scrapy stuff:
6868 .scrapy
6969
70-# Sphinx documentation
70+# docusaurus
7171 docs/_build/
72+docs/.docusaurus
7273
7374 # PyBuilder
7475 target/
modified .vscode/launch.json +0 −26
@@ -73,32 +73,6 @@
7373 "sourceMaps": true
7474 // "preLaunchTask": "gui:dev"
7575 },
76- // Has to be run after starting the server (separately or using the compound configuration)
77- {
78- "name": "Run tests",
79- "type": "extensionHost",
80- "request": "launch",
81- "cwd": "${workspaceFolder}/extensions/vscode",
82- "runtimeExecutable": "${execPath}",
83- "args": [
84- // Pass a directory to run tests in
85- "${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
86- "--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode",
87- "--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner"
88- ],
89- "outFiles": [
90- // Allows setting breakpoints in test suites across the /src folder
91- "${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js",
92- // Allows setting breakpoints in mocha test runner file
93- "${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js"
94- ],
95- "internalConsoleOptions": "openOnSessionStart",
96- "preLaunchTask": "vscode-extension:tests:build",
97- "env": {
98- // Avoid timing out when stopping on breakpoints during debugging in VSCode
99- "MOCHA_TIMEOUT": "0"
100- }
101- },
10276 {
10377 "name": "[Core] Jest Test Debugger, Current Open File",
10478 "type": "node",
modified .vscode/tasks.json +3 −33
@@ -103,42 +103,12 @@
103103 "clear": true
104104 },
105105 "options": {
106+ "env": {
107+ "SKIP_INSTALLS": "true"
108+ },
106109 "cwd": "${workspaceFolder}/extensions/vscode"
107110 }
108111 },
109- //
110- // Compile and bundle tests
111- {
112- "label": "vscode-extension:tests:build",
113- "dependsOn": [
114- // Build the extension
115- "vscode-extension:build",
116- // To detect compile errors - this type checks both the extension and the tests
117- "tsc:watch",
118- "vscode-extension:tests:esbuild"
119- ]
120- },
121- {
122- "label": "vscode-extension:tests:esbuild",
123- "type": "npm",
124- "script": "build-test",
125- "path": "extensions/vscode",
126- "problemMatcher": [
127- {
128- "pattern": [
129- {
130- "regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
131- "file": 1,
132- "line": 2,
133- "column": 3,
134- "severity": 4,
135- "message": 5
136- }
137- ]
138- }
139- ]
140- },
141- //
142112 // Install or update all dependencies for all projects in the monrepo
143113 {
144114 "label": "install-all-dependencies",
modified README.md +4 −4
@@ -36,27 +36,27 @@
3636
3737 [Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
3838
39-![agent](docs/static/img/agent.gif)
39+![agent](docs/images/agent.gif)
4040
4141 ## Chat
4242
4343 [Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
4444 the IDE
4545
46-![chat](docs/static/img/chat.gif)
46+![chat](docs/images/chat.gif)
4747
4848 ## Autocomplete
4949
5050 [Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
5151
52-![autocomplete](docs/static/img/autocomplete.gif)
52+![autocomplete](docs/images/autocomplete.gif)
5353
5454 ## Edit
5555
5656 [Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
5757 file
5858
59-![edit](docs/static/img/edit.gif)
59+![edit](docs/images/edit.gif)
6060
6161 </div>
6262
modified binary/.gitignore +1 −0
@@ -3,3 +3,4 @@
33 data
44 out
55 tmp
6+tree-sitter
modified binary/build.js +46 −144
@@ -3,13 +3,13 @@
33 const path = require("path");
44 const ncp = require("ncp").ncp;
55 const { rimrafSync } = require("rimraf");
6-const {
7- validateFilesPresent,
8- execCmdSync,
9- autodetectPlatformAndArch,
10-} = require("../scripts/util");
11-const { downloadRipgrep } = require("./utils/ripgrep");
6+const { validateFilesPresent } = require("../scripts/util");
127 const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
8+const { fork } = require("child_process");
9+const {
10+ installAndCopyNodeModules,
11+} = require("../extensions/vscode/scripts/install-copy-nodemodule");
12+const { bundleBinary } = require("./utils/bundle-binary");
1313
1414 const bin = path.join(__dirname, "bin");
1515 const out = path.join(__dirname, "out");
@@ -21,6 +21,7 @@
2121 rimrafSync(out);
2222 rimrafSync(build);
2323 rimrafSync(path.join(__dirname, "tmp"));
24+ rimrafSync(path.join(__dirname, "tree-sitter"));
2425 fs.mkdirSync(bin);
2526 fs.mkdirSync(out);
2627 fs.mkdirSync(build);
@@ -29,8 +30,6 @@
2930 const esbuildOutputFile = "out/index.js";
3031 let targets = [...ALL_TARGETS];
3132
32-const [currentPlatform, currentArch] = autodetectPlatformAndArch();
33-
3433 const assetBackups = [
3534 "node_modules/win-ca/lib/crypt32-ia32.node.bak",
3635 "node_modules/win-ca/lib/crypt32-x64.node.bak",
@@ -78,85 +77,6 @@
7877 });
7978 }
8079
81-async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
82- console.log(`Copying ${packageName} to ${toCopy}`);
83- // This is a way to install only one package without npm trying to install all the dependencies
84- // Create a temporary directory for installing the package
85- const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
86- const tempDir = path.join(
87- __dirname,
88- "tmp",
89- `continue-node_modules-${adjustedName}`,
90- );
91- const currentDir = process.cwd();
92-
93- // // Remove the dir we will be copying to
94- // rimrafSync(`node_modules/${toCopy}`);
95-
96- // // Ensure the temporary directory exists
97- fs.mkdirSync(tempDir, { recursive: true });
98-
99- try {
100- // Move to the temporary directory
101- process.chdir(tempDir);
102-
103- // Initialize a new package.json and install the package
104- execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
105-
106- console.log(
107- `Contents of: ${packageName}`,
108- fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
109- );
110-
111- // Without this it seems the file isn't completely written to disk
112- await new Promise((resolve) => setTimeout(resolve, 2000));
113-
114- // Copy the installed package back to the current directory
115- await new Promise((resolve, reject) => {
116- ncp(
117- path.join(tempDir, "node_modules", toCopy),
118- path.join(currentDir, "node_modules", toCopy),
119- { dereference: true },
120- (error) => {
121- if (error) {
122- console.error(
123- `[error] Error copying ${packageName} package`,
124- error,
125- );
126- reject(error);
127- } else {
128- resolve();
129- }
130- },
131- );
132- });
133- } finally {
134- // Clean up the temporary directory
135- // rimrafSync(tempDir);
136-
137- // Return to the original directory
138- process.chdir(currentDir);
139- }
140-}
141-
142-/**
143- * Downloads and installs ripgrep binaries for the specified target
144- *
145- * @param {string} target - Target platform-arch (e.g., 'darwin-x64')
146- * @param {string} targetDir - Directory to install ripgrep to
147- * @returns {Promise<void>}
148- */
149-async function downloadRipgrepForTarget(target, targetDir) {
150- console.log(`[info] Downloading ripgrep for ${target}...`);
151- try {
152- await downloadRipgrep(target, targetDir);
153- console.log(`[info] Successfully installed ripgrep for ${target}`);
154- } catch (error) {
155- console.error(`[error] Failed to download ripgrep for ${target}:`, error);
156- throw error;
157- }
158-}
159-
16080 (async () => {
16181 if (esbuildOnly) {
16282 await buildWithEsbuild();
@@ -181,16 +101,21 @@
181101 ),
182102 );
183103
184- console.log("[info] Downloading prebuilt lancedb...");
104+ const copyLanceDBPromises = [];
185105 for (const target of targets) {
186- if (TARGET_TO_LANCEDB[target]) {
187- console.log(`[info] Downloading for ${target}...`);
188- await installNodeModuleInTempDirAndCopyToCurrent(
189- TARGET_TO_LANCEDB[target],
190- "@lancedb",
191- );
106+ if (!TARGET_TO_LANCEDB[target]) {
107+ continue;
192108 }
109+ console.log(`[info] Downloading for ${target}...`);
110+ copyLanceDBPromises.push(
111+ installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb"),
112+ );
193113 }
114+ await Promise.all(copyLanceDBPromises).catch(() => {
115+ console.error("[error] Failed to copy LanceDB");
116+ process.exit(1);
117+ });
118+ console.log("[info] Copied all LanceDB");
194119
195120 // tree-sitter-wasm
196121 const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms");
@@ -218,6 +143,25 @@
218143 );
219144 });
220145
146+ // copy tree-sitter colder to binary folder to make it available when running in intellij debug mode
147+ const treeSitterDir = path.join(__dirname, "tree-sitter");
148+ fs.mkdirSync(treeSitterDir);
149+ await new Promise((resolve, reject) => {
150+ ncp(
151+ path.join(__dirname, "..", "extensions", "vscode", "tree-sitter"),
152+ treeSitterDir,
153+ { dereference: true },
154+ (error) => {
155+ if (error) {
156+ console.warn("[error] Error copying tree-sitter files", error);
157+ reject(error);
158+ } else {
159+ resolve();
160+ }
161+ },
162+ );
163+ });
164+
221165 const filesToCopy = [
222166 "../core/vendor/tree-sitter.wasm",
223167 "../core/llm/llamaTokenizerWorkerPool.mjs",
@@ -252,59 +196,16 @@
252196 "out/llamaTokenizerWorkerPool.mjs",
253197 );
254198
199+ const buildBinaryPromises = [];
255200 console.log("[info] Building binaries with pkg...");
256201 for (const target of targets) {
257- const targetDir = `bin/${target}`;
258- fs.mkdirSync(targetDir, { recursive: true });
259- console.log(`[info] Building ${target}...`);
260- execCmdSync(
261- `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
262- );
263-
264- // Download and unzip prebuilt sqlite3 binary for the target
265- console.log("[info] Downloading node-sqlite3");
266-
267- const downloadUrl =
268- // node-sqlite3 doesn't have a pre-built binary for win32-arm64
269- target === "win32-arm64"
270- ? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
271- : `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
272- target
273- }.tar.gz`;
274-
275- execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
276- execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
277-
278- // Copy to build directory for testing
279- try {
280- const [platform, arch] = target.split("-");
281- if (platform === currentPlatform && arch === currentArch) {
282- fs.copyFileSync(
283- `${targetDir}/build/Release/node_sqlite3.node`,
284- `build/node_sqlite3.node`,
285- );
286- }
287- } catch (error) {
288- console.log("[warn] Could not copy node_sqlite to build");
289- console.log(error);
290- }
291-
292- fs.unlinkSync(`${targetDir}/build.tar.gz`);
293-
294- // copy @lancedb to bin folders
295- console.log("[info] Copying @lancedb files to bin");
296- fs.copyFileSync(
297- `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
298- `${targetDir}/index.node`,
299- );
300-
301- // Download and install ripgrep for the target
302- await downloadRipgrepForTarget(target, targetDir);
303-
304- // Informs the `continue-binary` of where to look for node_sqlite3.node
305- // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
306- fs.writeFileSync(`${targetDir}/package.json`, "");
202+ buildBinaryPromises.push(bundleBinary(target));
307203 }
204+ await Promise.all(buildBinaryPromises).catch(() => {
205+ console.error("[error] Failed to build binaries");
206+ process.exit(1);
207+ });
208+ console.log("[info] All binaries built");
308209
309210 // Cleanup - this is needed when running locally
310211 fs.rmSync("out/package.json");
@@ -331,4 +232,5 @@
331232 validateFilesPresent(pathsToVerify);
332233
333234 console.log("[info] Done!");
235+ process.exit(0);
334236 })();
modified binary/package-lock.json +15 −2
@@ -20,6 +20,7 @@
2020 "posthog-node": "^3.6.3",
2121 "system-ca": "^1.0.2",
2222 "tar": "^7.4.3",
23+ "undici": "^7.10.0",
2324 "uuid": "^9.0.1",
2425 "vectordb": "^0.4.20",
2526 "win-ca": "^3.5.1"
@@ -52,9 +53,9 @@
5253 "@aws-sdk/credential-providers": "^3.778.0",
5354 "@continuedev/config-types": "^1.0.13",
5455 "@continuedev/config-yaml": "file:../packages/config-yaml",
55- "@continuedev/fetch": "^1.0.13",
56+ "@continuedev/fetch": "^1.0.14",
5657 "@continuedev/llm-info": "^1.0.8",
57- "@continuedev/openai-adapters": "^1.0.25",
58+ "@continuedev/openai-adapters": "file:../packages/openai-adapters",
5859 "@modelcontextprotocol/sdk": "^1.12.0",
5960 "@mozilla/readability": "^0.5.0",
6061 "@octokit/rest": "^20.1.1",
@@ -120,6 +121,8 @@
120121 "@babel/preset-env": "^7.24.7",
121122 "@biomejs/biome": "1.6.4",
122123 "@google/generative-ai": "^0.11.4",
124+ "@shikijs/colorized-brackets": "^3.7.0",
125+ "@shikijs/transformers": "^3.7.0",
123126 "@types/diff": "^7.0.1",
124127 "@types/follow-redirects": "^1.14.4",
125128 "@types/jest": "^29.5.12",
@@ -143,6 +146,7 @@
143146 "myers-diff": "^2.1.0",
144147 "onnxruntime-common": "1.14.0",
145148 "onnxruntime-web": "1.14.0",
149+ "shiki": "^3.6.0",
146150 "ts-jest": "^29.1.1",
147151 "typescript": "^5.6.3",
148152 "vitest": "^3.1.4"
@@ -6774,6 +6778,15 @@
67746778 "node": ">=8"
67756779 }
67766780 },
6781+ "node_modules/undici": {
6782+ "version": "7.10.0",
6783+ "resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz",
6784+ "integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==",
6785+ "license": "MIT",
6786+ "engines": {
6787+ "node": ">=20.18.1"
6788+ }
6789+ },
67776790 "node_modules/universal-user-agent": {
67786791 "version": "6.0.1",
67796792 "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz",
modified binary/package.json +1 −0
@@ -53,6 +53,7 @@
5353 "posthog-node": "^3.6.3",
5454 "system-ca": "^1.0.2",
5555 "tar": "^7.4.3",
56+ "undici": "^7.10.0",
5657 "uuid": "^9.0.1",
5758 "vectordb": "^0.4.20",
5859 "win-ca": "^3.5.1"
modified binary/pkgJson/darwin-arm64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../out/llamaTokenizer.mjs",
1516 "../../out/llamaTokenizerWorkerPool.mjs",
1617 "../../out/tiktokenWorkerPool.mjs",
modified binary/pkgJson/darwin-x64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../out/llamaTokenizer.mjs",
1516 "../../out/llamaTokenizerWorkerPool.mjs",
1617 "../../out/tiktokenWorkerPool.mjs",
modified binary/pkgJson/linux-arm64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../out/llamaTokenizer.mjs",
1516 "../../out/llamaTokenizerWorkerPool.mjs",
1617 "../../out/tiktokenWorkerPool.mjs",
modified binary/pkgJson/linux-x64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../out/llamaTokenizer.mjs",
1516 "../../out/llamaTokenizerWorkerPool.mjs",
1617 "../../out/tiktokenWorkerPool.mjs",
modified binary/pkgJson/win32-arm64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../node_modules/win-ca/lib/crypt32-ia32.node",
1516 "../../node_modules/win-ca/lib/crypt32-x64.node",
1617 "../../node_modules/win-ca/lib/roots.exe",
modified binary/pkgJson/win32-x64/package.json +1 −0
@@ -11,6 +11,7 @@
1111 "../../../core/node_modules/sqlite3/**/*",
1212 "../../out/tree-sitter.wasm",
1313 "../../out/tree-sitter-wasms/*",
14+ "../../tree-sitter/**/*",
1415 "../../node_modules/win-ca/lib/crypt32-ia32.node",
1516 "../../node_modules/win-ca/lib/crypt32-x64.node",
1617 "../../node_modules/win-ca/lib/roots.exe",
added binary/utils/bundle-binary.js +103 −0
@@ -0,0 +1,103 @@
1+/**
2+ * @file Builds the binary for the specified target. It is also intended to run as a child process.
3+ */
4+
5+const {
6+ execCmdSync,
7+ autodetectPlatformAndArch,
8+} = require("../../scripts/util");
9+const { downloadRipgrep } = require("./ripgrep");
10+const { TARGET_TO_LANCEDB } = require("../utils/targets");
11+const fs = require("fs");
12+const {
13+ downloadSqlite,
14+} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild");
15+const { fork } = require("child_process");
16+
17+async function downloadNodeSqlite(target, targetDir) {
18+ const [currentPlatform, currentArch] = autodetectPlatformAndArch();
19+
20+ // Download and unzip prebuilt sqlite3 binary for the target
21+ console.log("[info] Downloading node-sqlite3");
22+
23+ await downloadSqlite(target, `${targetDir}/build.tar.gz`);
24+
25+ execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
26+
27+ // Copy to build directory for testing
28+ try {
29+ const [platform, arch] = target.split("-");
30+ if (platform === currentPlatform && arch === currentArch) {
31+ fs.copyFileSync(
32+ `${targetDir}/build/Release/node_sqlite3.node`,
33+ `build/node_sqlite3.node`,
34+ );
35+ }
36+ } catch (error) {
37+ console.log("[warn] Could not copy node_sqlite to build");
38+ console.log(error);
39+ }
40+ fs.unlinkSync(`${targetDir}/build.tar.gz`);
41+}
42+
43+/**
44+ * @param {string} target the platform to build for
45+ */
46+async function bundleForBinary(target) {
47+ const targetDir = `bin/${target}`;
48+ fs.mkdirSync(targetDir, { recursive: true });
49+ console.log(`[info] Building ${target}...`);
50+ execCmdSync(
51+ `npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
52+ );
53+
54+ // copy @lancedb to bin folders
55+ console.log("[info] Copying @lancedb files to bin");
56+ fs.copyFileSync(
57+ `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
58+ `${targetDir}/index.node`,
59+ );
60+
61+ const downloadPromises = [];
62+ downloadPromises.push(downloadRipgrep(target, targetDir));
63+ downloadPromises.push(downloadNodeSqlite(target, targetDir));
64+ await Promise.all(downloadPromises);
65+
66+ // Informs the `continue-binary` of where to look for node_sqlite3.node
67+ // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
68+ fs.writeFileSync(`${targetDir}/package.json`, "");
69+}
70+
71+process.on("message", (msg) => {
72+ bundleForBinary(msg.payload.target)
73+ .then(() => process.send({ done: true }))
74+ .catch((error) => {
75+ console.error(error); // show the error in the parent process
76+ process.send({ error: true });
77+ });
78+});
79+
80+/**
81+ * @param {string} target the platform to bundle for
82+ */
83+async function bundleBinary(target) {
84+ const child = fork(__filename, { stdio: "inherit" });
85+ child.send({
86+ payload: {
87+ target,
88+ },
89+ });
90+ return new Promise((resolve, reject) => {
91+ child.on("message", (msg) => {
92+ if (msg.error) {
93+ reject();
94+ } else {
95+ resolve();
96+ }
97+ });
98+ });
99+}
100+
101+module.exports = {
102+ bundleBinary,
103+};
modified binary/utils/ripgrep.js +6 −0
@@ -4,6 +4,7 @@
44 const tar = require("tar");
55 const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets");
66 const AdmZip = require("adm-zip");
7+const { ProxyAgent } = require("undici");
78
89 const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`;
910
@@ -16,8 +17,13 @@
1617 */
1718 async function downloadFile(url, destPath) {
1819 // Use the built-in fetch API instead of node-fetch
20+ // Use proxy if set in environment variables
21+ const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
22+ const agent = proxy ? new ProxyAgent(proxy) : undefined;
23+
1924 const response = await fetch(url, {
2025 redirect: "follow", // Automatically follow redirects
26+ dispatcher: agent,
2127 });
2228
2329 if (!response.ok) {
modified core/autocomplete/CompletionProvider.ts +1 −1
@@ -254,7 +254,7 @@
254254 completionId: helper.input.completionId,
255255 gitRepo: await this.ide.getRepoName(helper.filepath),
256256 uniqueId: await this.ide.getUniqueId(),
257- timestamp: Date.now(),
257+ timestamp: new Date().toISOString(),
258258 ...helper.options,
259259 };
260260
modified core/autocomplete/constants/AutocompleteLanguageInfo.ts +33 −1
@@ -6,12 +6,36 @@
66 } from "../filtering/streamTransforms/lineStream";
77
88 export interface AutocompleteLanguageInfo {
9+ /**
10+ * The display name of the language
11+ */
912 name: string;
13+ /**
14+ * Keywords that show up at the top-level of files. We often use these as stop words or soft breaks
15+ */
1016 topLevelKeywords: string[];
17+ /**
18+ * The character that prefixes a single line comment
19+ * We use this to format snippets from other files as large comment blocks
20+ */
1121 singleLineComment?: string;
22+ /**
23+ * Semi-colon or other end of line indicator that may be used as a stop char
24+ * or other parsing
25+ */
1226 endOfLine: string[];
27+ /**
28+ * Strings that indicate we should filter out a line from completion
29+ * Primarily currently used for .ipynb files
30+ */
1331 lineFilters?: LineFilter[];
32+ /**
33+ * Similar to line filters, but characters. I think.
34+ */
1435 charFilters?: CharacterFilter[];
36+ /**
37+ * Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis
38+ */
1539 useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
1640 }
1741
@@ -23,6 +47,14 @@
2347 endOfLine: [";"],
2448 };
2549
50+// JavaScript
51+export const JavaScript = {
52+ name: "JavaScript",
53+ topLevelKeywords: ["function", "class", "module", "export", "import"],
54+ singleLineComment: "//",
55+ endOfLine: [";"],
56+};
57+
2658 // Python
2759 export const Python = {
2860 name: "Python",
@@ -336,7 +368,7 @@
336368
337369 export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
338370 ts: Typescript,
339- js: Typescript,
371+ js: JavaScript,
340372 tsx: Typescript,
341373 json: Json,
342374 jsx: Typescript,
modified core/autocomplete/context/ContextRetrievalService.ts +16 −0
@@ -70,4 +70,20 @@
7070 helper.treePath,
7171 );
7272 }
73+
74+ /**
75+ * Initialize the import definitions cache for a file.
76+ * This is normally done automatically when the active text editor changes,
77+ * but needs to be called manually when using context fetching outside the normal flow.
78+ */
79+ public async initializeForFile(filepath: string): Promise<void> {
80+ try {
81+ await (this.importDefinitionsService as any).cache.initKey(filepath);
82+ } catch (e) {
83+ console.warn(
84+ `Failed to initialize import definitions cache for ${filepath}:`,
85+ e,
86+ );
87+ }
88+ }
7389 }
deleted core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +0 −56
@@ -1,56 +0,0 @@
1-import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
2-import { testRootPathContext } from "./testUtils";
3-
4-const TEST_CASES = [
5- ...PYTHON_TEST_CASES,
6- ...TYPESCRIPT_TEST_CASES,
7- {
8- nodeType: "function_definition",
9- fileName: "file1.php",
10- language: "PHP",
11- cursorPosition: { line: 12, character: 32 },
12- definitionPositions: [
13- { row: 10, column: 26 }, // Person
14- { row: 10, column: 44 }, // Address
15- ],
16- },
17- {
18- nodeType: "method_declaration",
19- fileName: "file1.php",
20- language: "PHP",
21- cursorPosition: { line: 26, character: 35 },
22- definitionPositions: [
23- { row: 15, column: 29 }, // BaseClass
24- { row: 15, column: 55 }, // FirstInterface
25- { row: 15, column: 72 }, // SecondInterface
26- { row: 25, column: 43 }, // Person
27- { row: 25, column: 61 }, // Address
28- ],
29- },
30- {
31- nodeType: "function_declaration",
32- fileName: "file1.go",
33- language: "Go",
34- cursorPosition: { line: 7, character: 21 },
35- definitionPositions: [
36- { row: 6, column: 33 }, // models.User
37- { row: 6, column: 50 }, // models.Address
38- ],
39- },
40-];
41-
42-describe("RootPathContextService", () => {
43- describe("should look for correct type definitions", () => {
44- test.each(TEST_CASES)(
45- "$language: $nodeType",
46- async ({ fileName, cursorPosition, definitionPositions }) => {
47- await testRootPathContext(
48- "files",
49- fileName,
50- cursorPosition,
51- definitionPositions,
52- );
53- },
54- );
55- });
56-});
added core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts +57 −0
@@ -0,0 +1,57 @@
1+import { describe, test } from "vitest";
2+import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
3+import { testRootPathContext } from "./testUtils";
4+
5+const TEST_CASES = [
6+ ...PYTHON_TEST_CASES,
7+ ...TYPESCRIPT_TEST_CASES,
8+ {
9+ nodeType: "function_definition",
10+ fileName: "file1.php",
11+ language: "PHP",
12+ cursorPosition: { line: 12, character: 32 },
13+ definitionPositions: [
14+ { row: 10, column: 26 }, // Person
15+ { row: 10, column: 44 }, // Address
16+ ],
17+ },
18+ {
19+ nodeType: "method_declaration",
20+ fileName: "file1.php",
21+ language: "PHP",
22+ cursorPosition: { line: 26, character: 35 },
23+ definitionPositions: [
24+ { row: 15, column: 29 }, // BaseClass
25+ { row: 15, column: 55 }, // FirstInterface
26+ { row: 15, column: 72 }, // SecondInterface
27+ { row: 25, column: 43 }, // Person
28+ { row: 25, column: 61 }, // Address
29+ ],
30+ },
31+ {
32+ nodeType: "function_declaration",
33+ fileName: "file1.go",
34+ language: "Go",
35+ cursorPosition: { line: 7, character: 21 },
36+ definitionPositions: [
37+ { row: 6, column: 33 }, // models.User
38+ { row: 6, column: 50 }, // models.Address
39+ ],
40+ },
41+];
42+
43+describe("RootPathContextService", () => {
44+ describe("should look for correct type definitions", () => {
45+ test.each(TEST_CASES)(
46+ "$language: $nodeType",
47+ async ({ fileName, cursorPosition, definitionPositions }) => {
48+ await testRootPathContext(
49+ "files",
50+ fileName,
51+ cursorPosition,
52+ definitionPositions,
53+ );
54+ },
55+ );
56+ });
57+});
modified core/autocomplete/context/root-path-context/test/testUtils.ts +4 −4
@@ -1,6 +1,6 @@
1-import { jest } from "@jest/globals";
21 import fs from "fs";
32 import path from "path";
3+import { expect, vi } from "vitest";
44
55 import Parser from "web-tree-sitter";
66 import { Position } from "../../../..";
@@ -36,17 +36,17 @@
3636 const importDefinitionsService = new ImportDefinitionsService(ide);
3737 const service = new RootPathContextService(importDefinitionsService, ide);
3838
39- const getSnippetsMock = jest
39+ const getSnippetsMock = vi
4040 // @ts-ignore
4141 .spyOn(service, "getSnippets")
4242 // @ts-ignore
43- .mockImplementation(async (_filepath, _endPosition) => {
43+ .mockImplementation((_filePath, _endPosition) => {
4444 return [];
4545 });
4646
4747 // Copy the folder to the test directory
4848 const folderPath = path.join(
49- __dirname,
49+ process.cwd(),
5050 "autocomplete",
5151 "context",
5252 "root-path-context",
deleted core/autocomplete/filtering/streamTransforms/charStream.test.ts +0 −215
@@ -1,215 +0,0 @@
1-import { stopAtStartOf, stopAtStopTokens } from "./charStream";
2-
3-async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
4- for (const chunk of chunks) {
5- yield chunk;
6- }
7-}
8-
9-async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
10- let result = "";
11- for await (const chunk of stream) {
12- result += chunk;
13- }
14- return result;
15-}
16-
17-describe("stopAtStopTokens", () => {
18- it("should yield characters until a stop token is encountered", async () => {
19- const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
20- const stopTokens = ["Stop"];
21- const result = stopAtStopTokens(mockStream, stopTokens);
22-
23- const output = [];
24- for await (const char of result) {
25- output.push(char);
26- }
27-
28- expect(output.join("")).toBe("Hello world! ");
29- });
30-
31- it("should handle multiple stop tokens", async () => {
32- const mockStream = createMockStream([
33- "This",
34- " is a ",
35- "test. END",
36- " of stream",
37- ]);
38- const stopTokens = ["END", "STOP", "HALT"];
39- const result = stopAtStopTokens(mockStream, stopTokens);
40-
41- expect(await streamToString(result)).toBe("This is a test. ");
42- });
43-
44- it("should handle stop tokens split across chunks", async () => {
45- const mockStream = createMockStream([
46- "Hello",
47- " wo",
48- "r",
49- "ld! ST",
50- "OP now",
51- ]);
52- const stopTokens = ["STOP"];
53- const result = stopAtStopTokens(mockStream, stopTokens);
54-
55- const output = [];
56- for await (const char of result) {
57- output.push(char);
58- }
59-
60- expect(output.join("")).toBe("Hello world! ");
61- });
62-
63- it("should yield all characters if no stop token is encountered", async () => {
64- const mockStream = createMockStream([
65- "This",
66- " is ",
67- "a complete",
68- " stream",
69- ]);
70- const stopTokens = ["END"];
71- const result = stopAtStopTokens(mockStream, stopTokens);
72-
73- expect(await streamToString(result)).toBe("This is a complete stream");
74- });
75-
76- it("should handle empty chunks", async () => {
77- const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
78- const stopTokens = ["STOP"];
79- const result = stopAtStopTokens(mockStream, stopTokens);
80-
81- expect(await streamToString(result)).toBe("Hello world! ");
82- });
83-
84- it("should handle stop token at the beginning of the stream", async () => {
85- const mockStream = createMockStream(["STOP", "Hello world"]);
86- const stopTokens = ["STOP"];
87- const result = stopAtStopTokens(mockStream, stopTokens);
88-
89- const output = [];
90- for await (const char of result) {
91- output.push(char);
92- }
93-
94- expect(output.join("")).toBe("");
95- });
96-
97- it("should handle stop token at the end of the stream", async () => {
98- const mockStream = createMockStream(["Hello world", "STOP"]);
99- const stopTokens = ["STOP"];
100- const result = stopAtStopTokens(mockStream, stopTokens);
101-
102- expect(await streamToString(result)).toBe("Hello world");
103- });
104-
105- it("should handle multiple stop tokens of different lengths", async () => {
106- const mockStream = createMockStream([
107- "This is a ",
108- "test with ",
109- "multiple STOP",
110- " tokens END",
111- ]);
112- const stopTokens = ["STOP", "END", "HALT"];
113- const result = stopAtStopTokens(mockStream, stopTokens);
114-
115- expect(await streamToString(result)).toBe("This is a test with multiple ");
116- });
117-
118- it("should handle an empty stream", async () => {
119- const mockStream = createMockStream([]);
120- const stopTokens = ["STOP"];
121- const result = stopAtStopTokens(mockStream, stopTokens);
122-
123- expect(await streamToString(result)).toBe("");
124- });
125-
126- it("should handle an empty stop tokens array", async () => {
127- const mockStream = createMockStream(["Hello", " world!"]);
128- const stopTokens: string[] = [];
129- const result = stopAtStopTokens(mockStream, stopTokens);
130-
131- const output = [];
132- for await (const char of result) {
133- output.push(char);
134- }
135-
136- expect(output.join("")).toBe("Hello world!");
137- });
138-
139- it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => {
140- const mockStream = createMockStream(["Hello world!STOP"]);
141- const stopTokens: string[] = [
142- "STOP",
143- "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER",
144- ];
145- const result = stopAtStopTokens(mockStream, stopTokens);
146-
147- expect(await streamToString(result)).toBe("Hello world!");
148- });
149-});
150-
151-describe("stopAtStartOf", () => {
152- const sampleCode = ` {
153- method: "GET",
154- headers: {
155- "Content-Type": "application/json",
156- Authorization: \`Bearer \${this.workOsAccessToken}\`,
157- },
158- },
159- );
160- const data = await response.json();
161- return data.items;
162- }
163-
164- async getContextItems(
165- query: string,
166- extras: ContextProviderExtras,
167- ): Promise<ContextItem[]> {
168- const response = await extras.fetch(
169- new URL(
170- \`/proxy/context/\${this.options.id}/retrieve\`,
171- controlPlaneEnv.CONTROL_PLANE_URL,
172- ),
173-`;
174-
175- /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
176-and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
177- it("should stop if the start of the suffix is reached", async () => {
178- const suffix = `
179- const data = await response.json();
180- return data.items;
181-}`;
182- const mockStream = createMockStream(sampleCode.split(/(?! )/g));
183- const result = stopAtStartOf(mockStream, suffix);
184-
185- const resultStr = await streamToString(result);
186- expect(resultStr).toBe(` {
187- method: "GET",
188- headers: {
189- "Content-Type": "application/json",
190- Authorization: \`Bearer \${this.workOsAccessToken}\`,
191- },
192- },
193- );
194- `);
195- });
196- it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
197- const suffix = `
198- xxxconst data = await response.json();
199- return data.items;
200-}`;
201- const mockStream = createMockStream(sampleCode.split(/(?! )/g));
202- const result = stopAtStartOf(mockStream, suffix);
203-
204- const resultStr = await streamToString(result);
205- expect(resultStr).toBe(` {
206- method: "GET",
207- headers: {
208- "Content-Type": "application/json",
209- Authorization: \`Bearer \${this.workOsAccessToken}\`,
210- },
211- },
212- );
213- `);
214- });
215-});
added core/autocomplete/filtering/streamTransforms/charStream.vitest.ts +216 −0
@@ -0,0 +1,216 @@
1+import { describe, expect, it } from "vitest";
2+import { stopAtStartOf, stopAtStopTokens } from "./charStream";
3+
4+async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
5+ for (const chunk of chunks) {
6+ yield chunk;
7+ }
8+}
9+
10+async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
11+ let result = "";
12+ for await (const chunk of stream) {
13+ result += chunk;
14+ }
15+ return result;
16+}
17+
18+describe("stopAtStopTokens", () => {
19+ it("should yield characters until a stop token is encountered", async () => {
20+ const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
21+ const stopTokens = ["Stop"];
22+ const result = stopAtStopTokens(mockStream, stopTokens);
23+
24+ const output = [];
25+ for await (const char of result) {
26+ output.push(char);
27+ }
28+
29+ expect(output.join("")).toBe("Hello world! ");
30+ });
31+
32+ it("should handle multiple stop tokens", async () => {
33+ const mockStream = createMockStream([
34+ "This",
35+ " is a ",
36+ "test. END",
37+ " of stream",
38+ ]);
39+ const stopTokens = ["END", "STOP", "HALT"];
40+ const result = stopAtStopTokens(mockStream, stopTokens);
41+
42+ expect(await streamToString(result)).toBe("This is a test. ");
43+ });
44+
45+ it("should handle stop tokens split across chunks", async () => {
46+ const mockStream = createMockStream([
47+ "Hello",
48+ " wo",
49+ "r",
50+ "ld! ST",
51+ "OP now",
52+ ]);
53+ const stopTokens = ["STOP"];
54+ const result = stopAtStopTokens(mockStream, stopTokens);
55+
56+ const output = [];
57+ for await (const char of result) {
58+ output.push(char);
59+ }
60+
61+ expect(output.join("")).toBe("Hello world! ");
62+ });
63+
64+ it("should yield all characters if no stop token is encountered", async () => {
65+ const mockStream = createMockStream([
66+ "This",
67+ " is ",
68+ "a complete",
69+ " stream",
70+ ]);
71+ const stopTokens = ["END"];
72+ const result = stopAtStopTokens(mockStream, stopTokens);
73+
74+ expect(await streamToString(result)).toBe("This is a complete stream");
75+ });
76+
77+ it("should handle empty chunks", async () => {
78+ const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
79+ const stopTokens = ["STOP"];
80+ const result = stopAtStopTokens(mockStream, stopTokens);
81+
82+ expect(await streamToString(result)).toBe("Hello world! ");
83+ });
84+
85+ it("should handle stop token at the beginning of the stream", async () => {
86+ const mockStream = createMockStream(["STOP", "Hello world"]);
87+ const stopTokens = ["STOP"];
88+ const result = stopAtStopTokens(mockStream, stopTokens);
89+
90+ const output = [];
91+ for await (const char of result) {
92+ output.push(char);
93+ }
94+
95+ expect(output.join("")).toBe("");
96+ });
97+
98+ it("should handle stop token at the end of the stream", async () => {
99+ const mockStream = createMockStream(["Hello world", "STOP"]);
100+ const stopTokens = ["STOP"];
101+ const result = stopAtStopTokens(mockStream, stopTokens);
102+
103+ expect(await streamToString(result)).toBe("Hello world");
104+ });
105+
106+ it("should handle multiple stop tokens of different lengths", async () => {
107+ const mockStream = createMockStream([
108+ "This is a ",
109+ "test with ",
110+ "multiple STOP",
111+ " tokens END",
112+ ]);
113+ const stopTokens = ["STOP", "END", "HALT"];
114+ const result = stopAtStopTokens(mockStream, stopTokens);
115+
116+ expect(await streamToString(result)).toBe("This is a test with multiple ");
117+ });
118+
119+ it("should handle an empty stream", async () => {
120+ const mockStream = createMockStream([]);
121+ const stopTokens = ["STOP"];
122+ const result = stopAtStopTokens(mockStream, stopTokens);
123+
124+ expect(await streamToString(result)).toBe("");
125+ });
126+
127+ it("should handle an empty stop tokens array", async () => {
128+ const mockStream = createMockStream(["Hello", " world!"]);
129+ const stopTokens: string[] = [];
130+ const result = stopAtStopTokens(mockStream, stopTokens);
131+
132+ const output = [];
133+ for await (const char of result) {
134+ output.push(char);
135+ }
136+
137+ expect(output.join("")).toBe("Hello world!");
138+ });
139+
140+ it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => {
141+ const mockStream = createMockStream(["Hello world!STOP"]);
142+ const stopTokens: string[] = [
143+ "STOP",
144+ "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER",
145+ ];
146+ const result = stopAtStopTokens(mockStream, stopTokens);
147+
148+ expect(await streamToString(result)).toBe("Hello world!");
149+ });
150+});
151+
152+describe("stopAtStartOf", () => {
153+ const sampleCode = ` {
154+ method: "GET",
155+ headers: {
156+ "Content-Type": "application/json",
157+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
158+ },
159+ },
160+ );
161+ const data = await response.json();
162+ return data.items;
163+ }
164+
165+ async getContextItems(
166+ query: string,
167+ extras: ContextProviderExtras,
168+ ): Promise<ContextItem[]> {
169+ const response = await extras.fetch(
170+ new URL(
171+ \`/proxy/context/\${this.options.id}/retrieve\`,
172+ controlPlaneEnv.CONTROL_PLANE_URL,
173+ ),
174+`;
175+
176+ /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
177+and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
178+ it("should stop if the start of the suffix is reached", async () => {
179+ const suffix = `
180+ const data = await response.json();
181+ return data.items;
182+}`;
183+ const mockStream = createMockStream(sampleCode.split(/(?! )/g));
184+ const result = stopAtStartOf(mockStream, suffix);
185+
186+ const resultStr = await streamToString(result);
187+ expect(resultStr).toBe(` {
188+ method: "GET",
189+ headers: {
190+ "Content-Type": "application/json",
191+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
192+ },
193+ },
194+ );
195+ `);
196+ });
197+ it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
198+ const suffix = `
199+ xxxconst data = await response.json();
200+ return data.items;
201+}`;
202+ const mockStream = createMockStream(sampleCode.split(/(?! )/g));
203+ const result = stopAtStartOf(mockStream, suffix);
204+
205+ const resultStr = await streamToString(result);
206+ expect(resultStr).toBe(` {
207+ method: "GET",
208+ headers: {
209+ "Content-Type": "application/json",
210+ Authorization: \`Bearer \${this.workOsAccessToken}\`,
211+ },
212+ },
213+ );
214+ `);
215+ });
216+});
deleted core/autocomplete/filtering/streamTransforms/lineStream.test.ts +0 −616
@@ -1,616 +0,0 @@
1-import { jest } from "@jest/globals";
2-
3-import * as lineStream from "./lineStream";
4-
5-// eslint-disable-next-line max-lines-per-function
6-describe("lineStream", () => {
7- let mockFullStop: jest.Mock;
8-
9- async function getLineGenerator(lines: any) {
10- return (async function* () {
11- for (const line of lines) {
12- yield line;
13- }
14- })();
15- }
16-
17- async function getFilteredLines(results: any) {
18- const output = [];
19-
20- for await (const line of results) {
21- output.push(line);
22- }
23-
24- return output;
25- }
26-
27- beforeEach(() => {
28- mockFullStop = jest.fn();
29- });
30-
31- describe("noTopLevelKeywordsMidline", () => {
32- it.todo("Need some sample inputs to properly test this");
33- });
34-
35- describe("avoidPathLine", () => {
36- it("should filter out path lines", async () => {
37- const linesGenerator = await getLineGenerator([
38- "// Path: src/index.ts",
39- "const x = 5;",
40- "//",
41- "console.log(x);",
42- ]);
43- const result = lineStream.avoidPathLine(linesGenerator, "//");
44- const filteredLines = await getFilteredLines(result);
45- expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
46- });
47- });
48-
49- describe("avoidEmptyComments", () => {
50- it("should filter out empty comments", async () => {
51- const linesGenerator = await getLineGenerator([
52- "// Path: src/index.ts",
53- "const x = 5;",
54- "//",
55- "console.log(x);",
56- ]);
57- const result = lineStream.avoidEmptyComments(linesGenerator, "//");
58- const filteredLines = await getFilteredLines(result);
59- expect(filteredLines).toEqual([
60- "// Path: src/index.ts",
61- "const x = 5;",
62- "console.log(x);",
63- ]);
64- });
65- });
66-
67- describe("streamWithNewLines", () => {
68- it("should add newlines between lines", async () => {
69- const linesGenerator = await getLineGenerator([
70- "line1",
71- "line2",
72- "line3",
73- ]);
74-
75- const result = lineStream.streamWithNewLines(linesGenerator);
76- const filteredLines = await getFilteredLines(result);
77-
78- expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]);
79- });
80- });
81-
82- describe("lineIsRepeated", () => {
83- it("should return true for similar lines", () => {
84- expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe(
85- true,
86- );
87- });
88-
89- it("should return false for different lines", () => {
90- expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe(
91- false,
92- );
93- });
94-
95- it("should return false for short lines", () => {
96- expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false);
97- });
98- });
99-
100- describe("stopAtSimilarLine", () => {
101- it("should stop at the exact same line", async () => {
102- const lineToTest = "const x = 6";
103- const linesGenerator = await getLineGenerator([
104- "console.log();",
105- "const y = () => {};",
106- lineToTest,
107- ]);
108-
109- const result = lineStream.stopAtSimilarLine(
110- linesGenerator,
111- lineToTest,
112- mockFullStop,
113- );
114- const filteredLines = await getFilteredLines(result);
115-
116- expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
117- expect(mockFullStop).toHaveBeenCalledTimes(1);
118- });
119-
120- it("should stop at a similar line", async () => {
121- const lineToTest = "const x = 6;";
122- const linesGenerator = await getLineGenerator([
123- "console.log();",
124- "const y = () => {};",
125- lineToTest,
126- ]);
127-
128- const result = lineStream.stopAtSimilarLine(
129- linesGenerator,
130- "a" + lineToTest,
131- mockFullStop,
132- );
133- const filteredLines = await getFilteredLines(result);
134-
135- expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
136- expect(mockFullStop).toHaveBeenCalledTimes(1);
137- });
138-
139- it("should continue on bracket ending lines", async () => {
140- const linesGenerator = await getLineGenerator([
141- " if (x > 0) {",
142- " console.log(x);",
143- " }",
144- ]);
145-
146- const result = lineStream.stopAtSimilarLine(
147- linesGenerator,
148- "}",
149- mockFullStop,
150- );
151- const filteredLines = await getFilteredLines(result);
152-
153- expect(filteredLines).toEqual([
154- " if (x > 0) {",
155- " console.log(x);",
156- " }",
157- ]);
158- expect(mockFullStop).toHaveBeenCalledTimes(0);
159- });
160- });
161-
162- describe("stopAtLines", () => {
163- it("should stop at specified lines", async () => {
164- const linesGenerator = await getLineGenerator([
165- "const x = 5;",
166- "let y = 10;",
167- lineStream.LINES_TO_STOP_AT[0],
168- "const z = 15;",
169- ]);
170-
171- const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
172- const filteredLines = await getFilteredLines(result);
173-
174- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
175- expect(mockFullStop).toHaveBeenCalledTimes(1);
176- });
177- });
178-
179- describe("skipPrefixes", () => {
180- it("should skip specified prefixes", async () => {
181- const linesGenerator = await getLineGenerator([
182- `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`,
183- "let y = 10;",
184- ]);
185-
186- const result = lineStream.skipPrefixes(linesGenerator);
187- const filteredLines = await getFilteredLines(result);
188-
189- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
190- });
191- });
192-
193- describe("skipLines", () => {
194- it("should skip specified lines", async () => {
195- const linesGenerator = await getLineGenerator([
196- `${lineStream.LINES_TO_SKIP[0]}const x = 5;`,
197- "let y = 10;",
198- ]);
199-
200- const result = lineStream.skipLines(linesGenerator);
201- const filteredLines = await getFilteredLines(result);
202-
203- expect(filteredLines).toEqual(["let y = 10;"]);
204- });
205- });
206-
207- describe("filterCodeBlockLines", () => {
208- it("should handle unfenced code", async () => {
209- const linesGenerator = await getLineGenerator(["const x = 5;"]);
210-
211- const result = lineStream.filterCodeBlockLines(linesGenerator);
212- const filteredLines = await getFilteredLines(result);
213-
214- expect(filteredLines).toEqual(["const x = 5;"]);
215- });
216-
217- it("should handle unfenced code with a code block", async () => {
218- const linesGenerator = await getLineGenerator([
219- "const x = 5;",
220- "```bash",
221- "ls -al",
222- "```",
223- ]);
224-
225- const result = lineStream.filterCodeBlockLines(linesGenerator);
226- const filteredLines = await getFilteredLines(result);
227-
228- expect(filteredLines).toEqual([
229- "const x = 5;",
230- "```bash",
231- "ls -al",
232- "```",
233- ]);
234- });
235-
236- it("should handle unfenced code with two code blocks", async () => {
237- const linesGenerator = await getLineGenerator([
238- "const x = 5;",
239- "```bash",
240- "ls -al",
241- "```",
242- "```bash",
243- "ls -al",
244- "```",
245- ]);
246-
247- const result = lineStream.filterCodeBlockLines(linesGenerator);
248- const filteredLines = await getFilteredLines(result);
249-
250- expect(filteredLines).toEqual([
251- "const x = 5;",
252- "```bash",
253- "ls -al",
254- "```",
255- "```bash",
256- "ls -al",
257- "```",
258- ]);
259- });
260-
261- it("should remove lines before the first valid line", async () => {
262- const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
263-
264- const result = lineStream.filterCodeBlockLines(linesGenerator);
265- const filteredLines = await getFilteredLines(result);
266-
267- expect(filteredLines).toEqual(["const x = 5;"]);
268- });
269-
270- it("should remove outer blocks", async () => {
271- const linesGenerator = await getLineGenerator([
272- "```ts",
273- "const x = 5;",
274- "```",
275- ]);
276-
277- const result = lineStream.filterCodeBlockLines(linesGenerator);
278- const filteredLines = await getFilteredLines(result);
279-
280- expect(filteredLines).toEqual(["const x = 5;"]);
281- });
282-
283- it("should leave inner blocks intact", async () => {
284- const linesGenerator = await getLineGenerator([
285- "```md",
286- "const x = 5;",
287- "```bash",
288- "ls -al",
289- "```",
290- "```",
291- ]);
292-
293- const result = lineStream.filterCodeBlockLines(linesGenerator);
294- const filteredLines = await getFilteredLines(result);
295-
296- expect(filteredLines).toEqual([
297- "const x = 5;",
298- "```bash",
299- "ls -al",
300- "```",
301- ]);
302- });
303-
304- it("should handle included inner ticks", async () => {
305- const linesGenerator = await getLineGenerator([
306- "```md",
307- "const x = 5;",
308- "```bash",
309- "echo ```test```",
310- "```",
311- "```",
312- ]);
313-
314- const result = lineStream.filterCodeBlockLines(linesGenerator);
315- const filteredLines = await getFilteredLines(result);
316-
317- expect(filteredLines).toEqual([
318- "const x = 5;",
319- "```bash",
320- "echo ```test```",
321- "```",
322- ]);
323- });
324-
325- it("should leave single inner blocks intact but not return trailing text", async () => {
326- const linesGenerator = await getLineGenerator([
327- "```md",
328- "const x = 5;",
329- "```bash",
330- "ls -al",
331- "```",
332- "```",
333- "trailing text",
334- ]);
335-
336- const result = lineStream.filterCodeBlockLines(linesGenerator);
337- const filteredLines = await getFilteredLines(result);
338-
339- expect(filteredLines).toEqual([
340- "const x = 5;",
341- "```bash",
342- "ls -al",
343- "```",
344- ]);
345- });
346-
347- it("should leave double inner blocks intact but not return trailing text", async () => {
348- const linesGenerator = await getLineGenerator([
349- "```md",
350- "const x = 5;",
351- "```bash",
352- "ls -al",
353- "```",
354- "const y = 10;",
355- "```sh",
356- "echo `hello world`",
357- "```",
358- "```",
359- "trailing text",
360- ]);
361-
362- const result = lineStream.filterCodeBlockLines(linesGenerator);
363- const filteredLines = await getFilteredLines(result);
364-
365- expect(filteredLines).toEqual([
366- "const x = 5;",
367- "```bash",
368- "ls -al",
369- "```",
370- "const y = 10;",
371- "```sh",
372- "echo `hello world`",
373- "```",
374- ]);
375- });
376-
377- it("should leave inner blocks intact but not return trailing or leading text", async () => {
378- const linesGenerator = await getLineGenerator([
379- "[CODE]",
380- "const x = 5;",
381- "```bash",
382- "ls -al",
383- "```",
384- "[/CODE]",
385- "trailing text",
386- ]);
387-
388- const result = lineStream.filterCodeBlockLines(linesGenerator);
389- const filteredLines = await getFilteredLines(result);
390-
391- expect(filteredLines).toEqual([
392- "const x = 5;",
393- "```bash",
394- "ls -al",
395- "```",
396- ]);
397- });
398- });
399-
400- describe("filterEnglishLinesAtStart", () => {
401- it("should skip initial empty line", async () => {
402- const linesGenerator = await getLineGenerator([
403- "",
404- "const x = 5;",
405- "let y = 10;",
406- ]);
407-
408- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
409- const filteredLines = await getFilteredLines(result);
410-
411- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
412- });
413-
414- it("should filter out English first line", async () => {
415- const linesGenerator = await getLineGenerator([
416- lineStream.ENGLISH_START_PHRASES[0],
417- "let y = 10;",
418- ]);
419-
420- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
421- const filteredLines = await getFilteredLines(result);
422-
423- expect(filteredLines).toEqual(["let y = 10;"]);
424- });
425-
426- it("should not filter out non-English first line", async () => {
427- const linesGenerator = await getLineGenerator([
428- "const x = 5;",
429- "let y = 10;",
430- ]);
431-
432- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
433- const filteredLines = await getFilteredLines(result);
434-
435- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
436- });
437-
438- it("should filter out empty newline after first line english word", async () => {
439- const linesGenerator = await getLineGenerator([
440- lineStream.ENGLISH_START_PHRASES[0],
441- "",
442- "const x = 5;",
443- ]);
444-
445- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
446- const filteredLines = await getFilteredLines(result);
447-
448- expect(filteredLines).toEqual(["const x = 5;"]);
449- });
450-
451- it("should filter out sentences ending in a semi-colon that are not code keywords", async () => {
452- const linesGenerator = await getLineGenerator([
453- "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":",
454- "const x = 5;",
455- ]);
456-
457- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
458- const filteredLines = await getFilteredLines(result);
459-
460- expect(filteredLines).toEqual(["const x = 5;"]);
461- });
462-
463- it("should not filter out sentences ending in a semi-colon that are code keywords", async () => {
464- const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":";
465-
466- const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]);
467-
468- const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
469- const filteredLines = await getFilteredLines(result);
470-
471- expect(filteredLines).toEqual([keyword, "const x = 5;"]);
472- });
473- });
474-
475- describe("filterEnglishLinesAtEnd", () => {
476- it("should stop at English explanation after code block", async () => {
477- const linesGenerator = await getLineGenerator([
478- "const x = 5;",
479- "```",
480- lineStream.ENGLISH_POST_PHRASES[0],
481- ]);
482-
483- const result = lineStream.filterEnglishLinesAtEnd(linesGenerator);
484- const filteredLines = await getFilteredLines(result);
485-
486- expect(filteredLines).toEqual(["const x = 5;", "```"]);
487- });
488- });
489-
490- describe("fixCodeLlamaFirstLineIndentation", () => {
491- it("should fix indentation of the first line", async () => {
492- const linesGenerator = await getLineGenerator([
493- " const x = 5;",
494- "let y = 10;",
495- ]);
496-
497- const result =
498- lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator);
499- const filteredLines = await getFilteredLines(result);
500-
501- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
502- });
503- });
504-
505- describe("filterLeadingAndTrailingNewLineInsertion", () => {
506- it("should ignore 'useless' new first lines", async () => {
507- const linesGenerator = await getLineGenerator([
508- { type: "new", line: lineStream.USELESS_LINES[0] },
509- { type: "new", line: "const x = 5;" },
510- ]);
511-
512- const result =
513- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
514- const filteredLines = await getFilteredLines(result);
515-
516- expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]);
517- });
518-
519- it("should handle preserve newlines chars in old lines", async () => {
520- const linesGenerator = await getLineGenerator([
521- { type: "new", line: "const x = 5;" },
522- { type: "old", line: "let y = 10;" },
523- { type: "old", line: "" },
524- { type: "new", line: "const z = 15;" },
525- ]);
526-
527- const result =
528- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
529- const filteredLines = await getFilteredLines(result);
530-
531- expect(filteredLines).toEqual([
532- { type: "new", line: "const x = 5;" },
533- { type: "old", line: "let y = 10;" },
534- { type: "old", line: "" },
535- { type: "new", line: "const z = 15;" },
536- ]);
537- });
538-
539- it("should filter leading and trailing new line insertions", async () => {
540- const linesGenerator = await getLineGenerator([
541- { type: "new", line: "" },
542- { type: "new", line: "const x = 5;" },
543- { type: "new", line: "let y = 10;" },
544- { type: "new", line: "" },
545- ]);
546-
547- const result =
548- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
549- const filteredLines = await getFilteredLines(result);
550-
551- expect(filteredLines).toEqual([
552- { type: "new", line: "const x = 5;" },
553- { type: "new", line: "let y = 10;" },
554- ]);
555- });
556-
557- it("should buffer newline chars and then render them if we encounter another non-empty line", async () => {
558- const linesGenerator = await getLineGenerator([
559- { type: "new", line: "const x = 5;" },
560- { type: "new", line: "" },
561- { type: "new", line: "let y = 10;" },
562- ]);
563-
564- const result =
565- lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
566- const filteredLines = await getFilteredLines(result);
567-
568- expect(filteredLines).toEqual([
569- { type: "new", line: "const x = 5;" },
570- { type: "new", line: "" },
571- { type: "new", line: "let y = 10;" },
572- ]);
573- });
574- });
575-
576- describe("stopAtRepeatingLines", () => {
577- it("should handle non-repeating lines correctly", async () => {
578- const linesGenerator = await getLineGenerator([
579- "const x = 5;",
580- "let y = 10;",
581- "const z = 15;",
582- ]);
583-
584- const result = lineStream.stopAtRepeatingLines(
585- linesGenerator,
586- mockFullStop,
587- );
588- const filteredLines = await getFilteredLines(result);
589-
590- expect(filteredLines).toEqual([
591- "const x = 5;",
592- "let y = 10;",
593- "const z = 15;",
594- ]);
595- });
596-
597- it("should stop at repeating lines", async () => {
598- const linesGenerator = await getLineGenerator([
599- "const x = 5;",
600- "let y = 10;",
601- "let y = 10;",
602- "let y = 10;",
603- "const z = 15;",
604- ]);
605-
606- const result = lineStream.stopAtRepeatingLines(
607- linesGenerator,
608- mockFullStop,
609- );
610- const filteredLines = await getFilteredLines(result);
611-
612- expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
613- expect(mockFullStop).toHaveBeenCalledTimes(1);
614- });
615- });
616-});
added core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +616 −0
@@ -0,0 +1,616 @@
1+import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
2+
3+import * as lineStream from "./lineStream";
4+
5+// eslint-disable-next-line max-lines-per-function
6+describe("lineStream", () => {
7+ let mockFullStop: Mock;
8+
9+ async function getLineGenerator(lines: any) {
10+ return (async function* () {
11+ for (const line of lines) {
12+ yield line;
13+ }
14+ })();
15+ }
16+
17+ async function getFilteredLines(results: any) {
18+ const output = [];
19+
20+ for await (const line of results) {
21+ output.push(line);
22+ }
23+
24+ return output;
25+ }
26+
27+ beforeEach(() => {
28+ mockFullStop = vi.fn();
29+ });
30+
31+ describe("noTopLevelKeywordsMidline", () => {
32+ it.todo("Need some sample inputs to properly test this");
33+ });
34+
35+ describe("avoidPathLine", () => {
36+ it("should filter out path lines", async () => {
37+ const linesGenerator = await getLineGenerator([
38+ "// Path: src/index.ts",
39+ "const x = 5;",
40+ "//",
41+ "console.log(x);",
42+ ]);
43+ const result = lineStream.avoidPathLine(linesGenerator, "//");
44+ const filteredLines = await getFilteredLines(result);
45+ expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
46+ });
47+ });
48+
49+ describe("avoidEmptyComments", () => {
50+ it("should filter out empty comments", async () => {
51+ const linesGenerator = await getLineGenerator([
52+ "// Path: src/index.ts",
53+ "const x = 5;",
54+ "//",
55+ "console.log(x);",
56+ ]);
57+ const result = lineStream.avoidEmptyComments(linesGenerator, "//");
58+ const filteredLines = await getFilteredLines(result);
59+ expect(filteredLines).toEqual([
60+ "// Path: src/index.ts",
61+ "const x = 5;",
62+ "console.log(x);",
63+ ]);
64+ });
65+ });
66+
67+ describe("streamWithNewLines", () => {
68+ it("should add newlines between lines", async () => {
69+ const linesGenerator = await getLineGenerator([
70+ "line1",
71+ "line2",
72+ "line3",
73+ ]);
74+
75+ const result = lineStream.streamWithNewLines(linesGenerator);
76+ const filteredLines = await getFilteredLines(result);
77+
78+ expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]);
79+ });
80+ });
81+
82+ describe("lineIsRepeated", () => {
83+ it("should return true for similar lines", () => {
84+ expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe(
85+ true,
86+ );
87+ });
88+
89+ it("should return false for different lines", () => {
90+ expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe(
91+ false,
92+ );
93+ });
94+
95+ it("should return false for short lines", () => {
96+ expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false);
97+ });
98+ });
99+
100+ describe("stopAtSimilarLine", () => {
101+ it("should stop at the exact same line", async () => {
102+ const lineToTest = "const x = 6";
103+ const linesGenerator = await getLineGenerator([
104+ "console.log();",
105+ "const y = () => {};",
106+ lineToTest,
107+ ]);
108+
109+ const result = lineStream.stopAtSimilarLine(
110+ linesGenerator,
111+ lineToTest,
112+ mockFullStop,
113+ );
114+ const filteredLines = await getFilteredLines(result);
115+
116+ expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
117+ expect(mockFullStop).toHaveBeenCalledTimes(1);
118+ });
119+
120+ it("should stop at a similar line", async () => {
121+ const lineToTest = "const x = 6;";
122+ const linesGenerator = await getLineGenerator([
123+ "console.log();",
124+ "const y = () => {};",
125+ lineToTest,
126+ ]);
127+
128+ const result = lineStream.stopAtSimilarLine(
129+ linesGenerator,
130+ "a" + lineToTest,
131+ mockFullStop,
132+ );
133+ const filteredLines = await getFilteredLines(result);
134+
135+ expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]);
136+ expect(mockFullStop).toHaveBeenCalledTimes(1);
137+ });
138+
139+ it("should continue on bracket ending lines", async () => {
140+ const linesGenerator = await getLineGenerator([
141+ " if (x > 0) {",
142+ " console.log(x);",
143+ " }",
144+ ]);
145+
146+ const result = lineStream.stopAtSimilarLine(
147+ linesGenerator,
148+ "}",
149+ mockFullStop,
150+ );
151+ const filteredLines = await getFilteredLines(result);
152+
153+ expect(filteredLines).toEqual([
154+ " if (x > 0) {",
155+ " console.log(x);",
156+ " }",
157+ ]);
158+ expect(mockFullStop).toHaveBeenCalledTimes(0);
159+ });
160+ });
161+
162+ describe("stopAtLines", () => {
163+ it("should stop at specified lines", async () => {
164+ const linesGenerator = await getLineGenerator([
165+ "const x = 5;",
166+ "let y = 10;",
167+ lineStream.LINES_TO_STOP_AT[0],
168+ "const z = 15;",
169+ ]);
170+
171+ const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
172+ const filteredLines = await getFilteredLines(result);
173+
174+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
175+ expect(mockFullStop).toHaveBeenCalledTimes(1);
176+ });
177+ });
178+
179+ describe("skipPrefixes", () => {
180+ it("should skip specified prefixes", async () => {
181+ const linesGenerator = await getLineGenerator([
182+ `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`,
183+ "let y = 10;",
184+ ]);
185+
186+ const result = lineStream.skipPrefixes(linesGenerator);
187+ const filteredLines = await getFilteredLines(result);
188+
189+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
190+ });
191+ });
192+
193+ describe("skipLines", () => {
194+ it("should skip specified lines", async () => {
195+ const linesGenerator = await getLineGenerator([
196+ `${lineStream.LINES_TO_SKIP[0]}const x = 5;`,
197+ "let y = 10;",
198+ ]);
199+
200+ const result = lineStream.skipLines(linesGenerator);
201+ const filteredLines = await getFilteredLines(result);
202+
203+ expect(filteredLines).toEqual(["let y = 10;"]);
204+ });
205+ });
206+
207+ describe("filterCodeBlockLines", () => {
208+ it("should handle unfenced code", async () => {
209+ const linesGenerator = await getLineGenerator(["const x = 5;"]);
210+
211+ const result = lineStream.filterCodeBlockLines(linesGenerator);
212+ const filteredLines = await getFilteredLines(result);
213+
214+ expect(filteredLines).toEqual(["const x = 5;"]);
215+ });
216+
217+ it("should handle unfenced code with a code block", async () => {
218+ const linesGenerator = await getLineGenerator([
219+ "const x = 5;",
220+ "```bash",
221+ "ls -al",
222+ "```",
223+ ]);
224+
225+ const result = lineStream.filterCodeBlockLines(linesGenerator);
226+ const filteredLines = await getFilteredLines(result);
227+
228+ expect(filteredLines).toEqual([
229+ "const x = 5;",
230+ "```bash",
231+ "ls -al",
232+ "```",
233+ ]);
234+ });
235+
236+ it("should handle unfenced code with two code blocks", async () => {
237+ const linesGenerator = await getLineGenerator([
238+ "const x = 5;",
239+ "```bash",
240+ "ls -al",
241+ "```",
242+ "```bash",
243+ "ls -al",
244+ "```",
245+ ]);
246+
247+ const result = lineStream.filterCodeBlockLines(linesGenerator);
248+ const filteredLines = await getFilteredLines(result);
249+
250+ expect(filteredLines).toEqual([
251+ "const x = 5;",
252+ "```bash",
253+ "ls -al",
254+ "```",
255+ "```bash",
256+ "ls -al",
257+ "```",
258+ ]);
259+ });
260+
261+ it("should remove lines before the first valid line", async () => {
262+ const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
263+
264+ const result = lineStream.filterCodeBlockLines(linesGenerator);
265+ const filteredLines = await getFilteredLines(result);
266+
267+ expect(filteredLines).toEqual(["const x = 5;"]);
268+ });
269+
270+ it("should remove outer blocks", async () => {
271+ const linesGenerator = await getLineGenerator([
272+ "```ts",
273+ "const x = 5;",
274+ "```",
275+ ]);
276+
277+ const result = lineStream.filterCodeBlockLines(linesGenerator);
278+ const filteredLines = await getFilteredLines(result);
279+
280+ expect(filteredLines).toEqual(["const x = 5;"]);
281+ });
282+
283+ it("should leave inner blocks intact", async () => {
284+ const linesGenerator = await getLineGenerator([
285+ "```md",
286+ "const x = 5;",
287+ "```bash",
288+ "ls -al",
289+ "```",
290+ "```",
291+ ]);
292+
293+ const result = lineStream.filterCodeBlockLines(linesGenerator);
294+ const filteredLines = await getFilteredLines(result);
295+
296+ expect(filteredLines).toEqual([
297+ "const x = 5;",
298+ "```bash",
299+ "ls -al",
300+ "```",
301+ ]);
302+ });
303+
304+ it("should handle included inner ticks", async () => {
305+ const linesGenerator = await getLineGenerator([
306+ "```md",
307+ "const x = 5;",
308+ "```bash",
309+ "echo ```test```",
310+ "```",
311+ "```",
312+ ]);
313+
314+ const result = lineStream.filterCodeBlockLines(linesGenerator);
315+ const filteredLines = await getFilteredLines(result);
316+
317+ expect(filteredLines).toEqual([
318+ "const x = 5;",
319+ "```bash",
320+ "echo ```test```",
321+ "```",
322+ ]);
323+ });
324+
325+ it("should leave single inner blocks intact but not return trailing text", async () => {
326+ const linesGenerator = await getLineGenerator([
327+ "```md",
328+ "const x = 5;",
329+ "```bash",
330+ "ls -al",
331+ "```",
332+ "```",
333+ "trailing text",
334+ ]);
335+
336+ const result = lineStream.filterCodeBlockLines(linesGenerator);
337+ const filteredLines = await getFilteredLines(result);
338+
339+ expect(filteredLines).toEqual([
340+ "const x = 5;",
341+ "```bash",
342+ "ls -al",
343+ "```",
344+ ]);
345+ });
346+
347+ it("should leave double inner blocks intact but not return trailing text", async () => {
348+ const linesGenerator = await getLineGenerator([
349+ "```md",
350+ "const x = 5;",
351+ "```bash",
352+ "ls -al",
353+ "```",
354+ "const y = 10;",
355+ "```sh",
356+ "echo `hello world`",
357+ "```",
358+ "```",
359+ "trailing text",
360+ ]);
361+
362+ const result = lineStream.filterCodeBlockLines(linesGenerator);
363+ const filteredLines = await getFilteredLines(result);
364+
365+ expect(filteredLines).toEqual([
366+ "const x = 5;",
367+ "```bash",
368+ "ls -al",
369+ "```",
370+ "const y = 10;",
371+ "```sh",
372+ "echo `hello world`",
373+ "```",
374+ ]);
375+ });
376+
377+ it("should leave inner blocks intact but not return trailing or leading text", async () => {
378+ const linesGenerator = await getLineGenerator([
379+ "[CODE]",
380+ "const x = 5;",
381+ "```bash",
382+ "ls -al",
383+ "```",
384+ "[/CODE]",
385+ "trailing text",
386+ ]);
387+
388+ const result = lineStream.filterCodeBlockLines(linesGenerator);
389+ const filteredLines = await getFilteredLines(result);
390+
391+ expect(filteredLines).toEqual([
392+ "const x = 5;",
393+ "```bash",
394+ "ls -al",
395+ "```",
396+ ]);
397+ });
398+ });
399+
400+ describe("filterEnglishLinesAtStart", () => {
401+ it("should skip initial empty line", async () => {
402+ const linesGenerator = await getLineGenerator([
403+ "",
404+ "const x = 5;",
405+ "let y = 10;",
406+ ]);
407+
408+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
409+ const filteredLines = await getFilteredLines(result);
410+
411+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
412+ });
413+
414+ it("should filter out English first line", async () => {
415+ const linesGenerator = await getLineGenerator([
416+ lineStream.ENGLISH_START_PHRASES[0],
417+ "let y = 10;",
418+ ]);
419+
420+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
421+ const filteredLines = await getFilteredLines(result);
422+
423+ expect(filteredLines).toEqual(["let y = 10;"]);
424+ });
425+
426+ it("should not filter out non-English first line", async () => {
427+ const linesGenerator = await getLineGenerator([
428+ "const x = 5;",
429+ "let y = 10;",
430+ ]);
431+
432+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
433+ const filteredLines = await getFilteredLines(result);
434+
435+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
436+ });
437+
438+ it("should filter out empty newline after first line english word", async () => {
439+ const linesGenerator = await getLineGenerator([
440+ lineStream.ENGLISH_START_PHRASES[0],
441+ "",
442+ "const x = 5;",
443+ ]);
444+
445+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
446+ const filteredLines = await getFilteredLines(result);
447+
448+ expect(filteredLines).toEqual(["const x = 5;"]);
449+ });
450+
451+ it("should filter out sentences ending in a semi-colon that are not code keywords", async () => {
452+ const linesGenerator = await getLineGenerator([
453+ "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":",
454+ "const x = 5;",
455+ ]);
456+
457+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
458+ const filteredLines = await getFilteredLines(result);
459+
460+ expect(filteredLines).toEqual(["const x = 5;"]);
461+ });
462+
463+ it("should not filter out sentences ending in a semi-colon that are code keywords", async () => {
464+ const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":";
465+
466+ const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]);
467+
468+ const result = lineStream.filterEnglishLinesAtStart(linesGenerator);
469+ const filteredLines = await getFilteredLines(result);
470+
471+ expect(filteredLines).toEqual([keyword, "const x = 5;"]);
472+ });
473+ });
474+
475+ describe("filterEnglishLinesAtEnd", () => {
476+ it("should stop at English explanation after code block", async () => {
477+ const linesGenerator = await getLineGenerator([
478+ "const x = 5;",
479+ "```",
480+ lineStream.ENGLISH_POST_PHRASES[0],
481+ ]);
482+
483+ const result = lineStream.filterEnglishLinesAtEnd(linesGenerator);
484+ const filteredLines = await getFilteredLines(result);
485+
486+ expect(filteredLines).toEqual(["const x = 5;", "```"]);
487+ });
488+ });
489+
490+ describe("fixCodeLlamaFirstLineIndentation", () => {
491+ it("should fix indentation of the first line", async () => {
492+ const linesGenerator = await getLineGenerator([
493+ " const x = 5;",
494+ "let y = 10;",
495+ ]);
496+
497+ const result =
498+ lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator);
499+ const filteredLines = await getFilteredLines(result);
500+
501+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
502+ });
503+ });
504+
505+ describe("filterLeadingAndTrailingNewLineInsertion", () => {
506+ it("should ignore 'useless' new first lines", async () => {
507+ const linesGenerator = await getLineGenerator([
508+ { type: "new", line: lineStream.USELESS_LINES[0] },
509+ { type: "new", line: "const x = 5;" },
510+ ]);
511+
512+ const result =
513+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
514+ const filteredLines = await getFilteredLines(result);
515+
516+ expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]);
517+ });
518+
519+ it("should handle preserve newlines chars in old lines", async () => {
520+ const linesGenerator = await getLineGenerator([
521+ { type: "new", line: "const x = 5;" },
522+ { type: "old", line: "let y = 10;" },
523+ { type: "old", line: "" },
524+ { type: "new", line: "const z = 15;" },
525+ ]);
526+
527+ const result =
528+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
529+ const filteredLines = await getFilteredLines(result);
530+
531+ expect(filteredLines).toEqual([
532+ { type: "new", line: "const x = 5;" },
533+ { type: "old", line: "let y = 10;" },
534+ { type: "old", line: "" },
535+ { type: "new", line: "const z = 15;" },
536+ ]);
537+ });
538+
539+ it("should filter leading and trailing new line insertions", async () => {
540+ const linesGenerator = await getLineGenerator([
541+ { type: "new", line: "" },
542+ { type: "new", line: "const x = 5;" },
543+ { type: "new", line: "let y = 10;" },
544+ { type: "new", line: "" },
545+ ]);
546+
547+ const result =
548+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
549+ const filteredLines = await getFilteredLines(result);
550+
551+ expect(filteredLines).toEqual([
552+ { type: "new", line: "const x = 5;" },
553+ { type: "new", line: "let y = 10;" },
554+ ]);
555+ });
556+
557+ it("should buffer newline chars and then render them if we encounter another non-empty line", async () => {
558+ const linesGenerator = await getLineGenerator([
559+ { type: "new", line: "const x = 5;" },
560+ { type: "new", line: "" },
561+ { type: "new", line: "let y = 10;" },
562+ ]);
563+
564+ const result =
565+ lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator);
566+ const filteredLines = await getFilteredLines(result);
567+
568+ expect(filteredLines).toEqual([
569+ { type: "new", line: "const x = 5;" },
570+ { type: "new", line: "" },
571+ { type: "new", line: "let y = 10;" },
572+ ]);
573+ });
574+ });
575+
576+ describe("stopAtRepeatingLines", () => {
577+ it("should handle non-repeating lines correctly", async () => {
578+ const linesGenerator = await getLineGenerator([
579+ "const x = 5;",
580+ "let y = 10;",
581+ "const z = 15;",
582+ ]);
583+
584+ const result = lineStream.stopAtRepeatingLines(
585+ linesGenerator,
586+ mockFullStop,
587+ );
588+ const filteredLines = await getFilteredLines(result);
589+
590+ expect(filteredLines).toEqual([
591+ "const x = 5;",
592+ "let y = 10;",
593+ "const z = 15;",
594+ ]);
595+ });
596+
597+ it("should stop at repeating lines", async () => {
598+ const linesGenerator = await getLineGenerator([
599+ "const x = 5;",
600+ "let y = 10;",
601+ "let y = 10;",
602+ "let y = 10;",
603+ "const z = 15;",
604+ ]);
605+
606+ const result = lineStream.stopAtRepeatingLines(
607+ linesGenerator,
608+ mockFullStop,
609+ );
610+ const filteredLines = await getFilteredLines(result);
611+
612+ expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
613+ expect(mockFullStop).toHaveBeenCalledTimes(1);
614+ });
615+ });
616+});
deleted core/autocomplete/filtering/test/filter.test.ts +0 −48
@@ -1,48 +0,0 @@
1-import { setUpTestDir, tearDownTestDir } from "../../../test/testDir";
2-
3-import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
4-import {
5- AutocompleteFileringTestInput,
6- testAutocompleteFiltering,
7-} from "./util";
8-
9-const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
10- if (tests.some((test) => test.options?.only)) {
11- return tests.filter((test) => test.options?.only);
12- }
13-
14- return tests;
15-};
16-
17-describe("Autocomplete filtering tests", () => {
18- beforeAll(async () => {
19- tearDownTestDir();
20- setUpTestDir();
21- });
22-
23- afterAll(async () => {
24- tearDownTestDir();
25- });
26-
27- beforeEach(async () => {
28- await new Promise((resolve) => setTimeout(resolve, 50));
29- });
30-
31- describe("Should return unmodified LLM output", () => {
32- it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
33- "$description",
34- async (testCase) => {
35- await testAutocompleteFiltering(testCase);
36- },
37- );
38- });
39-
40- describe("Should return modified LLM output", () => {
41- it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
42- "$description",
43- async (testCase) => {
44- await testAutocompleteFiltering(testCase);
45- },
46- );
47- });
48-});
added core/autocomplete/filtering/test/filter.vitest.ts +54 −0
@@ -0,0 +1,54 @@
1+import { afterAll, beforeAll, beforeEach, describe, it } from "vitest";
2+import {
3+ addToTestDir,
4+ setUpTestDir,
5+ tearDownTestDir,
6+} from "../../../test/testDir";
7+
8+import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
9+import {
10+ AutocompleteFileringTestInput,
11+ testAutocompleteFiltering,
12+} from "./util";
13+
14+const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
15+ if (tests.some((test) => test.options?.only)) {
16+ return tests.filter((test) => test.options?.only);
17+ }
18+
19+ return tests;
20+};
21+
22+describe("Autocomplete filtering tests", () => {
23+ beforeAll(async () => {
24+ tearDownTestDir();
25+ setUpTestDir();
26+ addToTestDir([".continueignore"]);
27+ });
28+
29+ afterAll(async () => {
30+ tearDownTestDir();
31+ });
32+
33+ beforeEach(async () => {
34+ await new Promise((resolve) => setTimeout(resolve, 50));
35+ });
36+
37+ describe("Should return unmodified LLM output", () => {
38+ it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
39+ "$description",
40+ async (testCase) => {
41+ await testAutocompleteFiltering(testCase);
42+ },
43+ );
44+ });
45+
46+ describe("Should return modified LLM output", () => {
47+ it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
48+ "$description",
49+ async (testCase) => {
50+ await testAutocompleteFiltering(testCase);
51+ },
52+ );
53+ });
54+});
modified core/autocomplete/filtering/test/util.ts +1 −0
@@ -1,3 +1,4 @@
1+import { expect } from "vitest";
12 import MockLLM from "../../../llm/llms/Mock";
23 import { testConfigHandler, testIde } from "../../../test/fixtures";
34 import { joinPathsToUri } from "../../../util/uri";
deleted core/autocomplete/generation/GeneratorReuseManager.test.ts +0 −215
@@ -1,215 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { GeneratorReuseManager } from "./GeneratorReuseManager";
3-
4-function createMockGenerator(
5- data: string[],
6- delay: number = 0,
7-): (abortSignal: AbortSignal) => AsyncGenerator<string> {
8- const mockGenerator = async function* () {
9- for (const chunk of data) {
10- yield chunk;
11-
12- if (delay > 0) {
13- await new Promise((resolve) => setTimeout(resolve, delay));
14- }
15- }
16- };
17- const newGenerator = jest
18- .fn<() => AsyncGenerator<string>>()
19- .mockReturnValue(mockGenerator());
20-
21- return newGenerator;
22-}
23-
24-describe("GeneratorReuseManager", () => {
25- let reuseManager: GeneratorReuseManager;
26- let onErrorMock: jest.Mock;
27-
28- beforeEach(() => {
29- onErrorMock = jest.fn();
30- reuseManager = new GeneratorReuseManager(onErrorMock);
31- });
32-
33- afterEach(() => {
34- jest.clearAllMocks();
35- });
36-
37- test("creates new generator when there is no current generator", async () => {
38- const data = ["hello ", "world"];
39- const newGenerator = createMockGenerator(data);
40-
41- const prefix = "";
42-
43- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
44-
45- const output: string[] = [];
46- for await (const chunk of generator) {
47- output.push(chunk);
48- }
49-
50- expect(output).toEqual(data);
51- expect(newGenerator).toHaveBeenCalledTimes(1);
52- });
53-
54- test("reuses generator when prefix matches pending completion", async () => {
55- const newGenerator = createMockGenerator(["llo ", "world"]);
56-
57- // First call with initial prefix
58- const prefix1 = "he";
59- const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
60-
61- const output1: string[] = [];
62- for await (const chunk of generator1) {
63- output1.push(chunk);
64- }
65-
66- expect(output1).toEqual(["llo ", "world"]);
67-
68- // Second call with extended prefix that matches pending completion
69- const prefix2 = "hello ";
70- const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
71-
72- const output2: string[] = [];
73- for await (const chunk of generator2) {
74- output2.push(chunk);
75- }
76-
77- expect(output2).toEqual(["world"]);
78-
79- // Ensure generator was reused (newGenerator should be called only once)
80- expect(newGenerator).toHaveBeenCalledTimes(1);
81- });
82-
83- test("creates new generator when prefix does not match pending completion", async () => {
84- const data = ["goodbye ", "world"];
85- const newGenerator = createMockGenerator(data);
86-
87- // Initial generator with different prefix
88- reuseManager.pendingGeneratorPrefix = "hello ";
89- reuseManager.pendingCompletion = "world";
90-
91- const prefix = "good";
92- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
93-
94- const output: string[] = [];
95- for await (const chunk of generator) {
96- output.push(chunk);
97- }
98-
99- expect(output).toEqual(data);
100- // Ensure a new generator was created
101- expect(newGenerator).toHaveBeenCalledTimes(1);
102- });
103-
104- test("handles multiline=false by stopping at newline", async () => {
105- const data = ["first line\n", "second line"];
106- const newGenerator = createMockGenerator(data);
107-
108- const prefix = "";
109- const generator = reuseManager.getGenerator(prefix, newGenerator, false);
110-
111- const output: string[] = [];
112- for await (const chunk of generator) {
113- output.push(chunk);
114- }
115-
116- expect(output).toEqual(["first line"]);
117- // Ensure it stops after the first newline
118- });
119-
120- test("handles multiline=true by not stopping at newline", async () => {
121- const data = ["first line\n", "second line"];
122- const newGenerator = createMockGenerator(data);
123-
124- const prefix = "";
125- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
126-
127- const output: string[] = [];
128- for await (const chunk of generator) {
129- output.push(chunk);
130- }
131-
132- expect(output).toEqual(data);
133- });
134-
135- test("cancels previous generator when creating a new one", async () => {
136- const data1 = ["data from generator 1", "not generated"];
137- const data2 = ["data from generator 2"];
138-
139- const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
140- const newGenerator2 = createMockGenerator(data2);
141-
142- const prefix1 = "prefix1";
143- const prefix2 = "prefix2";
144-
145- // First generator
146- const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
147- const output1: string[] = [];
148- for await (const chunk of generator1) {
149- output1.push(chunk);
150- // Simulate the generator being canceled before completing
151- reuseManager.currentGenerator?.cancel();
152- }
153-
154- expect(output1.length).toEqual(1);
155- expect(output1[0]).toEqual(data1[0]);
156-
157- // Second generator
158- const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
159- const output2: string[] = [];
160- for await (const chunk of generator2) {
161- output2.push(chunk);
162- }
163-
164- expect(output2).toEqual(data2);
165- });
166-
167- test("calls onError when generator throws an error", async () => {
168- const error = new Error("Generator error");
169- const mockGenerator = async function* () {
170- throw error;
171- };
172- const newGenerator = jest
173- .fn<() => AsyncGenerator<string>>()
174- .mockReturnValue(mockGenerator());
175-
176- const prefix = "";
177- const generator = reuseManager.getGenerator(prefix, newGenerator, true);
178-
179- const output: string[] = [];
180- await expect(async () => {
181- for await (const chunk of generator) {
182- output.push(chunk);
183- }
184- }).not.toThrow(); // getGenerator handles errors internally
185-
186- expect(onErrorMock).toHaveBeenCalledWith(error);
187- expect(output).toEqual([]);
188- });
189-
190- test("handles backspacing by creating new generator when prefix is shorter", async () => {
191- const data = ["hello world"];
192- const newGenerator1 = createMockGenerator(data);
193- const newGenerator2 = createMockGenerator(data);
194-
195- // First prefix
196- const prefix1 = "hello world";
197- const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
198- const output1: string[] = [];
199- for await (const chunk of generator1) {
200- output1.push(chunk);
201- }
202-
203- // Simulate backspace (prefix is shorter)
204- const prefix2 = "hello worl";
205- const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
206- const output2: string[] = [];
207- for await (const chunk of generator2) {
208- output2.push(chunk);
209- }
210-
211- // Ensure a new generator was created
212- expect(newGenerator1).toHaveBeenCalledTimes(1);
213- expect(newGenerator2).toHaveBeenCalledTimes(1);
214- });
215-});
added core/autocomplete/generation/GeneratorReuseManager.vitest.ts +223 −0
@@ -0,0 +1,223 @@
1+import {
2+ afterEach,
3+ beforeEach,
4+ describe,
5+ expect,
6+ Mock,
7+ test,
8+ vi,
9+} from "vitest";
10+import { GeneratorReuseManager } from "./GeneratorReuseManager";
11+
12+function createMockGenerator(
13+ data: string[],
14+ delay: number = 0,
15+): (abortSignal: AbortSignal) => AsyncGenerator<string> {
16+ const mockGenerator = async function* () {
17+ for (const chunk of data) {
18+ yield chunk;
19+
20+ if (delay > 0) {
21+ await new Promise((resolve) => setTimeout(resolve, delay));
22+ }
23+ }
24+ };
25+ const newGenerator = vi
26+ .fn<() => AsyncGenerator<string>>()
27+ .mockReturnValue(mockGenerator());
28+
29+ return newGenerator;
30+}
31+
32+describe("GeneratorReuseManager", () => {
33+ let reuseManager: GeneratorReuseManager;
34+ let onErrorMock: Mock;
35+
36+ beforeEach(() => {
37+ onErrorMock = vi.fn();
38+ reuseManager = new GeneratorReuseManager(onErrorMock);
39+ });
40+
41+ afterEach(() => {
42+ vi.clearAllMocks();
43+ });
44+
45+ test("creates new generator when there is no current generator", async () => {
46+ const data = ["hello ", "world"];
47+ const newGenerator = createMockGenerator(data);
48+
49+ const prefix = "";
50+
51+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
52+
53+ const output: string[] = [];
54+ for await (const chunk of generator) {
55+ output.push(chunk);
56+ }
57+
58+ expect(output).toEqual(data);
59+ expect(newGenerator).toHaveBeenCalledTimes(1);
60+ });
61+
62+ test("reuses generator when prefix matches pending completion", async () => {
63+ const newGenerator = createMockGenerator(["llo ", "world"]);
64+
65+ // First call with initial prefix
66+ const prefix1 = "he";
67+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
68+
69+ const output1: string[] = [];
70+ for await (const chunk of generator1) {
71+ output1.push(chunk);
72+ }
73+
74+ expect(output1).toEqual(["llo ", "world"]);
75+
76+ // Second call with extended prefix that matches pending completion
77+ const prefix2 = "hello ";
78+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
79+
80+ const output2: string[] = [];
81+ for await (const chunk of generator2) {
82+ output2.push(chunk);
83+ }
84+
85+ expect(output2).toEqual(["world"]);
86+
87+ // Ensure generator was reused (newGenerator should be called only once)
88+ expect(newGenerator).toHaveBeenCalledTimes(1);
89+ });
90+
91+ test("creates new generator when prefix does not match pending completion", async () => {
92+ const data = ["goodbye ", "world"];
93+ const newGenerator = createMockGenerator(data);
94+
95+ // Initial generator with different prefix
96+ reuseManager.pendingGeneratorPrefix = "hello ";
97+ reuseManager.pendingCompletion = "world";
98+
99+ const prefix = "good";
100+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
101+
102+ const output: string[] = [];
103+ for await (const chunk of generator) {
104+ output.push(chunk);
105+ }
106+
107+ expect(output).toEqual(data);
108+ // Ensure a new generator was created
109+ expect(newGenerator).toHaveBeenCalledTimes(1);
110+ });
111+
112+ test("handles multiline=false by stopping at newline", async () => {
113+ const data = ["first line\n", "second line"];
114+ const newGenerator = createMockGenerator(data);
115+
116+ const prefix = "";
117+ const generator = reuseManager.getGenerator(prefix, newGenerator, false);
118+
119+ const output: string[] = [];
120+ for await (const chunk of generator) {
121+ output.push(chunk);
122+ }
123+
124+ expect(output).toEqual(["first line"]);
125+ // Ensure it stops after the first newline
126+ });
127+
128+ test("handles multiline=true by not stopping at newline", async () => {
129+ const data = ["first line\n", "second line"];
130+ const newGenerator = createMockGenerator(data);
131+
132+ const prefix = "";
133+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
134+
135+ const output: string[] = [];
136+ for await (const chunk of generator) {
137+ output.push(chunk);
138+ }
139+
140+ expect(output).toEqual(data);
141+ });
142+
143+ test("cancels previous generator when creating a new one", async () => {
144+ const data1 = ["data from generator 1", "not generated"];
145+ const data2 = ["data from generator 2"];
146+
147+ const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
148+ const newGenerator2 = createMockGenerator(data2);
149+
150+ const prefix1 = "prefix1";
151+ const prefix2 = "prefix2";
152+
153+ // First generator
154+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
155+ const output1: string[] = [];
156+ for await (const chunk of generator1) {
157+ output1.push(chunk);
158+ // Simulate the generator being canceled before completing
159+ reuseManager.currentGenerator?.cancel();
160+ }
161+
162+ expect(output1.length).toEqual(1);
163+ expect(output1[0]).toEqual(data1[0]);
164+
165+ // Second generator
166+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
167+ const output2: string[] = [];
168+ for await (const chunk of generator2) {
169+ output2.push(chunk);
170+ }
171+
172+ expect(output2).toEqual(data2);
173+ });
174+
175+ test("calls onError when generator throws an error", async () => {
176+ const error = new Error("Generator error");
177+ const mockGenerator = async function* () {
178+ throw error;
179+ };
180+ const newGenerator = vi
181+ .fn<() => AsyncGenerator<string>>()
182+ .mockReturnValue(mockGenerator());
183+
184+ const prefix = "";
185+ const generator = reuseManager.getGenerator(prefix, newGenerator, true);
186+
187+ const output: string[] = [];
188+ await expect(async () => {
189+ for await (const chunk of generator) {
190+ output.push(chunk);
191+ }
192+ }).not.toThrow(); // getGenerator handles errors internally
193+
194+ expect(onErrorMock).toHaveBeenCalledWith(error);
195+ expect(output).toEqual([]);
196+ });
197+
198+ test("handles backspacing by creating new generator when prefix is shorter", async () => {
199+ const data = ["hello world"];
200+ const newGenerator1 = createMockGenerator(data);
201+ const newGenerator2 = createMockGenerator(data);
202+
203+ // First prefix
204+ const prefix1 = "hello world";
205+ const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
206+ const output1: string[] = [];
207+ for await (const chunk of generator1) {
208+ output1.push(chunk);
209+ }
210+
211+ // Simulate backspace (prefix is shorter)
212+ const prefix2 = "hello worl";
213+ const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
214+ const output2: string[] = [];
215+ for await (const chunk of generator2) {
216+ output2.push(chunk);
217+ }
218+
219+ // Ensure a new generator was created
220+ expect(newGenerator1).toHaveBeenCalledTimes(1);
221+ expect(newGenerator2).toHaveBeenCalledTimes(1);
222+ });
223+});
deleted core/autocomplete/generation/ListenableGenerator.test.ts +0 −174
@@ -1,174 +0,0 @@
1-import { jest } from "@jest/globals";
2-
3-import { ListenableGenerator } from "./ListenableGenerator";
4-
5-describe("ListenableGenerator", () => {
6- // Helper function to create an async generator
7- async function* asyncGenerator<T>(values: T[], delay = 0) {
8- for (const value of values) {
9- if (delay > 0) {
10- await new Promise((resolve) => setTimeout(resolve, delay));
11- }
12- yield value;
13- }
14- }
15-
16- it("should yield values from the source generator via tee()", async () => {
17- const values = [1, 2, 3];
18- const source = asyncGenerator(values);
19- const onError = jest.fn();
20-
21- const lg = new ListenableGenerator<number>(
22- source,
23- onError,
24- new AbortController(),
25- );
26-
27- const result: number[] = [];
28- for await (const value of lg.tee()) {
29- result.push(value);
30- }
31-
32- expect(result).toEqual(values);
33- expect(onError).not.toHaveBeenCalled();
34- });
35-
36- it("should allow listeners to receive values", async () => {
37- const values = [1, 2, 3];
38- const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
39- const onError = jest.fn();
40-
41- const lg = new ListenableGenerator<number>(
42- source,
43- onError,
44- new AbortController(),
45- );
46-
47- const listener = jest.fn();
48-
49- // Add listener after some delay to simulate late subscription
50- setTimeout(() => {
51- lg.listen(listener);
52- }, 15);
53-
54- // Wait for generator to finish
55- await new Promise((resolve) => setTimeout(resolve, 50));
56-
57- expect(listener).toHaveBeenCalledWith(1);
58- expect(listener).toHaveBeenCalledWith(2);
59- expect(listener).toHaveBeenCalledWith(3);
60- // Listener should receive null at the end
61- expect(listener).toHaveBeenCalledWith(null);
62- });
63-
64- it("should buffer values for listeners added after some values have been yielded", async () => {
65- const values = [1, 2, 3];
66- const source = asyncGenerator(values, 10);
67- const onError = jest.fn();
68-
69- const lg = new ListenableGenerator<number>(
70- source,
71- onError,
72- new AbortController(),
73- );
74-
75- const initialListener = jest.fn();
76-
77- lg.listen(initialListener);
78-
79- // Wait for the first value to be yielded
80- await new Promise((resolve) => setTimeout(resolve, 15));
81-
82- // Add a second listener
83- const newListener = jest.fn();
84- lg.listen(newListener);
85-
86- // Wait for generator to finish
87- await new Promise((resolve) => setTimeout(resolve, 50));
88-
89- // Both listeners should have received all values
90- [initialListener, newListener].forEach((listener) => {
91- expect(listener).toHaveBeenCalledWith(1);
92- expect(listener).toHaveBeenCalledWith(2);
93- expect(listener).toHaveBeenCalledWith(3);
94- expect(listener).toHaveBeenCalledWith(null);
95- });
96- });
97-
98- it("should handle cancellation", async () => {
99- const values = [1, 2, 3, 4, 5];
100- const source = asyncGenerator(values, 10);
101- const onError = jest.fn();
102-
103- const lg = new ListenableGenerator<number>(
104- source,
105- onError,
106- new AbortController(),
107- );
108-
109- const result: number[] = [];
110- const teeIterator = lg.tee();
111-
112- const consume = async () => {
113- for await (const value of teeIterator) {
114- result.push(value);
115- if (value === 3) {
116- lg.cancel();
117- }
118- }
119- };
120-
121- await consume();
122-
123- expect(result).toEqual([1, 2, 3]);
124- expect(lg["_isEnded"]).toBe(true);
125- });
126-
127- it("should call onError when the source generator throws an error", async () => {
128- async function* errorGenerator() {
129- yield 1;
130- throw new Error("Test error");
131- }
132-
133- const source = errorGenerator();
134- const onError = jest.fn();
135-
136- const lg = new ListenableGenerator<number>(
137- source,
138- onError,
139- new AbortController(),
140- );
141-
142- const result: number[] = [];
143- for await (const value of lg.tee()) {
144- result.push(value);
145- }
146-
147- expect(result).toEqual([1]);
148- expect(onError).toHaveBeenCalledTimes(1);
149- expect(onError).toHaveBeenCalledWith(new Error("Test error"));
150- });
151-
152- it("should notify listeners when the generator ends", async () => {
153- const values = [1, 2, 3];
154- const source = asyncGenerator(values);
155- const onError = jest.fn();
156-
157- const lg = new ListenableGenerator<number>(
158- source,
159- onError,
160- new AbortController(),
161- );
162-
163- const listener = jest.fn();
164- lg.listen(listener);
165-
166- // Wait for the generator to finish
167- await new Promise((resolve) => setTimeout(resolve, 10));
168-
169- expect(listener).toHaveBeenCalledWith(1);
170- expect(listener).toHaveBeenCalledWith(2);
171- expect(listener).toHaveBeenCalledWith(3);
172- expect(listener).toHaveBeenCalledWith(null);
173- });
174-});
added core/autocomplete/generation/ListenableGenerator.vitest.ts +174 −0
@@ -0,0 +1,174 @@
1+import { describe, expect, it, vi } from "vitest";
2+
3+import { ListenableGenerator } from "./ListenableGenerator";
4+
5+describe("ListenableGenerator", () => {
6+ // Helper function to create an async generator
7+ async function* asyncGenerator<T>(values: T[], delay = 0) {
8+ for (const value of values) {
9+ if (delay > 0) {
10+ await new Promise((resolve) => setTimeout(resolve, delay));
11+ }
12+ yield value;
13+ }
14+ }
15+
16+ it("should yield values from the source generator via tee()", async () => {
17+ const values = [1, 2, 3];
18+ const source = asyncGenerator(values);
19+ const onError = vi.fn();
20+
21+ const lg = new ListenableGenerator<number>(
22+ source,
23+ onError,
24+ new AbortController(),
25+ );
26+
27+ const result: number[] = [];
28+ for await (const value of lg.tee()) {
29+ result.push(value);
30+ }
31+
32+ expect(result).toEqual(values);
33+ expect(onError).not.toHaveBeenCalled();
34+ });
35+
36+ it("should allow listeners to receive values", async () => {
37+ const values = [1, 2, 3];
38+ const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
39+ const onError = vi.fn();
40+
41+ const lg = new ListenableGenerator<number>(
42+ source,
43+ onError,
44+ new AbortController(),
45+ );
46+
47+ const listener = vi.fn();
48+
49+ // Add listener after some delay to simulate late subscription
50+ setTimeout(() => {
51+ lg.listen(listener);
52+ }, 15);
53+
54+ // Wait for generator to finish
55+ await new Promise((resolve) => setTimeout(resolve, 50));
56+
57+ expect(listener).toHaveBeenCalledWith(1);
58+ expect(listener).toHaveBeenCalledWith(2);
59+ expect(listener).toHaveBeenCalledWith(3);
60+ // Listener should receive null at the end
61+ expect(listener).toHaveBeenCalledWith(null);
62+ });
63+
64+ it("should buffer values for listeners added after some values have been yielded", async () => {
65+ const values = [1, 2, 3];
66+ const source = asyncGenerator(values, 10);
67+ const onError = vi.fn();
68+
69+ const lg = new ListenableGenerator<number>(
70+ source,
71+ onError,
72+ new AbortController(),
73+ );
74+
75+ const initialListener = vi.fn();
76+
77+ lg.listen(initialListener);
78+
79+ // Wait for the first value to be yielded
80+ await new Promise((resolve) => setTimeout(resolve, 15));
81+
82+ // Add a second listener
83+ const newListener = vi.fn();
84+ lg.listen(newListener);
85+
86+ // Wait for generator to finish
87+ await new Promise((resolve) => setTimeout(resolve, 50));
88+
89+ // Both listeners should have received all values
90+ [initialListener, newListener].forEach((listener) => {
91+ expect(listener).toHaveBeenCalledWith(1);
92+ expect(listener).toHaveBeenCalledWith(2);
93+ expect(listener).toHaveBeenCalledWith(3);
94+ expect(listener).toHaveBeenCalledWith(null);
95+ });
96+ });
97+
98+ it("should handle cancellation", async () => {
99+ const values = [1, 2, 3, 4, 5];
100+ const source = asyncGenerator(values, 10);
101+ const onError = vi.fn();
102+
103+ const lg = new ListenableGenerator<number>(
104+ source,
105+ onError,
106+ new AbortController(),
107+ );
108+
109+ const result: number[] = [];
110+ const teeIterator = lg.tee();
111+
112+ const consume = async () => {
113+ for await (const value of teeIterator) {
114+ result.push(value);
115+ if (value === 3) {
116+ lg.cancel();
117+ }
118+ }
119+ };
120+
121+ await consume();
122+
123+ expect(result).toEqual([1, 2, 3]);
124+ expect(lg["_isEnded"]).toBe(true);
125+ });
126+
127+ it("should call onError when the source generator throws an error", async () => {
128+ async function* errorGenerator() {
129+ yield 1;
130+ throw new Error("Test error");
131+ }
132+
133+ const source = errorGenerator();
134+ const onError = vi.fn();
135+
136+ const lg = new ListenableGenerator<number>(
137+ source,
138+ onError,
139+ new AbortController(),
140+ );
141+
142+ const result: number[] = [];
143+ for await (const value of lg.tee()) {
144+ result.push(value);
145+ }
146+
147+ expect(result).toEqual([1]);
148+ expect(onError).toHaveBeenCalledTimes(1);
149+ expect(onError).toHaveBeenCalledWith(new Error("Test error"));
150+ });
151+
152+ it("should notify listeners when the generator ends", async () => {
153+ const values = [1, 2, 3];
154+ const source = asyncGenerator(values);
155+ const onError = vi.fn();
156+
157+ const lg = new ListenableGenerator<number>(
158+ source,
159+ onError,
160+ new AbortController(),
161+ );
162+
163+ const listener = vi.fn();
164+ lg.listen(listener);
165+
166+ // Wait for the generator to finish
167+ await new Promise((resolve) => setTimeout(resolve, 10));
168+
169+ expect(listener).toHaveBeenCalledWith(1);
170+ expect(listener).toHaveBeenCalledWith(2);
171+ expect(listener).toHaveBeenCalledWith(3);
172+ expect(listener).toHaveBeenCalledWith(null);
173+ });
174+});
deleted core/autocomplete/generation/utils.test.ts +0 −138
@@ -1,138 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { stopAfterMaxProcessingTime } from "./utils";
3-
4-describe("stopAfterMaxProcessingTime", () => {
5- beforeEach(() => {
6- jest.useFakeTimers();
7- });
8-
9- afterEach(() => {
10- jest.useRealTimers();
11- });
12-
13- async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
14- for (const chunk of chunks) {
15- yield chunk;
16- }
17- }
18-
19- async function streamToString(
20- stream: AsyncGenerator<string>,
21- ): Promise<string> {
22- let result = "";
23- for await (const chunk of stream) {
24- result += chunk;
25- }
26- return result;
27- }
28-
29- it("should yield all chunks when maxTimeMs is not reached", async () => {
30- const mockStream = createMockStream(["Hello", " world", "!"]);
31- const fullStop = jest.fn();
32- const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
33-
34- const output = await streamToString(result);
35-
36- expect(output).toBe("Hello world!");
37- expect(fullStop).not.toHaveBeenCalled();
38- });
39-
40- it.only("should stop processing after max time is reached", async () => {
41- // Mock implementation of Date.now
42- let currentTime = 0;
43- const originalDateNow = Date.now;
44- Date.now = jest.fn(() => currentTime);
45-
46- // Create a generator that we can control
47- async function* controlledGenerator(): AsyncGenerator<string> {
48- for (let i = 0; i < 100; i++) {
49- // After yielding 10 chunks, simulate time passing beyond our limit
50- if (i === 10) {
51- currentTime = 1000; // This exceeds our 500ms limit
52- }
53- yield `chunk-${i}`;
54- }
55- }
56-
57- const fullStop = jest.fn();
58- const maxTimeMs = 500;
59-
60- const transformedGenerator = stopAfterMaxProcessingTime(
61- controlledGenerator(),
62- maxTimeMs,
63- fullStop,
64- );
65-
66- // Consume the generator and collect outputs
67- const outputs: string[] = [];
68- for await (const chunk of transformedGenerator) {
69- outputs.push(chunk);
70- }
71-
72- // We expect:
73- // 1. Not all chunks were processed (less than 100)
74- // 2. fullStop was called
75- // 3. We processed at least the chunks before time was exceeded
76- expect(outputs.length).toBeLessThan(100);
77- expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
78- expect(fullStop).toHaveBeenCalled();
79-
80- // Restore Date.now
81- Date.now = originalDateNow;
82- });
83-
84- it("should check time only periodically based on checkInterval", async () => {
85- const chunks = Array(100).fill("x");
86- const mockStream = createMockStream(chunks);
87- const fullStop = jest.fn();
88-
89- // Spy on Date.now to count how many times it's called
90- const dateSpy = jest.spyOn(Date, "now");
91-
92- // Stream should complete normally (not hitting the timeout)
93- await streamToString(
94- stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
95- );
96-
97- // The first call is to set startTime, then once every checkInterval (10) chunks
98- // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
99- // We use a range because implementation details might vary slightly
100- expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
101- expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
102-
103- dateSpy.mockRestore();
104- });
105-
106- it("should handle empty stream gracefully", async () => {
107- const mockStream = createMockStream([]);
108- const fullStop = jest.fn();
109- const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
110-
111- const output = await streamToString(result);
112-
113- expect(output).toBe("");
114- expect(fullStop).not.toHaveBeenCalled();
115- });
116-
117- it("should pass through all chunks if there's no timeout", async () => {
118- const chunks = Array(100).fill("test chunk");
119- const mockStream = createMockStream(chunks);
120- const fullStop = jest.fn();
121-
122- // Use undefined as timeout to simulate no timeout
123- const result = stopAfterMaxProcessingTime(
124- mockStream,
125- undefined as any,
126- fullStop,
127- );
128-
129- // Process the stream
130- const processedChunks = [];
131- for await (const chunk of result) {
132- processedChunks.push(chunk);
133- }
134-
135- expect(processedChunks.length).toBe(chunks.length);
136- expect(fullStop).not.toHaveBeenCalled();
137- });
138-});
added core/autocomplete/generation/utils.vitest.ts +138 −0
@@ -0,0 +1,138 @@
1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+import { stopAfterMaxProcessingTime } from "./utils";
3+
4+describe("stopAfterMaxProcessingTime", () => {
5+ beforeEach(() => {
6+ vi.useFakeTimers();
7+ });
8+
9+ afterEach(() => {
10+ vi.useRealTimers();
11+ });
12+
13+ async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
14+ for (const chunk of chunks) {
15+ yield chunk;
16+ }
17+ }
18+
19+ async function streamToString(
20+ stream: AsyncGenerator<string>,
21+ ): Promise<string> {
22+ let result = "";
23+ for await (const chunk of stream) {
24+ result += chunk;
25+ }
26+ return result;
27+ }
28+
29+ it("should yield all chunks when maxTimeMs is not reached", async () => {
30+ const mockStream = createMockStream(["Hello", " world", "!"]);
31+ const fullStop = vi.fn();
32+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
33+
34+ const output = await streamToString(result);
35+
36+ expect(output).toBe("Hello world!");
37+ expect(fullStop).not.toHaveBeenCalled();
38+ });
39+
40+ it("should stop processing after max time is reached", async () => {
41+ // Mock implementation of Date.now
42+ let currentTime = 0;
43+ const originalDateNow = Date.now;
44+ Date.now = vi.fn(() => currentTime);
45+
46+ // Create a generator that we can control
47+ async function* controlledGenerator(): AsyncGenerator<string> {
48+ for (let i = 0; i < 100; i++) {
49+ // After yielding 10 chunks, simulate time passing beyond our limit
50+ if (i === 10) {
51+ currentTime = 1000; // This exceeds our 500ms limit
52+ }
53+ yield `chunk-${i}`;
54+ }
55+ }
56+
57+ const fullStop = vi.fn();
58+ const maxTimeMs = 500;
59+
60+ const transformedGenerator = stopAfterMaxProcessingTime(
61+ controlledGenerator(),
62+ maxTimeMs,
63+ fullStop,
64+ );
65+
66+ // Consume the generator and collect outputs
67+ const outputs: string[] = [];
68+ for await (const chunk of transformedGenerator) {
69+ outputs.push(chunk);
70+ }
71+
72+ // We expect:
73+ // 1. Not all chunks were processed (less than 100)
74+ // 2. fullStop was called
75+ // 3. We processed at least the chunks before time was exceeded
76+ expect(outputs.length).toBeLessThan(100);
77+ expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
78+ expect(fullStop).toHaveBeenCalled();
79+
80+ // Restore Date.now
81+ Date.now = originalDateNow;
82+ });
83+
84+ it("should check time only periodically based on checkInterval", async () => {
85+ const chunks = Array(100).fill("x");
86+ const mockStream = createMockStream(chunks);
87+ const fullStop = vi.fn();
88+
89+ // Spy on Date.now to count how many times it's called
90+ const dateSpy = vi.spyOn(Date, "now");
91+
92+ // Stream should complete normally (not hitting the timeout)
93+ await streamToString(
94+ stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
95+ );
96+
97+ // The first call is to set startTime, then once every checkInterval (10) chunks
98+ // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
99+ // We use a range because implementation details might vary slightly
100+ expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
101+ expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
102+
103+ dateSpy.mockRestore();
104+ });
105+
106+ it("should handle empty stream gracefully", async () => {
107+ const mockStream = createMockStream([]);
108+ const fullStop = vi.fn();
109+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
110+
111+ const output = await streamToString(result);
112+
113+ expect(output).toBe("");
114+ expect(fullStop).not.toHaveBeenCalled();
115+ });
116+
117+ it("should pass through all chunks if there's no timeout", async () => {
118+ const chunks = Array(100).fill("test chunk");
119+ const mockStream = createMockStream(chunks);
120+ const fullStop = vi.fn();
121+
122+ // Use undefined as timeout to simulate no timeout
123+ const result = stopAfterMaxProcessingTime(
124+ mockStream,
125+ undefined as any,
126+ fullStop,
127+ );
128+
129+ // Process the stream
130+ const processedChunks = [];
131+ for await (const chunk of result) {
132+ processedChunks.push(chunk);
133+ }
134+
135+ expect(processedChunks.length).toBe(chunks.length);
136+ expect(fullStop).not.toHaveBeenCalled();
137+ });
138+});
modified core/autocomplete/postprocessing/index.ts +8 −0
@@ -132,6 +132,14 @@
132132 completion = "\n" + completion;
133133 }
134134
135+ if (
136+ (llm.model.includes("gemini") || llm.model.includes("gemma")) &&
137+ completion.endsWith("<|file_separator|>")
138+ ) {
139+ // "<|file_separator|>" is 18 characters long
140+ completion = completion.slice(0, -18);
141+ }
142+
135143 // If prefix ends with space and so does completion, then remove the space from completion
136144
137145 if (prefix.endsWith(" ") && completion.startsWith(" ")) {
modified core/autocomplete/snippets/getAllSnippets.ts +44 −0
@@ -209,3 +209,47 @@
209209 recentlyOpenedFileSnippets,
210210 };
211211 };
212+
213+export const getAllSnippetsWithoutRace = async ({
214+ helper,
215+ ide,
216+ getDefinitionsFromLsp,
217+ contextRetrievalService,
218+}: {
219+ helper: HelperVars;
220+ ide: IDE;
221+ getDefinitionsFromLsp: GetLspDefinitionsFunction;
222+ contextRetrievalService: ContextRetrievalService;
223+}): Promise<SnippetPayload> => {
224+ const recentlyEditedRangeSnippets =
225+ getSnippetsFromRecentlyEditedRanges(helper);
226+
227+ const [
228+ rootPathSnippets,
229+ importDefinitionSnippets,
230+ ideSnippets,
231+ diffSnippets,
232+ clipboardSnippets,
233+ recentlyOpenedFileSnippets,
234+ ] = await Promise.all([
235+ contextRetrievalService.getRootPathSnippets(helper),
236+ contextRetrievalService.getSnippetsFromImportDefinitions(helper),
237+ IDE_SNIPPETS_ENABLED
238+ ? getIdeSnippets(helper, ide, getDefinitionsFromLsp)
239+ : [],
240+ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
241+ getClipboardSnippets(ide),
242+ getSnippetsFromRecentlyOpenedFiles(helper, ide),
243+ ]);
244+
245+ return {
246+ rootPathSnippets,
247+ importDefinitionSnippets,
248+ ideSnippets,
249+ recentlyEditedRangeSnippets,
250+ diffSnippets,
251+ clipboardSnippets,
252+ recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
253+ recentlyOpenedFileSnippets,
254+ };
255+};
deleted core/autocomplete/snippets/gitDiffCache.test.ts +0 −84
@@ -1,84 +0,0 @@
1-import { GitDiffCache } from "./gitDiffCache";
2-
3-beforeEach(() => {
4- // Add this line to GitDiffCache class to make instance accessible
5- (GitDiffCache as any).instance = null;
6-});
7-
8-test("GitDiffCache returns cached results within cache time", async () => {
9- const mockDiff = ["file1.ts", "file2.ts"];
10- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
11- const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
12-
13- const result1 = await cache.get();
14- const result2 = await cache.get();
15-
16- expect(result1).toEqual(mockDiff);
17- expect(result2).toEqual(mockDiff);
18- expect(getDiffFn).toHaveBeenCalledTimes(1);
19-});
20-
21-test("GitDiffCache refreshes cache after expiration", async () => {
22- const mockDiff = ["file1.ts"];
23- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
24- const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
25-
26- const result1 = await cache.get();
27- await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
28- const result2 = await cache.get();
29-
30- expect(getDiffFn).toHaveBeenCalledTimes(2);
31-});
32-
33-test("GitDiffCache returns empty array on error", async () => {
34- const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
35- const cache = GitDiffCache.getInstance(getDiffFn);
36-
37- const result = await cache.get();
38- expect(result).toEqual([]);
39-});
40-
41-test("GitDiffCache reuses pending request", async () => {
42- const mockDiff = ["file1.ts"];
43- let resolvePromise: (value: string[]) => void;
44- const getDiffFn = jest.fn().mockImplementation(() => {
45- return new Promise((resolve) => {
46- resolvePromise = resolve;
47- });
48- });
49-
50- const cache = GitDiffCache.getInstance(getDiffFn);
51-
52- const promise1 = cache.get();
53- const promise2 = cache.get();
54-
55- resolvePromise!(mockDiff);
56-
57- const [result1, result2] = await Promise.all([promise1, promise2]);
58-
59- expect(result1).toEqual(mockDiff);
60- expect(result2).toEqual(mockDiff);
61- expect(getDiffFn).toHaveBeenCalledTimes(1);
62-});
63-
64-test("GitDiffCache invalidate clears cache", async () => {
65- const mockDiff = ["file1.ts"];
66- const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
67- const cache = GitDiffCache.getInstance(getDiffFn);
68-
69- await cache.get();
70- cache.invalidate();
71- await cache.get();
72-
73- expect(getDiffFn).toHaveBeenCalledTimes(2);
74-});
75-
76-test("GitDiffCache maintains singleton instance", () => {
77- const getDiffFn1 = jest.fn();
78- const getDiffFn2 = jest.fn();
79-
80- const instance1 = GitDiffCache.getInstance(getDiffFn1);
81- const instance2 = GitDiffCache.getInstance(getDiffFn2);
82-
83- expect(instance1).toBe(instance2);
84-});
added core/autocomplete/snippets/gitDiffCache.vitest.ts +85 −0
@@ -0,0 +1,85 @@
1+import { beforeEach, expect, test, vi } from "vitest";
2+import { GitDiffCache } from "./gitDiffCache";
3+
4+beforeEach(() => {
5+ // Add this line to GitDiffCache class to make instance accessible
6+ (GitDiffCache as any).instance = null;
7+});
8+
9+test("GitDiffCache returns cached results within cache time", async () => {
10+ const mockDiff = ["file1.ts", "file2.ts"];
11+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
12+ const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
13+
14+ const result1 = await cache.get();
15+ const result2 = await cache.get();
16+
17+ expect(result1).toEqual(mockDiff);
18+ expect(result2).toEqual(mockDiff);
19+ expect(getDiffFn).toHaveBeenCalledTimes(1);
20+});
21+
22+test("GitDiffCache refreshes cache after expiration", async () => {
23+ const mockDiff = ["file1.ts"];
24+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
25+ const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
26+
27+ const result1 = await cache.get();
28+ await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
29+ const result2 = await cache.get();
30+
31+ expect(getDiffFn).toHaveBeenCalledTimes(2);
32+});
33+
34+test("GitDiffCache returns empty array on error", async () => {
35+ const getDiffFn = vi.fn().mockRejectedValue(new Error("Git error"));
36+ const cache = GitDiffCache.getInstance(getDiffFn);
37+
38+ const result = await cache.get();
39+ expect(result).toEqual([]);
40+});
41+
42+test("GitDiffCache reuses pending request", async () => {
43+ const mockDiff = ["file1.ts"];
44+ let resolvePromise: (value: string[]) => void;
45+ const getDiffFn = vi.fn().mockImplementation(() => {
46+ return new Promise((resolve) => {
47+ resolvePromise = resolve;
48+ });
49+ });
50+
51+ const cache = GitDiffCache.getInstance(getDiffFn);
52+
53+ const promise1 = cache.get();
54+ const promise2 = cache.get();
55+
56+ resolvePromise!(mockDiff);
57+
58+ const [result1, result2] = await Promise.all([promise1, promise2]);
59+
60+ expect(result1).toEqual(mockDiff);
61+ expect(result2).toEqual(mockDiff);
62+ expect(getDiffFn).toHaveBeenCalledTimes(1);
63+});
64+
65+test("GitDiffCache invalidate clears cache", async () => {
66+ const mockDiff = ["file1.ts"];
67+ const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
68+ const cache = GitDiffCache.getInstance(getDiffFn);
69+
70+ await cache.get();
71+ cache.invalidate();
72+ await cache.get();
73+
74+ expect(getDiffFn).toHaveBeenCalledTimes(2);
75+});
76+
77+test("GitDiffCache maintains singleton instance", () => {
78+ const getDiffFn1 = vi.fn();
79+ const getDiffFn2 = vi.fn();
80+
81+ const instance1 = GitDiffCache.getInstance(getDiffFn1);
82+ const instance2 = GitDiffCache.getInstance(getDiffFn2);
83+
84+ expect(instance1).toBe(instance2);
85+});
deleted core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts +0 −434
@@ -1,434 +0,0 @@
1-/**
2- * Comprehensive tests for formatOpenedFilesContext.ts
3- *
4- */
5-
6-import {
7- AutocompleteCodeSnippet,
8- AutocompleteDiffSnippet,
9- AutocompleteSnippetType,
10-} from "../../snippets/types";
11-import { HelperVars } from "../../util/HelperVars";
12-import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
13-
14-// Import the now-exported internal functions
15-import {
16- getRecencyAndSizeScore,
17- rankByScore,
18- setLogStats,
19- trimSnippetForContext,
20-} from "../formatOpenedFilesContext";
21-
22-describe("formatOpenedFilesContext main function tests", () => {
23- const mockHelper = {
24- modelName: "test-model",
25- } as HelperVars;
26-
27- const TOKEN_BUFFER = 50;
28-
29- // Create sample code snippets with various sizes
30- const createCodeSnippet = (
31- filepath: string,
32- content: string,
33- ): AutocompleteCodeSnippet => ({
34- type: AutocompleteSnippetType.Code,
35- filepath,
36- content,
37- });
38-
39- const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
40- type: AutocompleteSnippetType.Diff,
41- content,
42- });
43-
44- test("should return empty array when no snippets are provided", () => {
45- const result = formatOpenedFilesContext(
46- [],
47- 1000,
48- mockHelper,
49- [],
50- TOKEN_BUFFER,
51- );
52- expect(result).toEqual([]);
53- });
54-
55- test("should handle zero remaining token count", () => {
56- const snippets = [
57- createCodeSnippet("file1.ts", "content of file 1"),
58- createCodeSnippet("file2.ts", "content of file 2"),
59- ];
60-
61- const result = formatOpenedFilesContext(
62- snippets,
63- 0,
64- mockHelper,
65- [],
66- TOKEN_BUFFER,
67- );
68-
69- expect(result).toEqual([]);
70- });
71-
72- test("should handle snippets with empty content", () => {
73- const emptySnippets = [
74- createCodeSnippet("empty1.ts", ""),
75- createCodeSnippet("empty2.ts", ""),
76- ];
77-
78- const result = formatOpenedFilesContext(
79- emptySnippets,
80- 1000,
81- mockHelper,
82- [],
83- TOKEN_BUFFER,
84- );
85-
86- expect(result.length).toBe(emptySnippets.length);
87- });
88-
89- test("should return all snippets when they all fit within token limit", () => {
90- const smallSnippets = [
91- createCodeSnippet("small1.ts", "a"),
92- createCodeSnippet("small2.ts", "b"),
93- createCodeSnippet("small3.ts", "c"),
94- ];
95-
96- const result = formatOpenedFilesContext(
97- smallSnippets,
98- 1000,
99- mockHelper,
100- [],
101- TOKEN_BUFFER,
102- );
103-
104- expect(result.length).toBe(smallSnippets.length);
105- });
106-
107- test("should handle limited token count", () => {
108- const snippets = Array(10)
109- .fill(0)
110- .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
111-
112- const result = formatOpenedFilesContext(
113- snippets,
114- 1, // Extremely small token count
115- mockHelper,
116- [],
117- TOKEN_BUFFER,
118- );
119-
120- expect(Array.isArray(result)).toBe(true);
121- });
122-
123- test("should accept valid inputs with adequate token count", () => {
124- const snippets = [
125- createCodeSnippet("file1.ts", "Some content here"),
126- createCodeSnippet("file2.ts", "More content here"),
127- ];
128-
129- const result = formatOpenedFilesContext(
130- snippets,
131- 1000,
132- mockHelper,
133- [],
134- TOKEN_BUFFER,
135- );
136-
137- expect(result.length).toBeGreaterThan(0);
138- });
139-
140- test("should handle already added snippets parameter", () => {
141- const snippets = [
142- createCodeSnippet("file1.ts", "content of file 1"),
143- createCodeSnippet("file2.ts", "content of file 2"),
144- ];
145-
146- const alreadyAddedSnippets = [createDiffSnippet("diff content")];
147-
148- const result = formatOpenedFilesContext(
149- snippets,
150- 1000,
151- mockHelper,
152- alreadyAddedSnippets,
153- TOKEN_BUFFER,
154- );
155-
156- expect(result.length).toBe(snippets.length);
157- });
158-
159- test("should handle large snippets by trimming them", () => {
160- const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
161-
162- const result = formatOpenedFilesContext(
163- [largeSnippet],
164- 200,
165- mockHelper,
166- [],
167- TOKEN_BUFFER,
168- );
169-
170- expect(result.length).toBe(1);
171- expect(result[0].filepath).toBe(largeSnippet.filepath);
172- expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
173- });
174-
175- test("should prioritize more recent snippets when not all fit", () => {
176- const snippets = [
177- createCodeSnippet("recent1.ts", "a".repeat(10)),
178- createCodeSnippet("recent2.ts", "b".repeat(10000)),
179- createCodeSnippet("recent3.ts", "c".repeat(10000)),
180- ];
181-
182- const result = formatOpenedFilesContext(
183- snippets,
184- 200,
185- mockHelper,
186- [],
187- TOKEN_BUFFER,
188- );
189-
190- expect(result.length).toBeGreaterThan(0);
191- expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
192- });
193-
194- test("should handle a mix of large and small snippets effectively", () => {
195- const mixedSnippets = [
196- createCodeSnippet("small1.ts", "a".repeat(10)),
197- createCodeSnippet("large1.ts", "b".repeat(5000)),
198- createCodeSnippet("small2.ts", "c".repeat(10)),
199- createCodeSnippet("large2.ts", "d".repeat(5000)),
200- ];
201-
202- const result = formatOpenedFilesContext(
203- mixedSnippets,
204- 500,
205- mockHelper,
206- [],
207- TOKEN_BUFFER,
208- );
209-
210- expect(result.length).toBeGreaterThan(0);
211- expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
212- });
213-
214- test("should respect minimum token threshold when trimming", () => {
215- const largeSnippets = [
216- createCodeSnippet("large1.ts", "a".repeat(5000)),
217- createCodeSnippet("large2.ts", "b".repeat(5000)),
218- ];
219-
220- const result = formatOpenedFilesContext(
221- largeSnippets,
222- 150,
223- mockHelper,
224- [],
225- TOKEN_BUFFER,
226- );
227-
228- expect(result.length).toBeLessThanOrEqual(1);
229-
230- if (result.length > 0) {
231- expect(result[0].content.length).toBeLessThan(
232- largeSnippets[0].content.length,
233- );
234- }
235- });
236-});
237-
238-// Tests for rankByScore function
239-describe("rankByScore function", () => {
240- const createCodeSnippet = (
241- filepath: string,
242- content: string,
243- ): AutocompleteCodeSnippet => ({
244- type: AutocompleteSnippetType.Code,
245- filepath,
246- content,
247- });
248-
249- test("should return empty array when given empty array", () => {
250- const result = rankByScore([]);
251- expect(result).toEqual([]);
252- });
253-
254- test("should rank snippets by score", () => {
255- // Initialize logMin and logMax by calling setLogStats first
256- const snippets = [
257- createCodeSnippet("file1.ts", "a".repeat(10)),
258- createCodeSnippet("file2.ts", "b".repeat(1000)),
259- createCodeSnippet("file3.ts", "c".repeat(100)),
260- ];
261- setLogStats(snippets);
262-
263- const result = rankByScore(snippets);
264-
265- expect(Array.isArray(result)).toBe(true);
266- expect(result.length).toBeGreaterThan(0);
267-
268- // The snippets should be ranked in some order, which may not match input order
269- expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
270- snippets.map((s) => s.filepath),
271- );
272- });
273-
274- test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
275- // Create more snippets than the default limit
276- const manySnippets = Array(10)
277- .fill(0)
278- .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
279- setLogStats(manySnippets);
280-
281- const result = rankByScore(manySnippets);
282-
283- // The function should limit the number of snippets (defaultNumFilesUsed is 5)
284- expect(result.length).toBeLessThanOrEqual(5);
285- });
286-});
287-
288-// Tests for getRecencyAndSizeScore function
289-describe("getRecencyAndSizeScore function", () => {
290- const createCodeSnippet = (
291- filepath: string,
292- content: string,
293- ): AutocompleteCodeSnippet => ({
294- type: AutocompleteSnippetType.Code,
295- filepath,
296- content,
297- });
298-
299- test("recency score should decrease with higher index", () => {
300- // Initialize log stats first
301- const snippets = [
302- createCodeSnippet("file1.ts", "a".repeat(100)),
303- createCodeSnippet("file2.ts", "b".repeat(100)),
304- ];
305- setLogStats(snippets);
306-
307- // Test that score decreases with increasing index
308- const score0 = getRecencyAndSizeScore(0, snippets[0]);
309- const score1 = getRecencyAndSizeScore(1, snippets[0]);
310- const score2 = getRecencyAndSizeScore(2, snippets[0]);
311-
312- expect(score0).toBeGreaterThan(score1);
313- expect(score1).toBeGreaterThan(score2);
314- });
315-
316- test("size score should be higher for smaller snippets", () => {
317- // Initialize log stats first
318- const snippets = [
319- createCodeSnippet("small.ts", "a".repeat(50)),
320- createCodeSnippet("medium.ts", "b".repeat(200)),
321- createCodeSnippet("large.ts", "c".repeat(1000)),
322- ];
323- setLogStats(snippets);
324-
325- // Test with same recency index but different sizes
326- const smallScore = getRecencyAndSizeScore(0, snippets[0]);
327- const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
328- const largeScore = getRecencyAndSizeScore(0, snippets[2]);
329-
330- // Scores should reflect preference for smaller snippets
331- expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
332- expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
333- });
334-
335- test("recency and size both affect the score with recency having more weight", () => {
336- // Initialize log stats first
337- const snippets = [
338- createCodeSnippet("recent_large.ts", "a".repeat(1000)),
339- createCodeSnippet("old_small.ts", "b".repeat(50)),
340- ];
341- setLogStats(snippets);
342-
343- // Test that recency and size both contribute to the score
344- const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
345- const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
346-
347- // We're not making a direct comparison, just verifying the scoring mechanism works
348- expect(recentLargeScore).toBeGreaterThan(0);
349- expect(oldSmallScore).toBeGreaterThan(0);
350- expect(oldSmallScore).toBeLessThan(1);
351- });
352-});
353-
354-// Tests for setLogStats function
355-describe("setLogStats function", () => {
356- const createCodeSnippet = (
357- filepath: string,
358- content: string,
359- ): AutocompleteCodeSnippet => ({
360- type: AutocompleteSnippetType.Code,
361- filepath,
362- content,
363- });
364-
365- test("should set logMin and logMax based on snippet sizes", () => {
366- const snippets = [
367- createCodeSnippet("small.ts", "a".repeat(50)),
368- createCodeSnippet("medium.ts", "b".repeat(200)),
369- createCodeSnippet("large.ts", "c".repeat(1000)),
370- ];
371-
372- // We can't directly test logMin and logMax as they're private
373- // but we can verify that the function runs without errors
374- expect(() => setLogStats(snippets)).not.toThrow();
375- });
376-
377- test("should handle empty snippets", () => {
378- const emptySnippets = [
379- createCodeSnippet("empty1.ts", ""),
380- createCodeSnippet("empty2.ts", ""),
381- ];
382-
383- expect(() => setLogStats(emptySnippets)).not.toThrow();
384- });
385-
386- test("should handle single snippet", () => {
387- const singleSnippet = [createCodeSnippet("single.ts", "content")];
388-
389- expect(() => setLogStats(singleSnippet)).not.toThrow();
390- });
391-});
392-
393-// Tests for trimSnippetForContext function
394-describe("trimSnippetForContext function", () => {
395- const createCodeSnippet = (
396- filepath: string,
397- content: string,
398- ): AutocompleteCodeSnippet => ({
399- type: AutocompleteSnippetType.Code,
400- filepath,
401- content,
402- });
403-
404- test("should return original snippet if it fits within token limit", () => {
405- const snippet = createCodeSnippet("small.ts", "small content");
406- const modelName = "test-model";
407- const maxTokens = 1000; // Large enough to fit the snippet
408-
409- const result = trimSnippetForContext(snippet, maxTokens, modelName);
410-
411- // Should return the original snippet with its token count
412- expect(result.newSnippet).toEqual(snippet);
413- expect(typeof result.newTokens).toBe("number");
414- expect(result.newTokens).toBeGreaterThan(0);
415- });
416-
417- test("should trim snippet content if it exceeds token limit", () => {
418- const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
419- const modelName = "test-model";
420- const maxTokens = 10; // Small enough to require trimming
421-
422- const result = trimSnippetForContext(snippet, maxTokens, modelName);
423-
424- // Should return a trimmed snippet
425- expect(result.newSnippet.filepath).toBe(snippet.filepath);
426- expect(result.newSnippet.type).toBe(snippet.type);
427- expect(result.newSnippet.content.length).toBeLessThanOrEqual(
428- snippet.content.length,
429- );
430-
431- // Token count should be less than or equal to maxTokens
432- expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
433- });
434-});
added core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts +435 −0
@@ -0,0 +1,435 @@
1+/**
2+ * Comprehensive tests for formatOpenedFilesContext.ts
3+ *
4+ */
5+
6+import { describe, expect, test } from "vitest";
7+import {
8+ AutocompleteCodeSnippet,
9+ AutocompleteDiffSnippet,
10+ AutocompleteSnippetType,
11+} from "../../snippets/types";
12+import { HelperVars } from "../../util/HelperVars";
13+import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
14+
15+// Import the now-exported internal functions
16+import {
17+ getRecencyAndSizeScore,
18+ rankByScore,
19+ setLogStats,
20+ trimSnippetForContext,
21+} from "../formatOpenedFilesContext";
22+
23+describe("formatOpenedFilesContext main function tests", () => {
24+ const mockHelper = {
25+ modelName: "test-model",
26+ } as HelperVars;
27+
28+ const TOKEN_BUFFER = 50;
29+
30+ // Create sample code snippets with various sizes
31+ const createCodeSnippet = (
32+ filepath: string,
33+ content: string,
34+ ): AutocompleteCodeSnippet => ({
35+ type: AutocompleteSnippetType.Code,
36+ filepath,
37+ content,
38+ });
39+
40+ const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
41+ type: AutocompleteSnippetType.Diff,
42+ content,
43+ });
44+
45+ test("should return empty array when no snippets are provided", () => {
46+ const result = formatOpenedFilesContext(
47+ [],
48+ 1000,
49+ mockHelper,
50+ [],
51+ TOKEN_BUFFER,
52+ );
53+ expect(result).toEqual([]);
54+ });
55+
56+ test("should handle zero remaining token count", () => {
57+ const snippets = [
58+ createCodeSnippet("file1.ts", "content of file 1"),
59+ createCodeSnippet("file2.ts", "content of file 2"),
60+ ];
61+
62+ const result = formatOpenedFilesContext(
63+ snippets,
64+ 0,
65+ mockHelper,
66+ [],
67+ TOKEN_BUFFER,
68+ );
69+
70+ expect(result).toEqual([]);
71+ });
72+
73+ test("should handle snippets with empty content", () => {
74+ const emptySnippets = [
75+ createCodeSnippet("empty1.ts", ""),
76+ createCodeSnippet("empty2.ts", ""),
77+ ];
78+
79+ const result = formatOpenedFilesContext(
80+ emptySnippets,
81+ 1000,
82+ mockHelper,
83+ [],
84+ TOKEN_BUFFER,
85+ );
86+
87+ expect(result.length).toBe(emptySnippets.length);
88+ });
89+
90+ test("should return all snippets when they all fit within token limit", () => {
91+ const smallSnippets = [
92+ createCodeSnippet("small1.ts", "a"),
93+ createCodeSnippet("small2.ts", "b"),
94+ createCodeSnippet("small3.ts", "c"),
95+ ];
96+
97+ const result = formatOpenedFilesContext(
98+ smallSnippets,
99+ 1000,
100+ mockHelper,
101+ [],
102+ TOKEN_BUFFER,
103+ );
104+
105+ expect(result.length).toBe(smallSnippets.length);
106+ });
107+
108+ test("should handle limited token count", () => {
109+ const snippets = Array(10)
110+ .fill(0)
111+ .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
112+
113+ const result = formatOpenedFilesContext(
114+ snippets,
115+ 1, // Extremely small token count
116+ mockHelper,
117+ [],
118+ TOKEN_BUFFER,
119+ );
120+
121+ expect(Array.isArray(result)).toBe(true);
122+ });
123+
124+ test("should accept valid inputs with adequate token count", () => {
125+ const snippets = [
126+ createCodeSnippet("file1.ts", "Some content here"),
127+ createCodeSnippet("file2.ts", "More content here"),
128+ ];
129+
130+ const result = formatOpenedFilesContext(
131+ snippets,
132+ 1000,
133+ mockHelper,
134+ [],
135+ TOKEN_BUFFER,
136+ );
137+
138+ expect(result.length).toBeGreaterThan(0);
139+ });
140+
141+ test("should handle already added snippets parameter", () => {
142+ const snippets = [
143+ createCodeSnippet("file1.ts", "content of file 1"),
144+ createCodeSnippet("file2.ts", "content of file 2"),
145+ ];
146+
147+ const alreadyAddedSnippets = [createDiffSnippet("diff content")];
148+
149+ const result = formatOpenedFilesContext(
150+ snippets,
151+ 1000,
152+ mockHelper,
153+ alreadyAddedSnippets,
154+ TOKEN_BUFFER,
155+ );
156+
157+ expect(result.length).toBe(snippets.length);
158+ });
159+
160+ test("should handle large snippets by trimming them", () => {
161+ const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
162+
163+ const result = formatOpenedFilesContext(
164+ [largeSnippet],
165+ 200,
166+ mockHelper,
167+ [],
168+ TOKEN_BUFFER,
169+ );
170+
171+ expect(result.length).toBe(1);
172+ expect(result[0].filepath).toBe(largeSnippet.filepath);
173+ expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
174+ });
175+
176+ test("should prioritize more recent snippets when not all fit", () => {
177+ const snippets = [
178+ createCodeSnippet("recent1.ts", "a".repeat(10)),
179+ createCodeSnippet("recent2.ts", "b".repeat(10000)),
180+ createCodeSnippet("recent3.ts", "c".repeat(10000)),
181+ ];
182+
183+ const result = formatOpenedFilesContext(
184+ snippets,
185+ 200,
186+ mockHelper,
187+ [],
188+ TOKEN_BUFFER,
189+ );
190+
191+ expect(result.length).toBeGreaterThan(0);
192+ expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
193+ });
194+
195+ test("should handle a mix of large and small snippets effectively", () => {
196+ const mixedSnippets = [
197+ createCodeSnippet("small1.ts", "a".repeat(10)),
198+ createCodeSnippet("large1.ts", "b".repeat(5000)),
199+ createCodeSnippet("small2.ts", "c".repeat(10)),
200+ createCodeSnippet("large2.ts", "d".repeat(5000)),
201+ ];
202+
203+ const result = formatOpenedFilesContext(
204+ mixedSnippets,
205+ 500,
206+ mockHelper,
207+ [],
208+ TOKEN_BUFFER,
209+ );
210+
211+ expect(result.length).toBeGreaterThan(0);
212+ expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
213+ });
214+
215+ test("should respect minimum token threshold when trimming", () => {
216+ const largeSnippets = [
217+ createCodeSnippet("large1.ts", "a".repeat(5000)),
218+ createCodeSnippet("large2.ts", "b".repeat(5000)),
219+ ];
220+
221+ const result = formatOpenedFilesContext(
222+ largeSnippets,
223+ 150,
224+ mockHelper,
225+ [],
226+ TOKEN_BUFFER,
227+ );
228+
229+ expect(result.length).toBeLessThanOrEqual(1);
230+
231+ if (result.length > 0) {
232+ expect(result[0].content.length).toBeLessThan(
233+ largeSnippets[0].content.length,
234+ );
235+ }
236+ });
237+});
238+
239+// Tests for rankByScore function
240+describe("rankByScore function", () => {
241+ const createCodeSnippet = (
242+ filepath: string,
243+ content: string,
244+ ): AutocompleteCodeSnippet => ({
245+ type: AutocompleteSnippetType.Code,
246+ filepath,
247+ content,
248+ });
249+
250+ test("should return empty array when given empty array", () => {
251+ const result = rankByScore([]);
252+ expect(result).toEqual([]);
253+ });
254+
255+ test("should rank snippets by score", () => {
256+ // Initialize logMin and logMax by calling setLogStats first
257+ const snippets = [
258+ createCodeSnippet("file1.ts", "a".repeat(10)),
259+ createCodeSnippet("file2.ts", "b".repeat(1000)),
260+ createCodeSnippet("file3.ts", "c".repeat(100)),
261+ ];
262+ setLogStats(snippets);
263+
264+ const result = rankByScore(snippets);
265+
266+ expect(Array.isArray(result)).toBe(true);
267+ expect(result.length).toBeGreaterThan(0);
268+
269+ // The snippets should be ranked in some order, which may not match input order
270+ expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
271+ snippets.map((s) => s.filepath),
272+ );
273+ });
274+
275+ test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
276+ // Create more snippets than the default limit
277+ const manySnippets = Array(10)
278+ .fill(0)
279+ .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
280+ setLogStats(manySnippets);
281+
282+ const result = rankByScore(manySnippets);
283+
284+ // The function should limit the number of snippets (defaultNumFilesUsed is 5)
285+ expect(result.length).toBeLessThanOrEqual(5);
286+ });
287+});
288+
289+// Tests for getRecencyAndSizeScore function
290+describe("getRecencyAndSizeScore function", () => {
291+ const createCodeSnippet = (
292+ filepath: string,
293+ content: string,
294+ ): AutocompleteCodeSnippet => ({
295+ type: AutocompleteSnippetType.Code,
296+ filepath,
297+ content,
298+ });
299+
300+ test("recency score should decrease with higher index", () => {
301+ // Initialize log stats first
302+ const snippets = [
303+ createCodeSnippet("file1.ts", "a".repeat(100)),
304+ createCodeSnippet("file2.ts", "b".repeat(100)),
305+ ];
306+ setLogStats(snippets);
307+
308+ // Test that score decreases with increasing index
309+ const score0 = getRecencyAndSizeScore(0, snippets[0]);
310+ const score1 = getRecencyAndSizeScore(1, snippets[0]);
311+ const score2 = getRecencyAndSizeScore(2, snippets[0]);
312+
313+ expect(score0).toBeGreaterThan(score1);
314+ expect(score1).toBeGreaterThan(score2);
315+ });
316+
317+ test("size score should be higher for smaller snippets", () => {
318+ // Initialize log stats first
319+ const snippets = [
320+ createCodeSnippet("small.ts", "a".repeat(50)),
321+ createCodeSnippet("medium.ts", "b".repeat(200)),
322+ createCodeSnippet("large.ts", "c".repeat(1000)),
323+ ];
324+ setLogStats(snippets);
325+
326+ // Test with same recency index but different sizes
327+ const smallScore = getRecencyAndSizeScore(0, snippets[0]);
328+ const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
329+ const largeScore = getRecencyAndSizeScore(0, snippets[2]);
330+
331+ // Scores should reflect preference for smaller snippets
332+ expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
333+ expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
334+ });
335+
336+ test("recency and size both affect the score with recency having more weight", () => {
337+ // Initialize log stats first
338+ const snippets = [
339+ createCodeSnippet("recent_large.ts", "a".repeat(1000)),
340+ createCodeSnippet("old_small.ts", "b".repeat(50)),
341+ ];
342+ setLogStats(snippets);
343+
344+ // Test that recency and size both contribute to the score
345+ const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
346+ const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
347+
348+ // We're not making a direct comparison, just verifying the scoring mechanism works
349+ expect(recentLargeScore).toBeGreaterThan(0);
350+ expect(oldSmallScore).toBeGreaterThan(0);
351+ expect(oldSmallScore).toBeLessThan(1);
352+ });
353+});
354+
355+// Tests for setLogStats function
356+describe("setLogStats function", () => {
357+ const createCodeSnippet = (
358+ filepath: string,
359+ content: string,
360+ ): AutocompleteCodeSnippet => ({
361+ type: AutocompleteSnippetType.Code,
362+ filepath,
363+ content,
364+ });
365+
366+ test("should set logMin and logMax based on snippet sizes", () => {
367+ const snippets = [
368+ createCodeSnippet("small.ts", "a".repeat(50)),
369+ createCodeSnippet("medium.ts", "b".repeat(200)),
370+ createCodeSnippet("large.ts", "c".repeat(1000)),
371+ ];
372+
373+ // We can't directly test logMin and logMax as they're private
374+ // but we can verify that the function runs without errors
375+ expect(() => setLogStats(snippets)).not.toThrow();
376+ });
377+
378+ test("should handle empty snippets", () => {
379+ const emptySnippets = [
380+ createCodeSnippet("empty1.ts", ""),
381+ createCodeSnippet("empty2.ts", ""),
382+ ];
383+
384+ expect(() => setLogStats(emptySnippets)).not.toThrow();
385+ });
386+
387+ test("should handle single snippet", () => {
388+ const singleSnippet = [createCodeSnippet("single.ts", "content")];
389+
390+ expect(() => setLogStats(singleSnippet)).not.toThrow();
391+ });
392+});
393+
394+// Tests for trimSnippetForContext function
395+describe("trimSnippetForContext function", () => {
396+ const createCodeSnippet = (
397+ filepath: string,
398+ content: string,
399+ ): AutocompleteCodeSnippet => ({
400+ type: AutocompleteSnippetType.Code,
401+ filepath,
402+ content,
403+ });
404+
405+ test("should return original snippet if it fits within token limit", () => {
406+ const snippet = createCodeSnippet("small.ts", "small content");
407+ const modelName = "test-model";
408+ const maxTokens = 1000; // Large enough to fit the snippet
409+
410+ const result = trimSnippetForContext(snippet, maxTokens, modelName);
411+
412+ // Should return the original snippet with its token count
413+ expect(result.newSnippet).toEqual(snippet);
414+ expect(typeof result.newTokens).toBe("number");
415+ expect(result.newTokens).toBeGreaterThan(0);
416+ });
417+
418+ test("should trim snippet content if it exceeds token limit", () => {
419+ const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
420+ const modelName = "test-model";
421+ const maxTokens = 10; // Small enough to require trimming
422+
423+ const result = trimSnippetForContext(snippet, maxTokens, modelName);
424+
425+ // Should return a trimmed snippet
426+ expect(result.newSnippet.filepath).toBe(snippet.filepath);
427+ expect(result.newSnippet.type).toBe(snippet.type);
428+ expect(result.newSnippet.content.length).toBeLessThanOrEqual(
429+ snippet.content.length,
430+ );
431+
432+ // Token count should be less than or equal to maxTokens
433+ expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
434+ });
435+});
deleted core/autocomplete/util/completionTestUtils.test.ts +0 −65
@@ -1,65 +0,0 @@
1-import {
2- processTestCase,
3- type CompletionTestCase,
4-} from "./completionTestUtils";
5-
6-describe("processTestCase utility", () => {
7- it("processes simple console.log completion", () => {
8- const testCase: CompletionTestCase = {
9- original: "console.log(|cur||till|)",
10- completion: '"foo,", bar',
11- };
12-
13- expect(processTestCase(testCase)).toEqual({
14- input: {
15- lastLineOfCompletionText: '"foo,", bar',
16- currentText: ")",
17- cursorPosition: "console.log(".length,
18- },
19- expectedResult: {
20- completionText: '"foo,", bar',
21- },
22- });
23- });
24-
25- it("processes simple console.log completion with overwriting", () => {
26- const testCase: CompletionTestCase = {
27- original: "console.log(|cur|)|till|",
28- completion: '"foo,", bar);',
29- };
30-
31- expect(processTestCase(testCase)).toEqual({
32- input: {
33- lastLineOfCompletionText: '"foo,", bar);',
34- currentText: ")",
35- cursorPosition: "console.log(".length,
36- },
37- expectedResult: {
38- completionText: '"foo,", bar);',
39- range: {
40- start: "console.log(".length,
41- end: "console.log()".length,
42- },
43- },
44- });
45- });
46-
47- it("partially applying completion", () => {
48- const testCase: CompletionTestCase = {
49- original: '|cur||till|fetch("https://example.com");',
50- completion: 'await fetch("https://example.com");',
51- appliedCompletion: "await ",
52- };
53-
54- expect(processTestCase(testCase)).toEqual({
55- input: {
56- lastLineOfCompletionText: 'await fetch("https://example.com");',
57- currentText: 'fetch("https://example.com");',
58- cursorPosition: 0,
59- },
60- expectedResult: {
61- completionText: "await ",
62- },
63- });
64- });
65-});
added core/autocomplete/util/completionTestUtils.vitest.ts +66 −0
@@ -0,0 +1,66 @@
1+import { describe, expect, it } from "vitest";
2+import {
3+ processTestCase,
4+ type CompletionTestCase,
5+} from "./completionTestUtils";
6+
7+describe("processTestCase utility", () => {
8+ it("processes simple console.log completion", () => {
9+ const testCase: CompletionTestCase = {
10+ original: "console.log(|cur||till|)",
11+ completion: '"foo,", bar',
12+ };
13+
14+ expect(processTestCase(testCase)).toEqual({
15+ input: {
16+ lastLineOfCompletionText: '"foo,", bar',
17+ currentText: ")",
18+ cursorPosition: "console.log(".length,
19+ },
20+ expectedResult: {
21+ completionText: '"foo,", bar',
22+ },
23+ });
24+ });
25+
26+ it("processes simple console.log completion with overwriting", () => {
27+ const testCase: CompletionTestCase = {
28+ original: "console.log(|cur|)|till|",
29+ completion: '"foo,", bar);',
30+ };
31+
32+ expect(processTestCase(testCase)).toEqual({
33+ input: {
34+ lastLineOfCompletionText: '"foo,", bar);',
35+ currentText: ")",
36+ cursorPosition: "console.log(".length,
37+ },
38+ expectedResult: {
39+ completionText: '"foo,", bar);',
40+ range: {
41+ start: "console.log(".length,
42+ end: "console.log()".length,
43+ },
44+ },
45+ });
46+ });
47+
48+ it("partially applying completion", () => {
49+ const testCase: CompletionTestCase = {
50+ original: '|cur||till|fetch("https://example.com");',
51+ completion: 'await fetch("https://example.com");',
52+ appliedCompletion: "await ",
53+ };
54+
55+ expect(processTestCase(testCase)).toEqual({
56+ input: {
57+ lastLineOfCompletionText: 'await fetch("https://example.com");',
58+ currentText: 'fetch("https://example.com");',
59+ cursorPosition: 0,
60+ },
61+ expectedResult: {
62+ completionText: "await ",
63+ },
64+ });
65+ });
66+});
deleted core/autocomplete/util/processSingleLineCompletion.test.ts +0 −95
@@ -1,95 +0,0 @@
1-import { processTestCase } from "./completionTestUtils";
2-import { processSingleLineCompletion } from "./processSingleLineCompletion";
3-
4-describe("processSingleLineCompletion", () => {
5- it("should handle simple end of line completion", () => {
6- const testCase = processTestCase({
7- original: "console.log(|cur|",
8- completion: '"Hello, world!")',
9- });
10-
11- const result = processSingleLineCompletion(
12- testCase.input.lastLineOfCompletionText,
13- testCase.input.currentText,
14- testCase.input.cursorPosition,
15- );
16-
17- expect(result).toEqual(testCase.expectedResult);
18- });
19-
20- it("should handle midline insert repeating the end of line", () => {
21- const testCase = processTestCase({
22- original: "console.log(|cur|);|till|",
23- completion: '"Hello, world!");',
24- });
25-
26- const result = processSingleLineCompletion(
27- testCase.input.lastLineOfCompletionText,
28- testCase.input.currentText,
29- testCase.input.cursorPosition,
30- );
31-
32- expect(result).toEqual(testCase.expectedResult);
33- });
34-
35- it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
36- const testCase = processTestCase({
37- original: "console.log(|cur|)|till|",
38- completion: '"Hello, world!");',
39- });
40-
41- const result = processSingleLineCompletion(
42- testCase.input.lastLineOfCompletionText,
43- testCase.input.currentText,
44- testCase.input.cursorPosition,
45- );
46-
47- expect(result).toEqual(testCase.expectedResult);
48- });
49-
50- it("should handle simple midline insert", () => {
51- const testCase = processTestCase({
52- original: "console.log(|cur|)",
53- completion: '"Hello, world!"',
54- });
55-
56- const result = processSingleLineCompletion(
57- testCase.input.lastLineOfCompletionText,
58- testCase.input.currentText,
59- testCase.input.cursorPosition,
60- );
61-
62- expect(result).toEqual(testCase.expectedResult);
63- });
64-
65- it("should handle complex dif with addition in the beginning", () => {
66- const testCase = processTestCase({
67- original: 'console.log(|cur||till|, "param1", )', // TODO
68- completion: '"Hello world!", "param1", param1);',
69- appliedCompletion: '"Hello world!"',
70- });
71-
72- const result = processSingleLineCompletion(
73- testCase.input.lastLineOfCompletionText,
74- testCase.input.currentText,
75- testCase.input.cursorPosition,
76- );
77-
78- expect(result).toEqual(testCase.expectedResult);
79- });
80-
81- it("should handle simple insertion even with random equality", () => {
82- const testCase = processTestCase({
83- original: 'print(f"Foobar length: |cur||till|")',
84- completion: "{len(foobar)}",
85- });
86-
87- const result = processSingleLineCompletion(
88- testCase.input.lastLineOfCompletionText,
89- testCase.input.currentText,
90- testCase.input.cursorPosition,
91- );
92-
93- expect(result).toEqual(testCase.expectedResult);
94- });
95-});
added core/autocomplete/util/processSingleLineCompletion.vitest.ts +96 −0
@@ -0,0 +1,96 @@
1+import { describe, expect, it } from "vitest";
2+import { processTestCase } from "./completionTestUtils";
3+import { processSingleLineCompletion } from "./processSingleLineCompletion";
4+
5+describe("processSingleLineCompletion", () => {
6+ it("should handle simple end of line completion", () => {
7+ const testCase = processTestCase({
8+ original: "console.log(|cur|",
9+ completion: '"Hello, world!")',
10+ });
11+
12+ const result = processSingleLineCompletion(
13+ testCase.input.lastLineOfCompletionText,
14+ testCase.input.currentText,
15+ testCase.input.cursorPosition,
16+ );
17+
18+ expect(result).toEqual(testCase.expectedResult);
19+ });
20+
21+ it("should handle midline insert repeating the end of line", () => {
22+ const testCase = processTestCase({
23+ original: "console.log(|cur|);|till|",
24+ completion: '"Hello, world!");',
25+ });
26+
27+ const result = processSingleLineCompletion(
28+ testCase.input.lastLineOfCompletionText,
29+ testCase.input.currentText,
30+ testCase.input.cursorPosition,
31+ );
32+
33+ expect(result).toEqual(testCase.expectedResult);
34+ });
35+
36+ it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
37+ const testCase = processTestCase({
38+ original: "console.log(|cur|)|till|",
39+ completion: '"Hello, world!");',
40+ });
41+
42+ const result = processSingleLineCompletion(
43+ testCase.input.lastLineOfCompletionText,
44+ testCase.input.currentText,
45+ testCase.input.cursorPosition,
46+ );
47+
48+ expect(result).toEqual(testCase.expectedResult);
49+ });
50+
51+ it("should handle simple midline insert", () => {
52+ const testCase = processTestCase({
53+ original: "console.log(|cur|)",
54+ completion: '"Hello, world!"',
55+ });
56+
57+ const result = processSingleLineCompletion(
58+ testCase.input.lastLineOfCompletionText,
59+ testCase.input.currentText,
60+ testCase.input.cursorPosition,
61+ );
62+
63+ expect(result).toEqual(testCase.expectedResult);
64+ });
65+
66+ it("should handle complex dif with addition in the beginning", () => {
67+ const testCase = processTestCase({
68+ original: 'console.log(|cur||till|, "param1", )', // TODO
69+ completion: '"Hello world!", "param1", param1);',
70+ appliedCompletion: '"Hello world!"',
71+ });
72+
73+ const result = processSingleLineCompletion(
74+ testCase.input.lastLineOfCompletionText,
75+ testCase.input.currentText,
76+ testCase.input.cursorPosition,
77+ );
78+
79+ expect(result).toEqual(testCase.expectedResult);
80+ });
81+
82+ it("should handle simple insertion even with random equality", () => {
83+ const testCase = processTestCase({
84+ original: 'print(f"Foobar length: |cur||till|")',
85+ completion: "{len(foobar)}",
86+ });
87+
88+ const result = processSingleLineCompletion(
89+ testCase.input.lastLineOfCompletionText,
90+ testCase.input.currentText,
91+ testCase.input.cursorPosition,
92+ );
93+
94+ expect(result).toEqual(testCase.expectedResult);
95+ });
96+});
modified core/autocomplete/util/types.ts +1 −1
@@ -41,5 +41,5 @@
4141 gitRepo?: string;
4242 completionId: string;
4343 uniqueId: string;
44- timestamp: number;
44+ timestamp: string;
4545 }
added core/codeRenderer/CodeRenderer.ts +379 −0
@@ -0,0 +1,379 @@
1+/**
2+ * CodeRenderer is a class that, when given a code string,
3+ * highlights the code string using shiki and
4+ * returns a svg representation of it.
5+ * We could technically just call shiki's methods to do a
6+ * one-liner syntax highlighting code, but
7+ * a separate class for this is useful because
8+ * we rarely ever need syntax highlighting outside of
9+ * creating a render of it.
10+ */
11+import {
12+ transformerMetaHighlight,
13+ transformerNotationDiff,
14+ transformerNotationFocus,
15+ transformerNotationHighlight,
16+} from "@shikijs/transformers";
17+import { JSDOM } from "jsdom";
18+import {
19+ BundledLanguage,
20+ BundledTheme,
21+ getSingletonHighlighter,
22+ Highlighter,
23+} from "shiki";
24+import { escapeForSVG, kebabOfStr } from "../util/text";
25+
26+interface CodeRendererOptions {
27+ themesDir?: string;
28+ theme?: string;
29+}
30+
31+interface HTMLOptions {
32+ theme?: string;
33+ customCSS?: string;
34+ containerClass?: string;
35+}
36+
37+interface ConversionOptions extends HTMLOptions {
38+ transparent?: boolean;
39+ imageType: "svg";
40+}
41+
42+interface Dimensions {
43+ width: number;
44+ height: number;
45+}
46+
47+type DataUri = PngUri | SvgUri;
48+type PngUri = string;
49+type SvgUri = string;
50+
51+export class CodeRenderer {
52+ private static instance: CodeRenderer;
53+ private currentTheme: string = "dark-plus";
54+ private editorBackground: string = "#000000";
55+ private editorForeground: string = "#FFFFFF";
56+ private editorLineHighlight: string = "#000000";
57+ private highlighter: Highlighter | null = null;
58+
59+ private constructor() {}
60+
61+ static getInstance(): CodeRenderer {
62+ if (!CodeRenderer.instance) {
63+ CodeRenderer.instance = new CodeRenderer();
64+ }
65+ return CodeRenderer.instance;
66+ }
67+
68+ public async setTheme(themeName: string): Promise<void> {
69+ if (
70+ this.themeExists(kebabOfStr(themeName)) ||
71+ themeName === "Default Dark Modern"
72+ ) {
73+ this.currentTheme =
74+ themeName === "Default Dark Modern"
75+ ? "dark-plus"
76+ : kebabOfStr(themeName);
77+
78+ this.highlighter = await getSingletonHighlighter({
79+ langs: ["typescript"],
80+ themes: [this.currentTheme],
81+ });
82+
83+ const th = this.highlighter.getTheme(this.currentTheme);
84+
85+ this.editorBackground = th.bg;
86+ this.editorForeground = th.fg;
87+ this.editorLineHighlight =
88+ th.colors!["editor.lineHighlightBackground"] ?? "#000000";
89+ } else {
90+ this.currentTheme = "dark-plus";
91+ }
92+ }
93+
94+ async init(): Promise<void> {}
95+
96+ async close(): Promise<void> {}
97+
98+ themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
99+ const themeArray: BundledTheme[] = [
100+ "andromeeda",
101+ "aurora-x",
102+ "ayu-dark",
103+ "catppuccin-frappe",
104+ "catppuccin-latte",
105+ "catppuccin-macchiato",
106+ "catppuccin-mocha",
107+ "dark-plus",
108+ "dracula",
109+ "dracula-soft",
110+ "everforest-dark",
111+ "everforest-light",
112+ "github-dark",
113+ "github-dark-default",
114+ "github-dark-dimmed",
115+ "github-dark-high-contrast",
116+ "github-light",
117+ "github-light-default",
118+ "github-light-high-contrast",
119+ "gruvbox-dark-hard",
120+ "gruvbox-dark-medium",
121+ "gruvbox-dark-soft",
122+ "gruvbox-light-hard",
123+ "gruvbox-light-medium",
124+ "gruvbox-light-soft",
125+ "houston",
126+ "kanagawa-dragon",
127+ "kanagawa-lotus",
128+ "kanagawa-wave",
129+ "laserwave",
130+ "light-plus",
131+ "material-theme",
132+ "material-theme-darker",
133+ "material-theme-lighter",
134+ "material-theme-ocean",
135+ "material-theme-palenight",
136+ "min-dark",
137+ "min-light",
138+ "monokai",
139+ "night-owl",
140+ "nord",
141+ "one-dark-pro",
142+ "one-light",
143+ "plastic",
144+ "poimandres",
145+ "red",
146+ "rose-pine",
147+ "rose-pine-dawn",
148+ "rose-pine-moon",
149+ "slack-dark",
150+ "slack-ochin",
151+ "snazzy-light",
152+ "solarized-dark",
153+ "solarized-light",
154+ "synthwave-84",
155+ "tokyo-night",
156+ "vesper",
157+ "vitesse-black",
158+ "vitesse-dark",
159+ "vitesse-light",
160+ ];
161+
162+ return themeArray.includes(themeNameKebab as BundledTheme);
163+ }
164+
165+ async highlightCode(
166+ code: string,
167+ language: string = "javascript",
168+ currLineOffsetFromTop: number,
169+ ): Promise<string> {
170+ const annotatedCode = code
171+ .split("\n")
172+ .map((line, i) =>
173+ i === currLineOffsetFromTop
174+ ? line + " \/\/ \[\!code highlight\]"
175+ : line,
176+ )
177+ .join("\n");
178+
179+ await this.highlighter!.loadLanguage(language as BundledLanguage);
180+
181+ return this.highlighter!.codeToHtml(annotatedCode, {
182+ lang: language,
183+ theme: this.currentTheme,
184+ transformers: [
185+ // transformerColorizedBrackets(),
186+ transformerMetaHighlight(),
187+ transformerNotationHighlight(),
188+ transformerNotationDiff(),
189+ transformerNotationFocus(),
190+ ],
191+ });
192+ }
193+
194+ async convertToSVG(
195+ code: string,
196+ language: string = "javascript",
197+ fontSize: number,
198+ fontFamily: string,
199+ dimensions: Dimensions,
200+ lineHeight: number,
201+ options: ConversionOptions,
202+ currLineOffsetFromTop: number,
203+ ): Promise<Buffer> {
204+ const strokeWidth = 1;
205+ const highlightedCodeHtml = await this.highlightCode(
206+ code,
207+ language,
208+ currLineOffsetFromTop,
209+ );
210+ // console.log(highlightedCodeHtml);
211+
212+ const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
213+ highlightedCodeHtml,
214+ fontSize,
215+ fontFamily,
216+ lineHeight,
217+ dimensions,
218+ );
219+ const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
220+
221+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}" shape-rendering="crispEdges">
222+ <style>
223+ :root {
224+ --purple: rgb(112, 114, 209);
225+ --green: rgb(136, 194, 163);
226+ --blue: rgb(107, 166, 205);
227+ }
228+ </style>
229+ <g>
230+ <rect x="0" y="0" rx="10" ry="10" width="${dimensions.width}" height="${dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
231+ ${lineBackgrounds}
232+ ${guts}
233+ </g>
234+</svg>`;
235+ console.log(svg);
236+
237+ return Buffer.from(svg, "utf8");
238+ }
239+
240+ convertShikiHtmlToSvgGut(
241+ shikiHtml: string,
242+ fontSize: number,
243+ fontFamily: string,
244+ lineHeight: number,
245+ dimensions: Dimensions,
246+ ): { guts: string; lineBackgrounds: string } {
247+ const dom = new JSDOM(shikiHtml);
248+ const document = dom.window.document;
249+
250+ const lines = Array.from(document.querySelectorAll(".line"));
251+ const svgLines = lines.map((line, index) => {
252+ const spans = Array.from(line.childNodes)
253+ .map((node) => {
254+ if (node.nodeType === 3) {
255+ return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
256+ }
257+
258+ const el = node as HTMLElement;
259+ const style = el.getAttribute("style") || "";
260+ const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
261+ const classes = el.getAttribute("class") || "";
262+ let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
263+ if (classes.includes("highlighted")) {
264+ fill = ` fill="${this.editorLineHighlight}"`;
265+ }
266+ const content = el.textContent || "";
267+ return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
268+ })
269+ .join("");
270+
271+ // Typography notes:
272+ // Each line of code is a <text> inside a <rect>.
273+ // Math becomes interesting here; the y value is actually aligned to the topmost border.
274+ // So y = 0 will have the rect be flush with the top border.
275+ // More importantly, text will also be positioned that way.
276+ // Since y = 0 is the axis the text will align itself to, the default settings will actually have the text sitting "on top of" the y = 0 axis, which effectively shifts them up.
277+ // To prevent this, we want the alignment axis to be at the middle of each rect, and have the text align itself vertically to the center (skwered by the axis).
278+ // The first step is to add lineHeight / 2 to move the axis down.
279+ // The second step is to add 'dominant-baseline="central"' to vertically center the text.
280+ // Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
281+ const y = index * lineHeight + lineHeight / 2;
282+ return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
283+ });
284+
285+ const lineBackgrounds = lines
286+ .map((line, index) => {
287+ const classes = line?.getAttribute("class") || "";
288+ const bgColor = classes.includes("highlighted")
289+ ? this.editorLineHighlight
290+ : this.editorBackground;
291+ const y = index * lineHeight;
292+ const isFirst = index === 0;
293+ const isLast = index === lines.length - 1;
294+ const radius = 10;
295+ // SVG notes:
296+ // By default SVGs have anti-aliasing on.
297+ // This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
298+ // Turning it off with 'shape-rendering="crispEdges"' solves the issue.
299+ return isFirst
300+ ? `<path d="M ${0} ${y + lineHeight}
301+ L ${0} ${y + radius}
302+ Q ${0} ${y} ${radius} ${y}
303+ L ${dimensions.width - radius} ${y}
304+ Q ${dimensions.width} ${y} ${dimensions.width} ${y + radius}
305+ L ${dimensions.width} ${y + lineHeight}
306+ Z"
307+ fill="${bgColor}" />`
308+ : isLast
309+ ? `<path d="M ${0} ${y}
310+ L ${0} ${y + lineHeight - radius}
311+ Q ${0} ${y + lineHeight} ${radius} ${y + lineHeight}
312+ L ${dimensions.width - radius} ${y + lineHeight}
313+ Q ${dimensions.width} ${y + lineHeight} ${dimensions.width} ${y + lineHeight - 10}
314+ L ${dimensions.width} ${y}
315+ Z"
316+ fill="${bgColor}" />`
317+ : `<rect x="0" y="${y}" rx="${radius}" ry="${radius}" width="100%" height="${lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
318+ })
319+ .join("\n");
320+
321+ return {
322+ guts: svgLines.join("\n"),
323+ lineBackgrounds,
324+ };
325+ }
326+
327+ getBackgroundColor(shikiHtml: string): string {
328+ const dom = new JSDOM(shikiHtml);
329+ const document = dom.window.document;
330+
331+ const preElement = document.querySelector("pre");
332+ let backgroundColor = "#333333"; // Default white background
333+ if (preElement) {
334+ const style = preElement.getAttribute("style") || "";
335+ const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
336+ if (bgColorMatch) {
337+ backgroundColor = bgColorMatch[1];
338+ }
339+ }
340+
341+ return backgroundColor;
342+ }
343+
344+ async getDataUri(
345+ code: string,
346+ language: string = "javascript",
347+ fontSize: number,
348+ fontFamily: string,
349+ dimensions: Dimensions,
350+ lineHeight: number,
351+ options: ConversionOptions,
352+ currLineOffsetFromTop: number,
353+ ): Promise<DataUri> {
354+ switch (options.imageType) {
355+ // case "png":
356+ // const pngBuffer = await this.convertToPNG(
357+ // code,
358+ // language,
359+ // fontSize,
360+ // dimensions,
361+ // lineHeight,
362+ // options,
363+ // );
364+ // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
365+ case "svg":
366+ const svgBuffer = await this.convertToSVG(
367+ code,
368+ language,
369+ fontSize,
370+ fontFamily,
371+ dimensions,
372+ lineHeight,
373+ options,
374+ currLineOffsetFromTop,
375+ );
376+ return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
377+ }
378+ }
379+}
deleted core/commands/index.ts +0 −87
@@ -1,87 +0,0 @@
1-import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
2-import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
3-import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
4-import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
5-import { renderChatMessage } from "../util/messageContent";
6-
7-import SlashCommands from "./slash";
8-
9-export function slashFromCustomCommand(
10- customCommand: CustomCommand,
11-): SlashCommand {
12- const commandName = customCommand.name.startsWith("/")
13- ? customCommand.name.substring(1)
14- : customCommand.name;
15- return {
16- name: commandName,
17- description: customCommand.description ?? "",
18- prompt: customCommand.prompt,
19- run: async function* ({
20- input,
21- llm,
22- history,
23- ide,
24- completionOptions,
25- config,
26- selectedCode,
27- fetch,
28- }) {
29- // Render prompt template
30- let renderedPrompt: string;
31- if (customCommand.prompt.includes("{{{ input }}}")) {
32- renderedPrompt = await renderTemplatedString(
33- customCommand.prompt,
34- ide.readFile.bind(ide),
35- { input },
36- );
37- } else {
38- const renderedPromptFile = await renderPromptFileV2(
39- customCommand.prompt,
40- {
41- config,
42- llm,
43- ide,
44- selectedCode,
45- fetch,
46- fullInput: input,
47- embeddingsProvider: config.modelsByRole.embed[0],
48- reranker: config.modelsByRole.rerank[0],
49- },
50- );
51-
52- renderedPrompt = renderedPromptFile[1];
53- }
54-
55- // Replaces slash command messages with the rendered prompt
56- // which INCLUDES the input
57- const messages = replaceSlashCommandWithPromptInChatHistory(
58- history,
59- commandName,
60- renderedPrompt,
61- undefined,
62- );
63-
64- for await (const chunk of llm.streamChat(
65- messages,
66- new AbortController().signal,
67- completionOptions,
68- )) {
69- yield renderChatMessage(chunk);
70- }
71- },
72- };
73-}
74-
75-export function slashCommandFromDescription(
76- desc: SlashCommandDescription,
77-): SlashCommand | undefined {
78- const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
79- if (!cmd) {
80- return undefined;
81- }
82- return {
83- ...cmd,
84- params: desc.params,
85- description: desc.description ?? cmd.description,
86- };
87-}
added core/commands/slash/built-in-legacy/cmd.ts +62 −0
@@ -0,0 +1,62 @@
1+import { streamLines } from "../../../diff/util.js";
2+import { SlashCommand } from "../../../index.js";
3+import { removeQuotesAndEscapes } from "../../../util/index.js";
4+
5+function commandIsPotentiallyDangerous(command: string) {
6+ return (
7+ command.includes("rm -rf") ||
8+ command.includes("sudo") ||
9+ command.includes("cd / ")
10+ );
11+}
12+
13+const GenerateTerminalCommand: SlashCommand = {
14+ name: "cmd",
15+ description: "Generate a shell command",
16+ run: async function* ({ ide, llm, input }) {
17+ if (input.trim() === "") {
18+ yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'.";
19+ return;
20+ }
21+
22+ const gen = llm.streamComplete(
23+ `The user has made a request to run a shell command. Their description of what it should do is:
24+
25+"${input}"
26+
27+Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
28+ new AbortController().signal,
29+ );
30+
31+ const lines = streamLines(gen);
32+ let cmd = "";
33+ for await (const line of lines) {
34+ console.log(line);
35+ if (line.startsWith("```") && line.endsWith("```")) {
36+ cmd = line.split(" ").slice(1).join(" ").slice(0, -3);
37+ break;
38+ }
39+
40+ if (
41+ line.startsWith(">") ||
42+ line.startsWith("``") ||
43+ line.startsWith("\\begin{") ||
44+ line.trim() === ""
45+ ) {
46+ continue;
47+ }
48+
49+ cmd = removeQuotesAndEscapes(line.trim());
50+ break;
51+ }
52+
53+ yield `Generated shell command: ${cmd}`;
54+ if (commandIsPotentiallyDangerous(cmd)) {
55+ yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal.";
56+ } else {
57+ await ide.runCommand(cmd);
58+ }
59+ },
60+};
61+
62+export default GenerateTerminalCommand;
added core/commands/slash/built-in-legacy/commit.ts +26 −0
@@ -0,0 +1,26 @@
1+import { SlashCommand } from "../../../index.js";
2+import { renderChatMessage } from "../../../util/messageContent.js";
3+
4+const CommitMessageCommand: SlashCommand = {
5+ name: "commit",
6+ description: "Generate a commit message for current changes",
7+ run: async function* ({ ide, llm, params, abortController }) {
8+ const includeUnstaged = params?.includeUnstaged ?? false;
9+ const diff = await ide.getDiff(includeUnstaged);
10+
11+ if (diff.length === 0) {
12+ yield "No changes detected. Make sure you are in a git repository with current changes.";
13+ return;
14+ }
15+
16+ const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
17+ for await (const chunk of llm.streamChat(
18+ [{ role: "user", content: prompt }],
19+ abortController.signal,
20+ )) {
21+ yield renderChatMessage(chunk);
22+ }
23+ },
24+};
25+
26+export default CommitMessageCommand;
added core/commands/slash/built-in-legacy/draftIssue.ts +62 −0
@@ -0,0 +1,62 @@
1+import { ChatMessage, SlashCommand } from "../../../index.js";
2+import { removeQuotesAndEscapes } from "../../../util/index.js";
3+import { renderChatMessage } from "../../../util/messageContent.js";
4+
5+const PROMPT = (
6+ input: string,
7+ title: string,
8+) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
9+- Be descriptive but do not make up details
10+- If the the user request includes any code snippets that are relevant, reference them in code blocks
11+- Describe step by step how to reproduce the problem
12+- Describe the ideal solution to the problem
13+- Describe the expected behavior after the issue has been resolved
14+- This issue will be read by a team member
15+- Use markdown formatting, but you do not need to surround the entire body with triple backticks
16+{additional_instructions}
17+
18+Here is the user request: '${input}'
19+
20+Title: ${title}
21+
22+Body:\n\n`;
23+
24+const DraftIssueCommand: SlashCommand = {
25+ name: "issue",
26+ description: "Draft a GitHub issue",
27+ run: async function* ({ input, llm, history, params, abortController }) {
28+ if (params?.repositoryUrl === undefined) {
29+ yield "This command requires a repository URL to be set in the config file.";
30+ return;
31+ }
32+ let title = await llm.complete(
33+ `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
34+ new AbortController().signal,
35+ { maxTokens: 30 },
36+ );
37+
38+ title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
39+ yield title;
40+
41+ let body = "";
42+ const messages: ChatMessage[] = [
43+ ...history.filter((msg) => msg.role !== "system"),
44+ { role: "user", content: PROMPT(input, title) },
45+ ];
46+
47+ for await (const chunk of llm.streamChat(
48+ messages,
49+ abortController.signal,
50+ )) {
51+ body += chunk.content;
52+ yield renderChatMessage(chunk);
53+ }
54+
55+ const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
56+ title,
57+ )}&body=${encodeURIComponent(body)}`;
58+ yield `\n\n[Link to draft of issue](${url})`;
59+ },
60+};
61+
62+export default DraftIssueCommand;
added core/commands/slash/built-in-legacy/http.ts +33 −0
@@ -0,0 +1,33 @@
1+import { streamResponse } from "@continuedev/fetch";
2+import { SlashCommand } from "../../../index.js";
3+import { removeQuotesAndEscapes } from "../../../util/index.js";
4+
5+const HttpSlashCommand: SlashCommand = {
6+ name: "http",
7+ description: "Call an HTTP endpoint to serve response",
8+ run: async function* ({ ide, llm, input, params, fetch }) {
9+ const url = params?.url;
10+ if (!url) {
11+ throw new Error("URL is not defined in params");
12+ }
13+ const response = await fetch(url, {
14+ method: "POST",
15+ headers: {
16+ "Content-Type": "application/json",
17+ },
18+ body: JSON.stringify({
19+ input: removeQuotesAndEscapes(input),
20+ }),
21+ });
22+
23+ // Stream the response
24+ if (response.body === null) {
25+ throw new Error("Response body is null");
26+ }
27+ for await (const chunk of streamResponse(response)) {
28+ yield chunk;
29+ }
30+ },
31+};
32+
33+export default HttpSlashCommand;
added core/commands/slash/built-in-legacy/index.ts +37 −0
@@ -0,0 +1,37 @@
1+import {
2+ SlashCommand,
3+ SlashCommandDescription,
4+ SlashCommandWithSource,
5+} from "../../..";
6+import GenerateTerminalCommand from "./cmd";
7+import CommitMessageCommand from "./commit";
8+import DraftIssueCommand from "./draftIssue";
9+import HttpSlashCommand from "./http";
10+import OnboardSlashCommand from "./onboard";
11+import ReviewMessageCommand from "./review";
12+import ShareSlashCommand from "./share";
13+
14+const LegacyBuiltInSlashCommands: SlashCommand[] = [
15+ DraftIssueCommand,
16+ ShareSlashCommand,
17+ GenerateTerminalCommand,
18+ HttpSlashCommand,
19+ CommitMessageCommand,
20+ ReviewMessageCommand,
21+ OnboardSlashCommand,
22+];
23+
24+export function getLegacyBuiltInSlashCommandFromDescription(
25+ desc: SlashCommandDescription,
26+): SlashCommandWithSource | undefined {
27+ const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
28+ if (!cmd) {
29+ return undefined;
30+ }
31+ return {
32+ ...cmd,
33+ params: desc.params,
34+ description: desc.description ?? cmd.description,
35+ source: "built-in-legacy",
36+ };
37+}
added core/commands/slash/built-in-legacy/onboard.ts +169 −0
@@ -0,0 +1,169 @@
1+import ignore from "ignore";
2+
3+import type { FileType, IDE, SlashCommand } from "../../..";
4+import {
5+ DEFAULT_IGNORE,
6+ getGlobalContinueIgArray,
7+ gitIgArrayFromFile,
8+} from "../../../indexing/ignore";
9+import { renderChatMessage } from "../../../util/messageContent";
10+import {
11+ findUriInDirs,
12+ getUriPathBasename,
13+ joinPathsToUri,
14+} from "../../../util/uri";
15+
16+const LANGUAGE_DEP_MGMT_FILENAMES = [
17+ "package.json", // JavaScript (Node.js)
18+ "requirements.txt", // Python
19+ "Gemfile", // Ruby
20+ "pom.xml", // Java (Maven)
21+ "build.gradle", // Java (Gradle)
22+ "composer.json", // PHP
23+ "Cargo.toml", // Rust
24+ "go.mod", // Go
25+ "packages.config", // C# (.NET)
26+ "*.csproj", // C# (.NET Core)
27+ "pubspec.yaml", // Dart
28+ "Project.toml", // Julia
29+ "mix.exs", // Elixir
30+ "rebar.config", // Erlang
31+ "shard.yml", // Crystal
32+ "Package.swift", // Swift
33+ "dependencies.gradle", // Kotlin (when using Gradle)
34+ "Podfile", // Objective-C/Swift (CocoaPods)
35+ "*.cabal", // Haskell
36+ "dub.json", // D
37+];
38+
39+const MAX_EXPLORE_DEPTH = 2;
40+
41+const OnboardSlashCommand: SlashCommand = {
42+ name: "onboard",
43+ description: "Familiarize yourself with the codebase",
44+ run: async function* ({ llm, ide, abortController }) {
45+ const [workspaceDir] = await ide.getWorkspaceDirs();
46+
47+ const context = await gatherProjectContext(workspaceDir, ide);
48+ const prompt = createOnboardingPrompt(context);
49+
50+ for await (const chunk of llm.streamChat(
51+ [{ role: "user", content: prompt }],
52+ abortController.signal,
53+ )) {
54+ yield renderChatMessage(chunk);
55+ }
56+ },
57+};
58+
59+async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
60+ const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
61+ const entries = await ide.listDir(dir);
62+
63+ const ignoreUri = joinPathsToUri(dir, ".gitignore");
64+ const fileExists = await ide.fileExists(ignoreUri);
65+
66+ if (fileExists) {
67+ const gitIgnore = await ide.readFile(ignoreUri);
68+ const igPatterns = gitIgArrayFromFile(gitIgnore);
69+
70+ ig.add(igPatterns);
71+ }
72+
73+ const workspaceDirs = await ide.getWorkspaceDirs();
74+
75+ const withRelativePaths = entries
76+ .filter(
77+ (entry) =>
78+ entry[1] === (1 as FileType.File) ||
79+ entry[1] === (2 as FileType.Directory),
80+ )
81+ .map((entry) => {
82+ const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
83+ return {
84+ uri: entry[0],
85+ type: entry[1],
86+ basename: getUriPathBasename(entry[0]),
87+ relativePath:
88+ relativePathOrBasename +
89+ (entry[1] === (2 as FileType.Directory) ? "/" : ""),
90+ };
91+ });
92+
93+ return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
94+}
95+
96+async function gatherProjectContext(
97+ workspaceDir: string,
98+ ide: IDE,
99+): Promise<string> {
100+ let context = "";
101+ async function exploreDirectory(dir: string, currentDepth: number = 0) {
102+ if (currentDepth > MAX_EXPLORE_DEPTH) {
103+ return;
104+ }
105+
106+ const entries = await getEntriesFilteredByIgnore(dir, ide);
107+
108+ for (const entry of entries) {
109+ if (entry.type === (2 as FileType.Directory)) {
110+ context += `\nFolder: ${entry.relativePath}\n`;
111+ await exploreDirectory(entry.uri, currentDepth + 1);
112+ } else {
113+ if (entry.basename.toLowerCase() === "readme.md") {
114+ const content = await ide.readFile(entry.uri);
115+ context += `README for ${entry.relativePath}:\n${content}\n\n`;
116+ } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
117+ const content = await ide.readFile(entry.uri);
118+ context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
119+ }
120+ }
121+ }
122+ }
123+
124+ await exploreDirectory(workspaceDir);
125+
126+ return context;
127+}
128+
129+function createOnboardingPrompt(context: string): string {
130+ return `
131+ As a helpful AI assistant, your task is to onboard a new developer to this project.
132+ Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
133+
134+ ${context}
135+
136+ Please provide an overview of the project with the following guidelines:
137+ - Determine the most important folders in the project, at most 10
138+ - Go through each important folder step-by-step:
139+ - Explain what each folder does in isolation by summarzing the README or package.json file, if available
140+ - Mention the most popular or common packages used in that folder and their roles.
141+ - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
142+ - How different parts of the codebase fit together.
143+ - The overall project architecture or design patterns evident from the folder structure and dependencies.
144+ - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
145+
146+ Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
147+
148+ Here is an example of a valid response:
149+
150+ ## Important folders
151+
152+ ### /folder1
153+ - Description: Contains the main application logic.
154+ - Key packages: Express.js for routing, Mongoose for database operations.
155+
156+ #### /folder1/folder2
157+
158+ ## Project Architecture
159+ - The frontend is built using React and Redux for state management.
160+ - The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
161+ - The application follows a Model-View-Controller (MVC) architecture.
162+
163+ ## Additional Insights
164+ - The project is using a monorepo structure.
165+ - The project uses TypeScript for type checking.
166+ `;
167+}
168+
169+export default OnboardSlashCommand;
added core/commands/slash/built-in-legacy/review.ts +55 −0
@@ -0,0 +1,55 @@
1+import { ChatMessage, SlashCommand } from "../../../index.js";
2+import { renderChatMessage } from "../../../util/messageContent.js";
3+
4+const prompt = `
5+ Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
6+
7+ Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements.
8+ Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts.
9+ Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly.
10+ Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability.
11+ Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`;
12+
13+function getLastUserHistory(history: ChatMessage[]): string {
14+ const lastUserHistory = history
15+ .reverse()
16+ .find((message) => message.role === "user");
17+
18+ if (!lastUserHistory) {
19+ return "";
20+ }
21+
22+ if (Array.isArray(lastUserHistory.content)) {
23+ return lastUserHistory.content.reduce(
24+ (acc: string, current: { type: string; text?: string }) => {
25+ return current.type === "text" && current.text
26+ ? acc + current.text
27+ : acc;
28+ },
29+ "",
30+ );
31+ }
32+
33+ return typeof lastUserHistory.content === "string"
34+ ? lastUserHistory.content
35+ : "";
36+}
37+
38+const ReviewMessageCommand: SlashCommand = {
39+ name: "review",
40+ description: "Review code and give feedback",
41+ run: async function* ({ llm, history, abortController }) {
42+ const reviewText = getLastUserHistory(history).replace("\\review", "");
43+
44+ const content = `${prompt} \r\n ${reviewText}`;
45+
46+ for await (const chunk of llm.streamChat(
47+ [{ role: "user", content: content }],
48+ abortController.signal,
49+ )) {
50+ yield renderChatMessage(chunk);
51+ }
52+ },
53+};
54+
55+export default ReviewMessageCommand;
added core/commands/slash/built-in-legacy/share.ts +101 −0
@@ -0,0 +1,101 @@
1+import fs from "fs";
2+import { homedir } from "node:os";
3+import { fileURLToPath, pathToFileURL } from "node:url";
4+import path from "path";
5+
6+import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
7+import { SlashCommand } from "../../../index.js";
8+import { renderChatMessage } from "../../../util/messageContent.js";
9+import { getContinueGlobalPath } from "../../../util/paths.js";
10+
11+// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12+function getOffsetDatetime(date: Date): Date {
13+ const offset = date.getTimezoneOffset();
14+ const offsetHours = Math.floor(offset / 60);
15+ const offsetMinutes = offset % 60;
16+ date.setHours(date.getHours() - offsetHours);
17+ date.setMinutes(date.getMinutes() - offsetMinutes);
18+
19+ return date;
20+}
21+
22+function asBasicISOString(date: Date): string {
23+ const isoString = date.toISOString();
24+
25+ return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26+}
27+
28+function reformatCodeBlocks(msgText: string): string {
29+ const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30+ msgText = msgText.replace(
31+ codeBlockFenceRegex,
32+ (match, metadata, filename, extension) => {
33+ const lang = languageForFilepath(filename);
34+ return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35+ },
36+ );
37+ // Appease the markdown linter
38+ return msgText.replace(/```\n```/g, "```\n\n```");
39+}
40+
41+const ShareSlashCommand: SlashCommand = {
42+ name: "share",
43+ description: "Export the current chat session to markdown",
44+ run: async function* ({ ide, history, params }) {
45+ const now = new Date();
46+
47+ let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
48+
49+ // As currently implemented, the /share command is by definition the last
50+ // message in the chat history, this will omit it
51+ for (const msg of history.slice(0, history.length - 1)) {
52+ let msgText = msg.content;
53+ msgText = renderChatMessage(msg);
54+
55+ if (msg.role === "user" && msgText.search("```") > -1) {
56+ msgText = reformatCodeBlocks(msgText);
57+ }
58+
59+ // format messages as blockquotes
60+ msgText = msgText.replace(/^/gm, "> ");
61+
62+ content += `\n\n#### ${
63+ msg.role === "user" ? "_User_" : "_Assistant_"
64+ }\n\n${msgText}`;
65+ }
66+
67+ let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
68+
69+ if (outputDir.startsWith("~")) {
70+ outputDir = outputDir.replace(/^~/, homedir);
71+ } else if (
72+ outputDir.startsWith("./") ||
73+ outputDir.startsWith(".\\") ||
74+ outputDir === "."
75+ ) {
76+ const workspaceDirs = await ide.getWorkspaceDirs();
77+ // Although the most common situation is to have one directory open in a
78+ // workspace it's also possible to have just a file open without an
79+ // associated directory or to use multi-root workspaces in which multiple
80+ // folders are included. We default to using the first item in the list, if
81+ // it exists.
82+ const workspaceDirectory = workspaceDirs?.[0] || "";
83+ outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
84+ }
85+
86+ if (!fs.existsSync(outputDir)) {
87+ fs.mkdirSync(outputDir, { recursive: true });
88+ }
89+
90+ const dtString = asBasicISOString(getOffsetDatetime(now));
91+ const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
92+
93+ const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
94+ await ide.writeFile(fileUrl, content);
95+ await ide.openFile(fileUrl);
96+
97+ yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
98+ },
99+};
100+
101+export default ShareSlashCommand;
deleted core/commands/slash/cmd.ts +0 −62
@@ -1,62 +0,0 @@
1-import { streamLines } from "../../diff/util.js";
2-import { SlashCommand } from "../../index.js";
3-import { removeQuotesAndEscapes } from "../../util/index.js";
4-
5-function commandIsPotentiallyDangerous(command: string) {
6- return (
7- command.includes("rm -rf") ||
8- command.includes("sudo") ||
9- command.includes("cd / ")
10- );
11-}
12-
13-const GenerateTerminalCommand: SlashCommand = {
14- name: "cmd",
15- description: "Generate a shell command",
16- run: async function* ({ ide, llm, input }) {
17- if (input.trim() === "") {
18- yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'.";
19- return;
20- }
21-
22- const gen = llm.streamComplete(
23- `The user has made a request to run a shell command. Their description of what it should do is:
24-
25-"${input}"
26-
27-Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
28- new AbortController().signal,
29- );
30-
31- const lines = streamLines(gen);
32- let cmd = "";
33- for await (const line of lines) {
34- console.log(line);
35- if (line.startsWith("```") && line.endsWith("```")) {
36- cmd = line.split(" ").slice(1).join(" ").slice(0, -3);
37- break;
38- }
39-
40- if (
41- line.startsWith(">") ||
42- line.startsWith("``") ||
43- line.startsWith("\\begin{") ||
44- line.trim() === ""
45- ) {
46- continue;
47- }
48-
49- cmd = removeQuotesAndEscapes(line.trim());
50- break;
51- }
52-
53- yield `Generated shell command: ${cmd}`;
54- if (commandIsPotentiallyDangerous(cmd)) {
55- yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal.";
56- } else {
57- await ide.runCommand(cmd);
58- }
59- },
60-};
61-
62-export default GenerateTerminalCommand;
deleted core/commands/slash/commit.ts +0 −26
@@ -1,26 +0,0 @@
1-import { SlashCommand } from "../../index.js";
2-import { renderChatMessage } from "../../util/messageContent.js";
3-
4-const CommitMessageCommand: SlashCommand = {
5- name: "commit",
6- description: "Generate a commit message for current changes",
7- run: async function* ({ ide, llm, params }) {
8- const includeUnstaged = params?.includeUnstaged ?? false;
9- const diff = await ide.getDiff(includeUnstaged);
10-
11- if (diff.length === 0) {
12- yield "No changes detected. Make sure you are in a git repository with current changes.";
13- return;
14- }
15-
16- const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
17- for await (const chunk of llm.streamChat(
18- [{ role: "user", content: prompt }],
19- new AbortController().signal,
20- )) {
21- yield renderChatMessage(chunk);
22- }
23- },
24-};
25-
26-export default CommitMessageCommand;
added core/commands/slash/customSlashCommand.ts +15 −0
@@ -0,0 +1,15 @@
1+import { CustomCommand, SlashCommandWithSource } from "../..";
2+
3+export function convertCustomCommandToSlashCommand(
4+ customCommand: CustomCommand,
5+): SlashCommandWithSource {
6+ const commandName = customCommand.name.startsWith("/")
7+ ? customCommand.name.substring(1)
8+ : customCommand.name;
9+ return {
10+ name: commandName,
11+ description: customCommand.description ?? "",
12+ prompt: customCommand.prompt,
13+ source: "json-custom-command",
14+ };
15+}
deleted core/commands/slash/draftIssue.ts +0 −62
@@ -1,62 +0,0 @@
1-import { ChatMessage, SlashCommand } from "../../index.js";
2-import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { renderChatMessage } from "../../util/messageContent.js";
4-
5-const PROMPT = (
6- input: string,
7- title: string,
8-) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
9-- Be descriptive but do not make up details
10-- If the the user request includes any code snippets that are relevant, reference them in code blocks
11-- Describe step by step how to reproduce the problem
12-- Describe the ideal solution to the problem
13-- Describe the expected behavior after the issue has been resolved
14-- This issue will be read by a team member
15-- Use markdown formatting, but you do not need to surround the entire body with triple backticks
16-{additional_instructions}
17-
18-Here is the user request: '${input}'
19-
20-Title: ${title}
21-
22-Body:\n\n`;
23-
24-const DraftIssueCommand: SlashCommand = {
25- name: "issue",
26- description: "Draft a GitHub issue",
27- run: async function* ({ input, llm, history, params }) {
28- if (params?.repositoryUrl === undefined) {
29- yield "This command requires a repository URL to be set in the config file.";
30- return;
31- }
32- let title = await llm.complete(
33- `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
34- new AbortController().signal,
35- { maxTokens: 30 },
36- );
37-
38- title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
39- yield title;
40-
41- let body = "";
42- const messages: ChatMessage[] = [
43- ...history.filter((msg) => msg.role !== "system"),
44- { role: "user", content: PROMPT(input, title) },
45- ];
46-
47- for await (const chunk of llm.streamChat(
48- messages,
49- new AbortController().signal,
50- )) {
51- body += chunk.content;
52- yield renderChatMessage(chunk);
53- }
54-
55- const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
56- title,
57- )}&body=${encodeURIComponent(body)}`;
58- yield `\n\n[Link to draft of issue](${url})`;
59- },
60-};
61-
62-export default DraftIssueCommand;
deleted core/commands/slash/http.ts +0 −33
@@ -1,33 +0,0 @@
1-import { streamResponse } from "@continuedev/fetch";
2-import { SlashCommand } from "../../index.js";
3-import { removeQuotesAndEscapes } from "../../util/index.js";
4-
5-const HttpSlashCommand: SlashCommand = {
6- name: "http",
7- description: "Call an HTTP endpoint to serve response",
8- run: async function* ({ ide, llm, input, params, fetch }) {
9- const url = params?.url;
10- if (!url) {
11- throw new Error("URL is not defined in params");
12- }
13- const response = await fetch(url, {
14- method: "POST",
15- headers: {
16- "Content-Type": "application/json",
17- },
18- body: JSON.stringify({
19- input: removeQuotesAndEscapes(input),
20- }),
21- });
22-
23- // Stream the response
24- if (response.body === null) {
25- throw new Error("Response body is null");
26- }
27- for await (const chunk of streamResponse(response)) {
28- yield chunk;
29- }
30- },
31-};
32-
33-export default HttpSlashCommand;
deleted core/commands/slash/index.ts +0 −17
@@ -1,17 +0,0 @@
1-import GenerateTerminalCommand from "./cmd";
2-import CommitMessageCommand from "./commit";
3-import DraftIssueCommand from "./draftIssue";
4-import HttpSlashCommand from "./http";
5-import OnboardSlashCommand from "./onboard";
6-import ReviewMessageCommand from "./review";
7-import ShareSlashCommand from "./share";
8-
9-export default [
10- DraftIssueCommand,
11- ShareSlashCommand,
12- GenerateTerminalCommand,
13- HttpSlashCommand,
14- CommitMessageCommand,
15- ReviewMessageCommand,
16- OnboardSlashCommand,
17-];
deleted core/commands/slash/mcp.ts +0 −70
@@ -1,70 +0,0 @@
1-import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2-
3-import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
4-import { ChatMessage, SlashCommand } from "../../index.js";
5-import { renderChatMessage } from "../../util/messageContent.js";
6-export function constructMcpSlashCommand(
7- client: Client,
8- name: string,
9- description?: string,
10- args?: string[],
11-): SlashCommand {
12- return {
13- name,
14- description: description ?? "MCP Prompt",
15- params: {},
16- run: async function* (context) {
17- const argsObject: { [key: string]: string } = {};
18- const userInput = context.input.split(" ").slice(1).join(" ");
19- if (args) {
20- args.forEach((arg, i) => {
21- argsObject[arg] = ""; // userInput
22- });
23- }
24-
25- const result = await client.getPrompt({ name, arguments: argsObject });
26- const mcpMessages: PromptMessage[] = result.messages;
27- const messages: ChatMessage[] = mcpMessages.map((msg) => {
28- if (msg.content.type !== "text") {
29- throw new Error(
30- "Continue currently only supports text prompts through MCP",
31- );
32- }
33- return {
34- content: msg.content.text,
35- role: msg.role,
36- };
37- });
38-
39- if (messages.length === 0) {
40- yield "The MCP prompt returned no messages";
41- return;
42- }
43-
44- if (userInput) {
45- const lastMessage = messages.at(-1);
46- if (!lastMessage || lastMessage.role !== "user") {
47- messages.push({
48- role: "user",
49- content: userInput,
50- });
51- } else {
52- let newContent = renderChatMessage(lastMessage);
53- if (newContent) {
54- newContent += "\n\n";
55- }
56- newContent += userInput;
57- lastMessage.content = newContent;
58- }
59- }
60-
61- for await (const chunk of context.llm.streamChat(
62- messages,
63- new AbortController().signal,
64- context.completionOptions,
65- )) {
66- yield renderChatMessage(chunk);
67- }
68- },
69- };
70-}
added core/commands/slash/mcpSlashCommand.ts +34 −0
@@ -0,0 +1,34 @@
1+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2+
3+import { SlashCommandWithSource } from "../../index.js";
4+
5+export function constructMcpSlashCommand(
6+ client: Client,
7+ name: string,
8+ description?: string,
9+ args?: string[],
10+): SlashCommandWithSource {
11+ return {
12+ name,
13+ description: description ?? "MCP Prompt",
14+ source: "mcp-prompt",
15+ params: {},
16+ };
17+}
18+
19+export function stringifyMcpPrompt(
20+ prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
21+): string {
22+ const { messages } = prompt;
23+ let stringified = "";
24+ for (const message of messages) {
25+ if (message.content.type === "text") {
26+ stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
27+ } else {
28+ console.warn(
29+ `MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
30+ );
31+ }
32+ }
33+ return stringified;
34+}
deleted core/commands/slash/onboard.ts +0 −169
@@ -1,169 +0,0 @@
1-import ignore from "ignore";
2-
3-import type { FileType, IDE, SlashCommand } from "../..";
4-import {
5- DEFAULT_IGNORE,
6- getGlobalContinueIgArray,
7- gitIgArrayFromFile,
8-} from "../../indexing/ignore";
9-import { renderChatMessage } from "../../util/messageContent";
10-import {
11- findUriInDirs,
12- getUriPathBasename,
13- joinPathsToUri,
14-} from "../../util/uri";
15-
16-const LANGUAGE_DEP_MGMT_FILENAMES = [
17- "package.json", // JavaScript (Node.js)
18- "requirements.txt", // Python
19- "Gemfile", // Ruby
20- "pom.xml", // Java (Maven)
21- "build.gradle", // Java (Gradle)
22- "composer.json", // PHP
23- "Cargo.toml", // Rust
24- "go.mod", // Go
25- "packages.config", // C# (.NET)
26- "*.csproj", // C# (.NET Core)
27- "pubspec.yaml", // Dart
28- "Project.toml", // Julia
29- "mix.exs", // Elixir
30- "rebar.config", // Erlang
31- "shard.yml", // Crystal
32- "Package.swift", // Swift
33- "dependencies.gradle", // Kotlin (when using Gradle)
34- "Podfile", // Objective-C/Swift (CocoaPods)
35- "*.cabal", // Haskell
36- "dub.json", // D
37-];
38-
39-const MAX_EXPLORE_DEPTH = 2;
40-
41-const OnboardSlashCommand: SlashCommand = {
42- name: "onboard",
43- description: "Familiarize yourself with the codebase",
44- run: async function* ({ llm, ide }) {
45- const [workspaceDir] = await ide.getWorkspaceDirs();
46-
47- const context = await gatherProjectContext(workspaceDir, ide);
48- const prompt = createOnboardingPrompt(context);
49-
50- for await (const chunk of llm.streamChat(
51- [{ role: "user", content: prompt }],
52- new AbortController().signal,
53- )) {
54- yield renderChatMessage(chunk);
55- }
56- },
57-};
58-
59-async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
60- const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
61- const entries = await ide.listDir(dir);
62-
63- const ignoreUri = joinPathsToUri(dir, ".gitignore");
64- const fileExists = await ide.fileExists(ignoreUri);
65-
66- if (fileExists) {
67- const gitIgnore = await ide.readFile(ignoreUri);
68- const igPatterns = gitIgArrayFromFile(gitIgnore);
69-
70- ig.add(igPatterns);
71- }
72-
73- const workspaceDirs = await ide.getWorkspaceDirs();
74-
75- const withRelativePaths = entries
76- .filter(
77- (entry) =>
78- entry[1] === (1 as FileType.File) ||
79- entry[1] === (2 as FileType.Directory),
80- )
81- .map((entry) => {
82- const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
83- return {
84- uri: entry[0],
85- type: entry[1],
86- basename: getUriPathBasename(entry[0]),
87- relativePath:
88- relativePathOrBasename +
89- (entry[1] === (2 as FileType.Directory) ? "/" : ""),
90- };
91- });
92-
93- return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
94-}
95-
96-async function gatherProjectContext(
97- workspaceDir: string,
98- ide: IDE,
99-): Promise<string> {
100- let context = "";
101- async function exploreDirectory(dir: string, currentDepth: number = 0) {
102- if (currentDepth > MAX_EXPLORE_DEPTH) {
103- return;
104- }
105-
106- const entries = await getEntriesFilteredByIgnore(dir, ide);
107-
108- for (const entry of entries) {
109- if (entry.type === (2 as FileType.Directory)) {
110- context += `\nFolder: ${entry.relativePath}\n`;
111- await exploreDirectory(entry.uri, currentDepth + 1);
112- } else {
113- if (entry.basename.toLowerCase() === "readme.md") {
114- const content = await ide.readFile(entry.uri);
115- context += `README for ${entry.relativePath}:\n${content}\n\n`;
116- } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
117- const content = await ide.readFile(entry.uri);
118- context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
119- }
120- }
121- }
122- }
123-
124- await exploreDirectory(workspaceDir);
125-
126- return context;
127-}
128-
129-function createOnboardingPrompt(context: string): string {
130- return `
131- As a helpful AI assistant, your task is to onboard a new developer to this project.
132- Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
133-
134- ${context}
135-
136- Please provide an overview of the project with the following guidelines:
137- - Determine the most important folders in the project, at most 10
138- - Go through each important folder step-by-step:
139- - Explain what each folder does in isolation by summarzing the README or package.json file, if available
140- - Mention the most popular or common packages used in that folder and their roles.
141- - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
142- - How different parts of the codebase fit together.
143- - The overall project architecture or design patterns evident from the folder structure and dependencies.
144- - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
145-
146- Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
147-
148- Here is an example of a valid response:
149-
150- ## Important folders
151-
152- ### /folder1
153- - Description: Contains the main application logic.
154- - Key packages: Express.js for routing, Mongoose for database operations.
155-
156- #### /folder1/folder2
157-
158- ## Project Architecture
159- - The frontend is built using React and Redux for state management.
160- - The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
161- - The application follows a Model-View-Controller (MVC) architecture.
162-
163- ## Additional Insights
164- - The project is using a monorepo structure.
165- - The project uses TypeScript for type checking.
166- `;
167-}
168-
169-export default OnboardSlashCommand;
added core/commands/slash/promptBlockSlashCommand.ts +13 −0
@@ -0,0 +1,13 @@
1+import { Prompt } from "@continuedev/config-yaml";
2+import { SlashCommandWithSource } from "../..";
3+
4+export function convertPromptBlockToSlashCommand(
5+ prompt: Prompt,
6+): SlashCommandWithSource {
7+ return {
8+ name: prompt.name,
9+ description: prompt.description ?? "",
10+ prompt: prompt.prompt,
11+ source: "yaml-prompt-block",
12+ };
13+}
added core/commands/slash/promptFileSlashCommand.ts +21 −0
@@ -0,0 +1,21 @@
1+import { SlashCommandWithSource } from "../..";
2+import { parsePromptFile } from "../../promptFiles/parsePromptFile";
3+
4+export function slashCommandFromPromptFile(
5+ path: string,
6+ content: string,
7+): SlashCommandWithSource | null {
8+ const { name, description, systemMessage, prompt, version } = parsePromptFile(
9+ path,
10+ content,
11+ );
12+
13+ return {
14+ name,
15+ description,
16+ prompt,
17+ source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
18+ promptFile: path,
19+ overrideSystemMessage: systemMessage,
20+ };
21+}
deleted core/commands/slash/review.ts +0 −55
@@ -1,55 +0,0 @@
1-import { ChatMessage, SlashCommand } from "../../index.js";
2-import { renderChatMessage } from "../../util/messageContent.js";
3-
4-const prompt = `
5- Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
6-
7- Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements.
8- Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts.
9- Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly.
10- Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability.
11- Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`;
12-
13-function getLastUserHistory(history: ChatMessage[]): string {
14- const lastUserHistory = history
15- .reverse()
16- .find((message) => message.role === "user");
17-
18- if (!lastUserHistory) {
19- return "";
20- }
21-
22- if (Array.isArray(lastUserHistory.content)) {
23- return lastUserHistory.content.reduce(
24- (acc: string, current: { type: string; text?: string }) => {
25- return current.type === "text" && current.text
26- ? acc + current.text
27- : acc;
28- },
29- "",
30- );
31- }
32-
33- return typeof lastUserHistory.content === "string"
34- ? lastUserHistory.content
35- : "";
36-}
37-
38-const ReviewMessageCommand: SlashCommand = {
39- name: "review",
40- description: "Review code and give feedback",
41- run: async function* ({ llm, history }) {
42- const reviewText = getLastUserHistory(history).replace("\\review", "");
43-
44- const content = `${prompt} \r\n ${reviewText}`;
45-
46- for await (const chunk of llm.streamChat(
47- [{ role: "user", content: content }],
48- new AbortController().signal,
49- )) {
50- yield renderChatMessage(chunk);
51- }
52- },
53-};
54-
55-export default ReviewMessageCommand;
deleted core/commands/slash/share.ts +0 −101
@@ -1,101 +0,0 @@
1-import fs from "fs";
2-import { homedir } from "node:os";
3-import { fileURLToPath, pathToFileURL } from "node:url";
4-import path from "path";
5-
6-import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
7-import { SlashCommand } from "../../index.js";
8-import { renderChatMessage } from "../../util/messageContent.js";
9-import { getContinueGlobalPath } from "../../util/paths.js";
10-
11-// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12-function getOffsetDatetime(date: Date): Date {
13- const offset = date.getTimezoneOffset();
14- const offsetHours = Math.floor(offset / 60);
15- const offsetMinutes = offset % 60;
16- date.setHours(date.getHours() - offsetHours);
17- date.setMinutes(date.getMinutes() - offsetMinutes);
18-
19- return date;
20-}
21-
22-function asBasicISOString(date: Date): string {
23- const isoString = date.toISOString();
24-
25- return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26-}
27-
28-function reformatCodeBlocks(msgText: string): string {
29- const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30- msgText = msgText.replace(
31- codeBlockFenceRegex,
32- (match, metadata, filename, extension) => {
33- const lang = languageForFilepath(filename);
34- return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35- },
36- );
37- // Appease the markdown linter
38- return msgText.replace(/```\n```/g, "```\n\n```");
39-}
40-
41-const ShareSlashCommand: SlashCommand = {
42- name: "share",
43- description: "Export the current chat session to markdown",
44- run: async function* ({ ide, history, params }) {
45- const now = new Date();
46-
47- let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
48-
49- // As currently implemented, the /share command is by definition the last
50- // message in the chat history, this will omit it
51- for (const msg of history.slice(0, history.length - 1)) {
52- let msgText = msg.content;
53- msgText = renderChatMessage(msg);
54-
55- if (msg.role === "user" && msgText.search("```") > -1) {
56- msgText = reformatCodeBlocks(msgText);
57- }
58-
59- // format messages as blockquotes
60- msgText = msgText.replace(/^/gm, "> ");
61-
62- content += `\n\n#### ${
63- msg.role === "user" ? "_User_" : "_Assistant_"
64- }\n\n${msgText}`;
65- }
66-
67- let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
68-
69- if (outputDir.startsWith("~")) {
70- outputDir = outputDir.replace(/^~/, homedir);
71- } else if (
72- outputDir.startsWith("./") ||
73- outputDir.startsWith(".\\") ||
74- outputDir === "."
75- ) {
76- const workspaceDirs = await ide.getWorkspaceDirs();
77- // Although the most common situation is to have one directory open in a
78- // workspace it's also possible to have just a file open without an
79- // associated directory or to use multi-root workspaces in which multiple
80- // folders are included. We default to using the first item in the list, if
81- // it exists.
82- const workspaceDirectory = workspaceDirs?.[0] || "";
83- outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
84- }
85-
86- if (!fs.existsSync(outputDir)) {
87- fs.mkdirSync(outputDir, { recursive: true });
88- }
89-
90- const dtString = asBasicISOString(getOffsetDatetime(now));
91- const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
92-
93- const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
94- await ide.writeFile(fileUrl, content);
95- await ide.openFile(fileUrl);
96-
97- yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
98- },
99-};
100-
101-export default ShareSlashCommand;
deleted core/commands/util.test.ts +0 −149
@@ -1,149 +0,0 @@
1-import { ctxItemToRifWithContents } from "./util";
2-import { ContextItemWithId, RangeInFileWithContents } from "../index";
3-
4-describe("ctxItemToRifWithContents", () => {
5- it("should parse start and end lines from the item name when format is valid", () => {
6- const item: ContextItemWithId = {
7- id: { providerTitle: "testProvider", itemId: "1" },
8- name: "myFunction(10-20)",
9- content: "function content",
10- description: "test description",
11- uri: { type: "file", value: "/path/to/file" },
12- };
13-
14- const expected: RangeInFileWithContents = {
15- filepath: "/path/to/file",
16- range: {
17- start: { line: 10, character: 0 },
18- end: { line: 20, character: 0 },
19- },
20- contents: "function content",
21- };
22-
23- const result = ctxItemToRifWithContents(item);
24- expect(result).toEqual(expected);
25- });
26-
27- it("should set startLine and endLine to 0 when name format is invalid", () => {
28- const item: ContextItemWithId = {
29- id: { providerTitle: "testProvider", itemId: "2" },
30- name: "myFunction",
31- content: "function content",
32- description: "test description",
33- uri: { type: "file", value: "/path/to/file" },
34- };
35-
36- const expected: RangeInFileWithContents = {
37- filepath: "/path/to/file",
38- range: {
39- start: { line: 0, character: 0 },
40- end: { line: 0, character: 0 },
41- },
42- contents: "function content",
43- };
44-
45- const result = ctxItemToRifWithContents(item);
46- expect(result).toEqual(expected);
47- });
48-
49- it("should handle missing uri by setting filepath to empty string", () => {
50- const item: ContextItemWithId = {
51- id: { providerTitle: "testProvider", itemId: "3" },
52- name: "myFunction(10-20)",
53- content: "function content",
54- description: "test description",
55- };
56-
57- const expected: RangeInFileWithContents = {
58- filepath: "",
59- range: {
60- start: { line: 10, character: 0 },
61- end: { line: 20, character: 0 },
62- },
63- contents: "function content",
64- };
65-
66- const result = ctxItemToRifWithContents(item);
67- expect(result).toEqual(expected);
68- });
69-
70- it("should handle uri with undefined value by setting filepath to empty string", () => {
71- const item: ContextItemWithId = {
72- id: { providerTitle: "testProvider", itemId: "4" },
73- name: "myFunction(10-20)",
74- content: "function content",
75- description: "test description",
76- };
77-
78- const expected: RangeInFileWithContents = {
79- filepath: "",
80- range: {
81- start: { line: 10, character: 0 },
82- end: { line: 20, character: 0 },
83- },
84- contents: "function content",
85- };
86-
87- const result = ctxItemToRifWithContents(item);
88- expect(result).toEqual(expected);
89- });
90-
91- it("should handle invalid line numbers gracefully", () => {
92- const item: ContextItemWithId = {
93- id: { providerTitle: "testProvider", itemId: "6" },
94- name: "myFunction(invalid-lines)",
95- content: "function content",
96- description: "test description",
97- uri: { type: "file", value: "/path/to/file" },
98- };
99-
100- const result = ctxItemToRifWithContents(item);
101-
102- expect(result.range.start.line).toBeNaN();
103- expect(result.range.end.line).toBeNaN();
104- });
105-
106- it("should handle missing closing parenthesis in name", () => {
107- const item: ContextItemWithId = {
108- id: { providerTitle: "testProvider", itemId: "7" },
109- name: "myFunction(10-20",
110- content: "function content",
111- description: "test description",
112- uri: { type: "file", value: "/path/to/file" },
113- };
114-
115- const expected: RangeInFileWithContents = {
116- filepath: "/path/to/file",
117- range: {
118- start: { line: 10, character: 0 },
119- end: { line: 20, character: 0 },
120- },
121- contents: "function content",
122- };
123-
124- const result = ctxItemToRifWithContents(item);
125- expect(result).toEqual(expected);
126- });
127-
128- it("should handle name with multiple '-' characters", () => {
129- const item: ContextItemWithId = {
130- id: { providerTitle: "testProvider", itemId: "8" },
131- name: "myFunction(10-20-30)",
132- content: "function content",
133- description: "test description",
134- uri: { type: "file", value: "/path/to/file" },
135- };
136-
137- const expected: RangeInFileWithContents = {
138- filepath: "/path/to/file",
139- range: {
140- start: { line: 10, character: 0 },
141- end: { line: 20, character: 0 },
142- },
143- contents: "function content",
144- };
145-
146- const result = ctxItemToRifWithContents(item);
147- expect(result).toEqual(expected);
148- });
149-});
modified core/commands/util.ts +1 −1
@@ -16,7 +16,7 @@
1616 return {
1717 content: rif.contents,
1818 name: `${basename} ${rangeStr}`,
19- description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
19+ description: `${relativePathOrBasename} ${rangeStr}`,
2020 id: {
2121 providerTitle: "code",
2222 itemId: uuidv4(),
added core/commands/util.vitest.ts +150 −0
@@ -0,0 +1,150 @@
1+import { describe, expect, it } from "vitest";
2+import { ContextItemWithId, RangeInFileWithContents } from "../index";
3+import { ctxItemToRifWithContents } from "./util";
4+
5+describe("ctxItemToRifWithContents", () => {
6+ it("should parse start and end lines from the item name when format is valid", () => {
7+ const item: ContextItemWithId = {
8+ id: { providerTitle: "testProvider", itemId: "1" },
9+ name: "myFunction(10-20)",
10+ content: "function content",
11+ description: "test description",
12+ uri: { type: "file", value: "/path/to/file" },
13+ };
14+
15+ const expected: RangeInFileWithContents = {
16+ filepath: "/path/to/file",
17+ range: {
18+ start: { line: 10, character: 0 },
19+ end: { line: 20, character: 0 },
20+ },
21+ contents: "function content",
22+ };
23+
24+ const result = ctxItemToRifWithContents(item);
25+ expect(result).toEqual(expected);
26+ });
27+
28+ it("should set startLine and endLine to 0 when name format is invalid", () => {
29+ const item: ContextItemWithId = {
30+ id: { providerTitle: "testProvider", itemId: "2" },
31+ name: "myFunction",
32+ content: "function content",
33+ description: "test description",
34+ uri: { type: "file", value: "/path/to/file" },
35+ };
36+
37+ const expected: RangeInFileWithContents = {
38+ filepath: "/path/to/file",
39+ range: {
40+ start: { line: 0, character: 0 },
41+ end: { line: 0, character: 0 },
42+ },
43+ contents: "function content",
44+ };
45+
46+ const result = ctxItemToRifWithContents(item);
47+ expect(result).toEqual(expected);
48+ });
49+
50+ it("should handle missing uri by setting filepath to empty string", () => {
51+ const item: ContextItemWithId = {
52+ id: { providerTitle: "testProvider", itemId: "3" },
53+ name: "myFunction(10-20)",
54+ content: "function content",
55+ description: "test description",
56+ };
57+
58+ const expected: RangeInFileWithContents = {
59+ filepath: "",
60+ range: {
61+ start: { line: 10, character: 0 },
62+ end: { line: 20, character: 0 },
63+ },
64+ contents: "function content",
65+ };
66+
67+ const result = ctxItemToRifWithContents(item);
68+ expect(result).toEqual(expected);
69+ });
70+
71+ it("should handle uri with undefined value by setting filepath to empty string", () => {
72+ const item: ContextItemWithId = {
73+ id: { providerTitle: "testProvider", itemId: "4" },
74+ name: "myFunction(10-20)",
75+ content: "function content",
76+ description: "test description",
77+ };
78+
79+ const expected: RangeInFileWithContents = {
80+ filepath: "",
81+ range: {
82+ start: { line: 10, character: 0 },
83+ end: { line: 20, character: 0 },
84+ },
85+ contents: "function content",
86+ };
87+
88+ const result = ctxItemToRifWithContents(item);
89+ expect(result).toEqual(expected);
90+ });
91+
92+ it("should handle invalid line numbers gracefully", () => {
93+ const item: ContextItemWithId = {
94+ id: { providerTitle: "testProvider", itemId: "6" },
95+ name: "myFunction(invalid-lines)",
96+ content: "function content",
97+ description: "test description",
98+ uri: { type: "file", value: "/path/to/file" },
99+ };
100+
101+ const result = ctxItemToRifWithContents(item);
102+
103+ expect(result.range.start.line).toBeNaN();
104+ expect(result.range.end.line).toBeNaN();
105+ });
106+
107+ it("should handle missing closing parenthesis in name", () => {
108+ const item: ContextItemWithId = {
109+ id: { providerTitle: "testProvider", itemId: "7" },
110+ name: "myFunction(10-20",
111+ content: "function content",
112+ description: "test description",
113+ uri: { type: "file", value: "/path/to/file" },
114+ };
115+
116+ const expected: RangeInFileWithContents = {
117+ filepath: "/path/to/file",
118+ range: {
119+ start: { line: 10, character: 0 },
120+ end: { line: 20, character: 0 },
121+ },
122+ contents: "function content",
123+ };
124+
125+ const result = ctxItemToRifWithContents(item);
126+ expect(result).toEqual(expected);
127+ });
128+
129+ it("should handle name with multiple '-' characters", () => {
130+ const item: ContextItemWithId = {
131+ id: { providerTitle: "testProvider", itemId: "8" },
132+ name: "myFunction(10-20-30)",
133+ content: "function content",
134+ description: "test description",
135+ uri: { type: "file", value: "/path/to/file" },
136+ };
137+
138+ const expected: RangeInFileWithContents = {
139+ filepath: "/path/to/file",
140+ range: {
141+ start: { line: 10, character: 0 },
142+ end: { line: 20, character: 0 },
143+ },
144+ contents: "function content",
145+ };
146+
147+ const result = ctxItemToRifWithContents(item);
148+ expect(result).toEqual(expected);
149+ });
150+});
deleted core/config/ConfigHandler.test.ts +0 −54
@@ -1,54 +0,0 @@
1-import fs from "node:fs";
2-import path from "node:path";
3-
4-import { testConfigHandler } from "../test/fixtures";
5-import { TEST_DIR } from "../test/testDir";
6-import { getConfigTsPath } from "../util/paths";
7-
8-import { defaultConfig } from "./default";
9-
10-describe.skip("Test the ConfigHandler and E2E config loading", () => {
11- test("should show only local profile", () => {
12- const profiles = testConfigHandler.currentOrg.profiles;
13- expect(profiles?.length).toBe(1);
14- expect(profiles?.[0].profileDescription.id).toBe("local");
15-
16- const currentProfile = testConfigHandler.currentProfile;
17- expect(currentProfile?.profileDescription.id).toBe("local");
18- });
19-
20- test("should load the default config successfully", async () => {
21- const result = await testConfigHandler.loadConfig();
22- expect(result.config!.modelsByRole.chat.length).toBe(
23- defaultConfig.models?.length,
24- );
25- });
26-
27- test.skip("should add a system message from config.ts", async () => {
28- const configTs = `export function modifyConfig(config: Config): Config {
29- config.systemMessage = "SYSTEM";
30- return config;
31-}`;
32- fs.writeFileSync(getConfigTsPath(), configTs);
33- await new Promise((resolve) => setTimeout(resolve, 1000));
34- const config = await testConfigHandler.reloadConfig();
35- /**
36- * @ts-ignore is applied because this test is skipped
37- */
38- // @ts-ignore
39- expect(config.systemMessage).toBe("SYSTEM");
40- });
41-
42- test.skip("should acknowledge override from .continuerc.json", async () => {
43- fs.writeFileSync(
44- path.join(TEST_DIR, ".continuerc.json"),
45- JSON.stringify({ systemMessage: "SYSTEM2" }),
46- );
47- const config = await testConfigHandler.reloadConfig();
48- /**
49- * @ts-ignore is applied because this test is skipped
50- */
51- // @ts-ignore
52- expect(config.systemMessage).toBe("SYSTEM2");
53- });
54-});
added core/config/ConfigHandler.vitest.ts +55 −0
@@ -0,0 +1,55 @@
1+import fs from "node:fs";
2+import path from "node:path";
3+
4+import { describe, expect, test } from "vitest";
5+import { testConfigHandler } from "../test/fixtures";
6+import { TEST_DIR } from "../test/testDir";
7+import { getConfigTsPath } from "../util/paths";
8+
9+import { defaultConfig } from "./default";
10+
11+describe.skip("Test the ConfigHandler and E2E config loading", () => {
12+ test("should show only local profile", () => {
13+ const profiles = testConfigHandler.currentOrg.profiles;
14+ expect(profiles?.length).toBe(1);
15+ expect(profiles?.[0].profileDescription.id).toBe("local");
16+
17+ const currentProfile = testConfigHandler.currentProfile;
18+ expect(currentProfile?.profileDescription.id).toBe("local");
19+ });
20+
21+ test("should load the default config successfully", async () => {
22+ const result = await testConfigHandler.loadConfig();
23+ expect(result.config!.modelsByRole.chat.length).toBe(
24+ defaultConfig.models?.length,
25+ );
26+ });
27+
28+ test("should add a system message from config.ts", async () => {
29+ const configTs = `export function modifyConfig(config: Config): Config {
30+ config.systemMessage = "SYSTEM";
31+ return config;
32+}`;
33+ fs.writeFileSync(getConfigTsPath(), configTs);
34+ await new Promise((resolve) => setTimeout(resolve, 1000));
35+ const config = await testConfigHandler.reloadConfig();
36+ /**
37+ * @ts-ignore is applied because this test is skipped
38+ */
39+ // @ts-ignore
40+ expect(config.systemMessage).toBe("SYSTEM");
41+ });
42+
43+ test("should acknowledge override from .continuerc.json", async () => {
44+ fs.writeFileSync(
45+ path.join(TEST_DIR, ".continuerc.json"),
46+ JSON.stringify({ systemMessage: "SYSTEM2" }),
47+ );
48+ const config = await testConfigHandler.reloadConfig();
49+ /**
50+ * @ts-ignore is applied because this test is skipped
51+ */
52+ // @ts-ignore
53+ expect(config.systemMessage).toBe("SYSTEM2");
54+ });
55+});
modified core/config/ProfileLifecycleManager.ts +32 −30
@@ -87,38 +87,40 @@
8787 }
8888
8989 // Set pending config promise
90- this.pendingConfigPromise = new Promise(async (resolve, reject) => {
91- let result: ConfigResult<ContinueConfig>;
92- // This try catch is expected to catch high-level errors that aren't block-specific
93- // Like invalid json, invalid yaml, file read errors, etc.
94- // NOT block-specific loading errors
95- try {
96- result = await this.profileLoader.doLoadConfig();
97- } catch (e) {
98- const message =
99- e instanceof Error
100- ? `${e.message}\n${e.stack ? e.stack : ""}`
101- : "Error loading config";
102- result = {
103- errors: [
104- {
105- fatal: true,
106- message,
107- },
108- ],
109- config: undefined,
110- configLoadInterrupted: true,
111- };
112- }
90+ this.pendingConfigPromise = new Promise((resolve) => {
91+ void (async () => {
92+ let result: ConfigResult<ContinueConfig>;
93+ // This try catch is expected to catch high-level errors that aren't block-specific
94+ // Like invalid json, invalid yaml, file read errors, etc.
95+ // NOT block-specific loading errors
96+ try {
97+ result = await this.profileLoader.doLoadConfig();
98+ } catch (e) {
99+ const message =
100+ e instanceof Error
101+ ? `${e.message}\n${e.stack ? e.stack : ""}`
102+ : "Error loading config";
103+ result = {
104+ errors: [
105+ {
106+ fatal: true,
107+ message,
108+ },
109+ ],
110+ config: undefined,
111+ configLoadInterrupted: true,
112+ };
113+ }
113114
114- if (result.config) {
115- // Add registered context providers
116- result.config.contextProviders = (
117- result.config.contextProviders ?? []
118- ).concat(additionalContextProviders);
119- }
115+ if (result.config) {
116+ // Add registered context providers
117+ result.config.contextProviders = (
118+ result.config.contextProviders ?? []
119+ ).concat(additionalContextProviders);
120+ }
120121
121- resolve(result);
122+ resolve(result);
123+ })();
122124 });
123125
124126 // Wait for the config promise to resolve
modified core/config/load.ts +38 −27
@@ -30,14 +30,12 @@
3030 ModelDescription,
3131 RerankerDescription,
3232 SerializedContinueConfig,
33- SlashCommand,
33+ SlashCommandWithSource,
3434 } from "..";
35-import {
36- slashCommandFromDescription,
37- slashFromCustomCommand,
38-} from "../commands/index";
35+import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
36+import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
37+import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
3938 import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
40-import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
4139 import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
4240 import CustomContextProviderClass from "../context/providers/CustomContextProvider";
4341 import FileContextProvider from "../context/providers/FileContextProvider";
@@ -48,8 +46,7 @@
4846 import CustomLLMClass from "../llm/llms/CustomLLM";
4947 import { LLMReranker } from "../llm/llms/llm";
5048 import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
51-import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
52-import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
49+import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
5350 import { copyOf } from "../util";
5451 import { GlobalContext } from "../util/GlobalContext";
5552 import mergeJson from "../util/merge";
@@ -65,7 +62,8 @@
6562 } from "../util/paths";
6663 import { localPathToUri } from "../util/pathToUri";
6764
68-import { baseToolDefinitions } from "../tools";
65+import { getToolsForIde } from "../tools";
66+import { resolveRelativePathInDir } from "../util/ideUtils";
6967 import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
7068 import {
7169 getModelByRole,
@@ -174,15 +172,15 @@
174172 ide: IDE,
175173 ): Promise<Config> {
176174 // DEPRECATED - load custom slash commands
177- const slashCommands: SlashCommand[] = [];
175+ const slashCommands: SlashCommandWithSource[] = [];
178176 for (const command of initial.slashCommands || []) {
179- const newCommand = slashCommandFromDescription(command);
177+ const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
180178 if (newCommand) {
181179 slashCommands.push(newCommand);
182180 }
183181 }
184182 for (const command of initial.customCommands || []) {
185- slashCommands.push(slashFromCustomCommand(command));
183+ slashCommands.push(convertCustomCommandToSlashCommand(command));
186184 }
187185
188186 // DEPRECATED - load slash commands from v1 prompt files
@@ -194,7 +192,7 @@
194192 );
195193
196194 for (const file of promptFiles) {
197- const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
195+ const slashCommand = slashCommandFromPromptFile(file.path, file.content);
198196 if (slashCommand) {
199197 slashCommands.push(slashCommand);
200198 }
@@ -254,7 +252,10 @@
254252 loadPromptFiles?: boolean;
255253 }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
256254 const errors: ConfigValidationError[] = [];
257-
255+ const workspaceDirs = await ide.getWorkspaceDirs();
256+ const getUriFromPath = (path: string) => {
257+ return resolveRelativePathInDir(path, ide, workspaceDirs);
258+ };
258259 // Auto-detect models
259260 let models: BaseLLM[] = [];
260261 await Promise.all(
@@ -263,6 +264,7 @@
263264 const llm = await llmFromDescription(
264265 desc,
265266 ide.readFile.bind(ide),
267+ getUriFromPath,
266268 uniqueId,
267269 ideSettings,
268270 llmLogger,
@@ -284,6 +286,7 @@
284286 title: modelName,
285287 },
286288 ide.readFile.bind(ide),
289+ getUriFromPath,
287290 uniqueId,
288291 ideSettings,
289292 llmLogger,
@@ -360,6 +363,7 @@
360363 const llm = await llmFromDescription(
361364 desc,
362365 ide.readFile.bind(ide),
366+ getUriFromPath,
363367 uniqueId,
364368 ideSettings,
365369 llmLogger,
@@ -393,13 +397,7 @@
393397 | undefined
394398 )?.params || {};
395399
396- const DEFAULT_CONTEXT_PROVIDERS = [
397- new FileContextProvider({}),
398- // Add codebase provider if indexing is enabled
399- ...(!config.disableIndexing
400- ? [new CodebaseContextProvider(codebaseContextParams)]
401- : []),
402- ];
400+ const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
403401
404402 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
405403 ({ description: { title } }) => title,
@@ -527,9 +525,9 @@
527525 const continueConfig: ContinueConfig = {
528526 ...config,
529527 contextProviders,
530- tools: [...baseToolDefinitions],
528+ tools: await getToolsForIde(ide),
531529 mcpServerStatuses: [],
532- slashCommands: config.slashCommands ?? [],
530+ slashCommands: [],
533531 modelsByRole: {
534532 chat: models,
535533 edit: models,
@@ -551,6 +549,17 @@
551549 rules: [],
552550 };
553551
552+ for (const cmd of config.slashCommands ?? []) {
553+ if ("source" in cmd) {
554+ continueConfig.slashCommands.push(cmd);
555+ } else {
556+ continueConfig.slashCommands.push({
557+ ...cmd,
558+ source: "config-ts-slash-command",
559+ });
560+ }
561+ }
562+
554563 if (config.systemMessage) {
555564 continueConfig.rules.unshift({
556565 rule: config.systemMessage,
@@ -634,6 +643,7 @@
634643 template: llm.template,
635644 completionOptions: llm.completionOptions,
636645 baseAgentSystemMessage: llm.baseAgentSystemMessage,
646+ basePlanSystemMessage: llm.basePlanSystemMessage,
637647 baseChatSystemMessage: llm.baseChatSystemMessage,
638648 requestOptions: llm.requestOptions,
639649 promptTemplates: serializePromptTemplates(llm.promptTemplates),
@@ -641,6 +651,7 @@
641651 roles: llm.roles,
642652 configurationStatus: llm.getConfigurationStatus(),
643653 apiKeyLocation: llm.apiKeyLocation,
654+ envSecretLocations: llm.envSecretLocations,
644655 };
645656 }
646657
@@ -651,9 +662,10 @@
651662 return {
652663 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
653664 completionOptions: final.completionOptions,
654- slashCommands: final.slashCommands?.map(
655- ({ run, ...slashCommandDescription }) => slashCommandDescription,
656- ),
665+ slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
666+ ...rest,
667+ isLegacy: !!run,
668+ })),
657669 contextProviders: final.contextProviders?.map((c) => c.description),
658670 disableIndexing: final.disableIndexing,
659671 disableSessionTitles: final.disableSessionTitles,
@@ -975,7 +987,6 @@
975987
976988 export {
977989 finalToBrowserConfig,
978- intermediateToFinalConfig,
979990 loadContinueConfigFromJson,
980991 type BrowserSerializedContinueConfig,
981992 };
modified core/config/loadLocalAssistants.ts +27 −15
@@ -1,4 +1,5 @@
11 import ignore from "ignore";
2+import * as URI from "uri-js";
23 import { IDE } from "..";
34 import {
45 DEFAULT_IGNORE_DIRS,
@@ -12,18 +13,19 @@
1213 export const ASSISTANTS = "assistants";
1314 export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
1415
15-export function isLocalAssistantFile(uri: string): boolean {
16+export function isLocalDefinitionFile(uri: string): boolean {
1617 if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
1718 return false;
1819 }
1920
20- const normalizedUri = uri.replace(/\\/g, "/");
21+ const normalizedUri = URI.normalize(uri);
2122 return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
2223 }
2324
2425 async function getDefinitionFilesInDir(
2526 ide: IDE,
2627 dir: string,
28+ fileExtType?: "yaml" | "markdown",
2729 ): Promise<{ path: string; content: string }[]> {
2830 try {
2931 const exists = await ide.fileExists(dir);
@@ -40,9 +42,19 @@
4042 overrideDefaultIgnores,
4143 source: "get assistant files",
4244 });
43- const assistantFilePaths = uris.filter(
44- (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
45- );
45+ let assistantFilePaths: string[];
46+ if (fileExtType === "yaml") {
47+ assistantFilePaths = uris.filter(
48+ (p) => p.endsWith(".yaml") || p.endsWith(".yml"),
49+ );
50+ } else if (fileExtType === "markdown") {
51+ assistantFilePaths = uris.filter((p) => p.endsWith(".md"));
52+ } else {
53+ assistantFilePaths = uris.filter(
54+ (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
55+ );
56+ }
57+
4658 const results = assistantFilePaths.map(async (uri) => {
4759 const content = await ide.readFile(uri); // make a try catch
4860 return { path: uri, content };
@@ -57,6 +69,7 @@
5769 export interface LoadAssistantFilesOptions {
5870 includeGlobal: boolean;
5971 includeWorkspace: boolean;
72+ fileExtType?: "yaml" | "markdown";
6073 }
6174
6275 export function getDotContinueSubDirs(
@@ -84,7 +97,7 @@
8497
8598 /**
8699 * This method searches in both ~/.continue and workspace .continue
87- * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
100+ * for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts
88101 */
89102 export async function getAllDotContinueDefinitionFiles(
90103 ide: IDE,
@@ -101,15 +114,14 @@
101114 subDirName,
102115 );
103116
104- // Get all assistant files from the directories
105- const assistantFiles = (
106- await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
117+ // Get all definition files from the directories
118+ const definitionFiles = (
119+ await Promise.all(
120+ fullDirs.map((dir) =>
121+ getDefinitionFilesInDir(ide, dir, options.fileExtType),
122+ ),
123+ )
107124 ).flat();
108125
109- return await Promise.all(
110- assistantFiles.map(async (file) => {
111- const content = await ide.readFile(file.path);
112- return { path: file.path, content };
113- }),
114- );
126+ return definitionFiles;
115127 }
added core/config/loadLocalAssistants.vitest.ts +242 −0
@@ -0,0 +1,242 @@
1+import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+import { walkDirCache } from "../indexing/walkDir";
3+import { testIde } from "../test/fixtures";
4+import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
5+import {
6+ getAllDotContinueDefinitionFiles,
7+ LoadAssistantFilesOptions,
8+} from "./loadLocalAssistants";
9+describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
10+ beforeEach(() => {
11+ setUpTestDir();
12+ walkDirCache.invalidate();
13+
14+ // Add test files to the test directory
15+ addToTestDir([
16+ ".continue/assistants/",
17+ [".continue/assistants/assistant1.yaml", "yaml content 1"],
18+ [".continue/assistants/assistant2.yml", "yaml content 2"],
19+ [".continue/assistants/assistant3.md", "markdown content 1"],
20+ [".continue/assistants/assistant4.txt", "txt content"],
21+ ]);
22+ });
23+
24+ afterEach(() => {
25+ tearDownTestDir();
26+ walkDirCache.invalidate();
27+ });
28+
29+ it("should return only YAML files when fileExtType is 'yaml'", async () => {
30+ const options: LoadAssistantFilesOptions = {
31+ includeGlobal: false, // Only test workspace for simplicity
32+ includeWorkspace: true,
33+ fileExtType: "yaml",
34+ };
35+
36+ const result = await getAllDotContinueDefinitionFiles(
37+ testIde,
38+ options,
39+ "assistants",
40+ );
41+ expect(result).toHaveLength(2);
42+ expect(result.map((f) => f.path.split("/").pop())).toEqual(
43+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
44+ );
45+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
46+ "assistant3.md",
47+ );
48+ });
49+
50+ it("should return only Markdown files when fileExtType is 'markdown'", async () => {
51+ const options: LoadAssistantFilesOptions = {
52+ includeGlobal: false,
53+ includeWorkspace: true,
54+ fileExtType: "markdown",
55+ };
56+
57+ const result = await getAllDotContinueDefinitionFiles(
58+ testIde,
59+ options,
60+ "assistants",
61+ );
62+ expect(result).toHaveLength(1);
63+ expect(result.map((f) => f.path.split("/").pop())).toEqual([
64+ "assistant3.md",
65+ ]);
66+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
67+ "assistant1.yaml",
68+ );
69+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
70+ "assistant2.yml",
71+ );
72+ });
73+
74+ it("should return all supported files when fileExtType is not specified", async () => {
75+ const options: LoadAssistantFilesOptions = {
76+ includeGlobal: false,
77+ includeWorkspace: true,
78+ // fileExtType not specified
79+ };
80+
81+ const result = await getAllDotContinueDefinitionFiles(
82+ testIde,
83+ options,
84+ "assistants",
85+ );
86+ expect(result).toHaveLength(3);
87+ expect(result.map((f) => f.path.split("/").pop())).toEqual(
88+ expect.arrayContaining([
89+ "assistant1.yaml",
90+ "assistant2.yml",
91+ "assistant3.md",
92+ ]),
93+ );
94+ // Should not include .txt files
95+ expect(result.map((f) => f.path.split("/").pop())).not.toContain(
96+ "assistant4.txt",
97+ );
98+ });
99+
100+ it("should respect includeWorkspace option with fileExtType", async () => {
101+ // Test with includeWorkspace: false
102+ const workspaceOffOptions: LoadAssistantFilesOptions = {
103+ includeGlobal: false,
104+ includeWorkspace: false,
105+ fileExtType: "yaml",
106+ };
107+
108+ const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
109+ testIde,
110+ workspaceOffOptions,
111+ "assistants",
112+ );
113+ expect(noWorkspaceResult).toHaveLength(0);
114+
115+ // Test with includeWorkspace: true
116+ const workspaceOnOptions: LoadAssistantFilesOptions = {
117+ includeGlobal: false,
118+ includeWorkspace: true,
119+ fileExtType: "yaml",
120+ };
121+
122+ const workspaceResult = await getAllDotContinueDefinitionFiles(
123+ testIde,
124+ workspaceOnOptions,
125+ "assistants",
126+ );
127+ expect(workspaceResult).toHaveLength(2);
128+ expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
129+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
130+ );
131+ });
132+
133+ it("should return empty array when no files match the specified extension type", async () => {
134+ // Create a test directory with only non-matching files
135+ tearDownTestDir();
136+ walkDirCache.invalidate();
137+ setUpTestDir();
138+ addToTestDir([
139+ ".continue/assistants/",
140+ [".continue/assistants/nonmatch1.txt", "txt content"],
141+ [".continue/assistants/nonmatch2.json", "json content"],
142+ ]);
143+
144+ const options: LoadAssistantFilesOptions = {
145+ includeGlobal: false,
146+ includeWorkspace: true,
147+
148+ fileExtType: "yaml",
149+ };
150+
151+ const result = await getAllDotContinueDefinitionFiles(
152+ testIde,
153+ options,
154+ "assistants",
155+ );
156+ expect(result).toHaveLength(0);
157+ });
158+
159+ it("should handle directories that don't exist", async () => {
160+ // Create a clean test directory without the assistants folder
161+ tearDownTestDir();
162+ setUpTestDir();
163+
164+ const options: LoadAssistantFilesOptions = {
165+ includeGlobal: false,
166+ includeWorkspace: true,
167+ fileExtType: "yaml",
168+ };
169+
170+ const result = await getAllDotContinueDefinitionFiles(
171+ testIde,
172+ options,
173+ "assistants",
174+ );
175+ expect(result).toHaveLength(0);
176+ });
177+
178+ it("should return correct file content", async () => {
179+ const options: LoadAssistantFilesOptions = {
180+ includeGlobal: false,
181+ includeWorkspace: true,
182+ fileExtType: "yaml",
183+ };
184+
185+ const result = await getAllDotContinueDefinitionFiles(
186+ testIde,
187+ options,
188+ "assistants",
189+ );
190+ expect(result).toHaveLength(2);
191+ const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
192+ expect(yamlFile?.content).toBe("yaml content 1");
193+ });
194+
195+ it("should filter by file extension case sensitively", async () => {
196+ // Add files with uppercase extensions
197+ addToTestDir([
198+ [".continue/assistants/assistant5.YAML", "uppercase yaml"],
199+ [".continue/assistants/assistant6.YML", "uppercase yml"],
200+ [".continue/assistants/assistant7.MD", "uppercase md"],
201+ ]);
202+
203+ const yamlOptions: LoadAssistantFilesOptions = {
204+ includeGlobal: false,
205+ includeWorkspace: true,
206+ fileExtType: "yaml",
207+ };
208+
209+ const yamlResult = await getAllDotContinueDefinitionFiles(
210+ testIde,
211+ yamlOptions,
212+ "assistants",
213+ );
214+ // Should only get lowercase extensions (current implementation)
215+ expect(yamlResult).toHaveLength(2);
216+ expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
217+ expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
218+ );
219+ expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
220+ "assistant5.YAML",
221+ );
222+
223+ const markdownOptions: LoadAssistantFilesOptions = {
224+ includeGlobal: false,
225+ includeWorkspace: true,
226+ fileExtType: "markdown",
227+ };
228+
229+ const markdownResult = await getAllDotContinueDefinitionFiles(
230+ testIde,
231+ markdownOptions,
232+ "assistants",
233+ );
234+ expect(markdownResult).toHaveLength(1);
235+ expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
236+ "assistant3.md",
237+ ]);
238+ expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
239+ "assistant7.MD",
240+ );
241+ });
242+});
deleted core/config/markdown/createMarkdownRule.test.ts +0 −157
@@ -1,157 +0,0 @@
1-import {
2- createMarkdownWithFrontmatter,
3- createRuleFilePath,
4- createRuleMarkdown,
5- sanitizeRuleName,
6-} from "./createMarkdownRule";
7-import { parseMarkdownRule } from "./parseMarkdownRule";
8-
9-describe("sanitizeRuleName", () => {
10- it("should sanitize rule names for filenames", () => {
11- expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
12- expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
13- expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
14- expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
15- expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
16- });
17-
18- it("should handle empty and edge case inputs", () => {
19- expect(sanitizeRuleName("")).toBe("");
20- expect(sanitizeRuleName(" ")).toBe("");
21- expect(sanitizeRuleName("123")).toBe("123");
22- expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
23- "rule-with-numbers-123",
24- );
25- });
26-});
27-
28-describe("createRuleFilePath", () => {
29- it("should create correct rule file path", () => {
30- const result = createRuleFilePath("/workspace", "My Test Rule");
31- expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
32- });
33-
34- it("should handle special characters in rule name", () => {
35- const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
36- expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
37- });
38-
39- it("should handle edge case rule names", () => {
40- const result = createRuleFilePath("/test", " Multiple Spaces ");
41- expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
42- });
43-});
44-
45-describe("createMarkdownWithFrontmatter", () => {
46- it("should create properly formatted markdown with frontmatter", () => {
47- const frontmatter = {
48- name: "Test Rule",
49- description: "A test rule",
50- globs: "*.ts",
51- };
52- const markdown = "# Test Rule\n\nThis is a test rule.";
53-
54- const result = createMarkdownWithFrontmatter(frontmatter, markdown);
55-
56- // The exact quote style doesn't matter as long as it parses correctly
57- expect(result).toContain("name: Test Rule");
58- expect(result).toContain("description: A test rule");
59- expect(result).toContain("globs:");
60- expect(result).toContain("*.ts");
61- expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
62- });
63-
64- it("should handle empty frontmatter", () => {
65- const frontmatter = {};
66- const markdown = "# Simple Rule\n\nJust markdown content.";
67-
68- const result = createMarkdownWithFrontmatter(frontmatter, markdown);
69-
70- const expected = `---
71-{}
72----
73-
74-# Simple Rule
75-
76-Just markdown content.`;
77-
78- expect(result).toBe(expected);
79- });
80-
81- it("should create content that can be parsed back correctly", () => {
82- const originalFrontmatter = {
83- name: "Roundtrip Test",
84- description: "Testing roundtrip parsing",
85- globs: ["*.js", "*.ts"],
86- alwaysApply: true,
87- };
88- const originalMarkdown =
89- "# Roundtrip Test\n\nThis should parse back correctly.";
90-
91- const created = createMarkdownWithFrontmatter(
92- originalFrontmatter,
93- originalMarkdown,
94- );
95- const parsed = parseMarkdownRule(created);
96-
97- expect(parsed.frontmatter).toEqual(originalFrontmatter);
98- expect(parsed.markdown).toBe(originalMarkdown);
99- });
100-});
101-
102-describe("createRuleMarkdown", () => {
103- it("should create rule markdown with all options", () => {
104- const result = createRuleMarkdown("Test Rule", "This is the rule content", {
105- description: "Test description",
106- globs: ["*.ts", "*.js"],
107- alwaysApply: true,
108- });
109-
110- const parsed = parseMarkdownRule(result);
111-
112- expect(parsed.frontmatter.description).toBe("Test description");
113- expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]);
114- expect(parsed.frontmatter.alwaysApply).toBe(true);
115- expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content");
116- });
117-
118- it("should create rule markdown with minimal options", () => {
119- const result = createRuleMarkdown("Simple Rule", "Simple content");
120-
121- const parsed = parseMarkdownRule(result);
122-
123- expect(parsed.frontmatter.description).toBeUndefined();
124- expect(parsed.frontmatter.globs).toBeUndefined();
125- expect(parsed.frontmatter.alwaysApply).toBeUndefined();
126- expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content");
127- });
128-
129- it("should handle string globs", () => {
130- const result = createRuleMarkdown("String Glob Rule", "Content", {
131- globs: "*.py",
132- });
133-
134- const parsed = parseMarkdownRule(result);
135- expect(parsed.frontmatter.globs).toBe("*.py");
136- });
137-
138- it("should trim description and globs", () => {
139- const result = createRuleMarkdown("Trim Test", "Content", {
140- description: " spaced description ",
141- globs: " *.ts ",
142- });
143-
144- const parsed = parseMarkdownRule(result);
145- expect(parsed.frontmatter.description).toBe("spaced description");
146- expect(parsed.frontmatter.globs).toBe("*.ts");
147- });
148-
149- it("should handle alwaysApply false explicitly", () => {
150- const result = createRuleMarkdown("Always Apply False", "Content", {
151- alwaysApply: false,
152- });
153-
154- const parsed = parseMarkdownRule(result);
155- expect(parsed.frontmatter.alwaysApply).toBe(false);
156- });
157-});
deleted core/config/markdown/createMarkdownRule.ts +0 −75
@@ -1,75 +0,0 @@
1-import * as YAML from "yaml";
2-import { joinPathsToUri } from "../../util/uri";
3-import { RuleFrontmatter } from "./parseMarkdownRule";
4-
5-export const RULE_FILE_EXTENSION = "md";
6-
7-/**
8- * Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
9- */
10-export function sanitizeRuleName(name: string): string {
11- return name
12- .toLowerCase()
13- .replace(/[^a-z0-9\s-]/g, "")
14- .replace(/\s+/g, "-")
15- .replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
16-}
17-
18-/**
19- * Creates the file path for a rule in the workspace .continue/rules directory
20- */
21-export function createRuleFilePath(
22- workspaceDir: string,
23- ruleName: string,
24-): string {
25- const safeRuleName = sanitizeRuleName(ruleName);
26- return joinPathsToUri(
27- workspaceDir,
28- ".continue",
29- "rules",
30- `${safeRuleName}.${RULE_FILE_EXTENSION}`,
31- );
32-}
33-
34-/**
35- * Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
36- */
37-export function createMarkdownWithFrontmatter(
38- frontmatter: RuleFrontmatter,
39- markdown: string,
40-): string {
41- const frontmatterStr = YAML.stringify(frontmatter).trim();
42- return `---\n${frontmatterStr}\n---\n\n${markdown}`;
43-}
44-
45-/**
46- * Creates a rule markdown file content from rule components
47- */
48-export function createRuleMarkdown(
49- name: string,
50- ruleContent: string,
51- options: {
52- description?: string;
53- globs?: string | string[];
54- alwaysApply?: boolean;
55- } = {},
56-): string {
57- const frontmatter: RuleFrontmatter = {};
58-
59- if (options.globs) {
60- frontmatter.globs =
61- typeof options.globs === "string" ? options.globs.trim() : options.globs;
62- }
63-
64- if (options.description) {
65- frontmatter.description = options.description.trim();
66- }
67-
68- if (options.alwaysApply !== undefined) {
69- frontmatter.alwaysApply = options.alwaysApply;
70- }
71-
72- const markdownBody = `# ${name}\n\n${ruleContent}`;
73-
74- return createMarkdownWithFrontmatter(frontmatter, markdownBody);
75-}
modified core/config/markdown/index.ts +0 −2
@@ -1,3 +1,1 @@
1-export * from "./createMarkdownRule";
21 export * from "./loadMarkdownRules";
3-export * from "./parseMarkdownRule";
modified core/config/markdown/loadCodebaseRules.ts +6 −4
@@ -1,9 +1,11 @@
1-import { ConfigValidationError } from "@continuedev/config-yaml";
1+import {
2+ ConfigValidationError,
3+ markdownToRule,
4+} from "@continuedev/config-yaml";
25 import { IDE, RuleWithSource } from "../..";
36 import { walkDirs } from "../../indexing/walkDir";
47 import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
58 import { getUriPathBasename } from "../../util/uri";
6-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
79
810 /**
911 * Loads rules from rules.md files colocated in the codebase
@@ -29,9 +31,9 @@
2931 for (const filePath of rulesMdFiles) {
3032 try {
3133 const content = await ide.readFile(filePath);
32- const rule = convertMarkdownRuleToContinueRule(filePath, content);
34+ const rule = markdownToRule(content, { uriType: "file", filePath });
3335
34- rules.push(rule);
36+ rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
3537 } catch (e) {
3638 errors.push({
3739 fatal: false,
modified core/config/markdown/loadCodebaseRules.vitest.ts +8 −8
@@ -1,16 +1,16 @@
1+import { markdownToRule } from "@continuedev/config-yaml";
12 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23 import { IDE } from "../..";
34 import { walkDirs } from "../../indexing/walkDir";
45 import { loadCodebaseRules } from "./loadCodebaseRules";
5-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
66
77 // Mock dependencies
88 vi.mock("../../indexing/walkDir", () => ({
99 walkDirs: vi.fn(),
1010 }));
1111
12-vi.mock("./parseMarkdownRule", () => ({
13- convertMarkdownRuleToContinueRule: vi.fn(),
12+vi.mock("@continuedev/config-yaml", () => ({
13+ markdownToRule: vi.fn(),
1414 }));
1515
1616 describe("loadCodebaseRules", () => {
@@ -82,10 +82,10 @@
8282 return Promise.resolve(mockRuleContent[path] || "");
8383 });
8484
85- // Mock convertMarkdownRuleToContinueRule to return converted rules
86- (convertMarkdownRuleToContinueRule as any).mockImplementation(
87- (path: string, content: string) => {
88- return mockConvertedRules[path];
85+ // Mock markdownToRule to return converted rules
86+ (markdownToRule as any).mockImplementation(
87+ (content: string, options: any) => {
88+ return mockConvertedRules[options.filePath];
8989 },
9090 );
9191 });
@@ -107,7 +107,7 @@
107107 expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
108108
109109 // Should convert all rules
110- expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4);
110+ expect(markdownToRule).toHaveBeenCalledTimes(4);
111111
112112 // Should return all rules
113113 expect(rules).toHaveLength(4);
modified core/config/markdown/loadMarkdownRules.ts +10 −5
@@ -1,7 +1,9 @@
1-import { ConfigValidationError } from "@continuedev/config-yaml";
1+import {
2+ ConfigValidationError,
3+ markdownToRule,
4+} from "@continuedev/config-yaml";
25 import { IDE, RuleWithSource } from "../..";
36 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4-import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
57
68 /**
79 * Loads rules from markdown files in the .continue/rules directory
@@ -17,7 +19,7 @@
1719 // Get all .md files from .continue/rules
1820 const markdownFiles = await getAllDotContinueDefinitionFiles(
1921 ide,
20- { includeGlobal: true, includeWorkspace: true },
22+ { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" },
2123 "rules",
2224 );
2325
@@ -27,8 +29,11 @@
2729 // Process each markdown file
2830 for (const file of mdFiles) {
2931 try {
30- const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
31- rules.push(rule);
32+ const rule = markdownToRule(file.content, {
33+ uriType: "file",
34+ filePath: file.path,
35+ });
36+ rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
3237 } catch (e) {
3338 errors.push({
3439 fatal: false,
deleted core/config/markdown/parseMarkdownRule.test.ts +0 −192
@@ -1,192 +0,0 @@
1-import {
2- convertMarkdownRuleToContinueRule,
3- parseMarkdownRule,
4-} from "./parseMarkdownRule";
5-
6-describe("parseMarkdownRule", () => {
7- it("should correctly parse markdown with YAML frontmatter", () => {
8- const content = `---
9-globs: "**/test/**/*.kt"
10----
11-
12-# Test Rule
13-
14-This is a test rule.`;
15-
16- const result = parseMarkdownRule(content);
17- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
18- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
19- });
20-
21- it("should handle missing frontmatter", () => {
22- const content = `# Test Rule
23-
24-This is a test rule without frontmatter.`;
25-
26- const result = parseMarkdownRule(content);
27- expect(result.frontmatter).toEqual({});
28- expect(result.markdown).toBe(content);
29- });
30-
31- it("should handle empty frontmatter", () => {
32- const content = `---
33----
34-
35-# Test Rule
36-
37-This is a test rule with empty frontmatter.`;
38-
39- const result = parseMarkdownRule(content);
40-
41- // Log exact strings for debugging
42- console.log("Actual:", JSON.stringify(result.markdown));
43- console.log(
44- "Expected:",
45- JSON.stringify(
46- "# Test Rule\n\nThis is a test rule with empty frontmatter.",
47- ),
48- );
49-
50- expect(result.frontmatter).toEqual({});
51- expect(result.markdown).toBe(
52- "# Test Rule\n\nThis is a test rule with empty frontmatter.",
53- );
54- });
55-
56- it("should handle frontmatter with whitespace", () => {
57- const content = `---
58-globs: "**/test/**/*.kt"
59----
60-
61-# Test Rule
62-
63-This is a test rule.`;
64-
65- const result = parseMarkdownRule(content);
66- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
67- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
68- });
69-
70- it("should handle Windows line endings (CRLF)", () => {
71- // Using \r\n for CRLF line endings
72- const content = `---\r
73-globs: "**/test/**/*.kt"\r
74----\r
75-\r
76-# Test Rule\r
77-\r
78-This is a test rule.`;
79-
80- const result = parseMarkdownRule(content);
81- expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
82- // The result should be normalized to \n
83- expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
84- });
85-
86- it("should handle malformed frontmatter", () => {
87- const content = `---
88-globs: - "**/test/**/*.kt"
89-invalid: yaml: content
90----
91-
92-# Test Rule
93-
94-This is a test rule.`;
95-
96- // Should treat as only markdown when frontmatter is malformed
97- const result = parseMarkdownRule(content);
98- expect(result.frontmatter).toEqual({});
99- expect(result.markdown).toBe(content);
100- });
101-});
102-
103-describe("convertMarkdownRuleToContinueRule", () => {
104- it("should convert markdown with frontmatter to a rule", () => {
105- const content = `---
106-globs: "**/test/**/*.kt"
107-name: Custom Name
108----
109-
110-# Test Rule
111-
112-This is a test rule.`;
113-
114- const result = convertMarkdownRuleToContinueRule(
115- "/path/to/rule.md",
116- content,
117- );
118- expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
119- expect(result.globs).toBe("**/test/**/*.kt");
120- expect(result.name).toBe("Custom Name");
121- expect(result.source).toBe("rules-block");
122- expect(result.ruleFile).toBe("/path/to/rule.md");
123- });
124-
125- it("should use the first heading as name if not in frontmatter", () => {
126- const content = `---
127-globs: "**/test/**/*.kt"
128----
129-
130-# Test Rule Title
131-
132-This is a test rule.`;
133-
134- const result = convertMarkdownRuleToContinueRule(
135- "/path/to/rule.md",
136- content,
137- );
138- expect(result.name).toBe("Test Rule Title");
139- });
140-
141- it("should use filename as name if no heading or frontmatter name", () => {
142- const content = `---
143-globs: "**/test/**/*.kt"
144----
145-
146-This is a test rule without a heading.`;
147-
148- const result = convertMarkdownRuleToContinueRule(
149- "/path/to/custom-rule.md",
150- content,
151- );
152- expect(result.name).toBe("custom-rule");
153- });
154-
155- it("should include description from frontmatter", () => {
156- const content = `---
157-globs: "**/test/**/*.kt"
158-name: Test Rule
159-description: This is a rule description from frontmatter
160----
161-
162-# Test Rule
163-
164-This is the content of the rule.`;
165-
166- const result = convertMarkdownRuleToContinueRule(
167- "/path/to/rule.md",
168- content,
169- );
170- expect(result.description).toBe(
171- "This is a rule description from frontmatter",
172- );
173- });
174-
175- it("should include `alwaysApply` from frontmatter", () => {
176- const content = `---
177-globs: "**/test/**/*.kt"
178-name: Test Rule
179-alwaysApply: false
180----
181-
182-# Test Rule
183-
184-This is a rule with alwaysApply explicitly set to false.`;
185-
186- const result = convertMarkdownRuleToContinueRule(
187- "/path/to/rule.md",
188- content,
189- );
190- expect(result.alwaysApply).toBe(false);
191- });
192-});
deleted core/config/markdown/parseMarkdownRule.ts +0 −77
@@ -1,77 +0,0 @@
1-import { basename } from "path";
2-import * as YAML from "yaml";
3-import { RuleWithSource } from "../..";
4-
5-export interface RuleFrontmatter {
6- globs?: RuleWithSource["globs"];
7- name?: RuleWithSource["name"];
8- description?: RuleWithSource["description"];
9- alwaysApply?: RuleWithSource["alwaysApply"];
10-}
11-
12-/**
13- * Parses markdown content with YAML frontmatter
14- */
15-export function parseMarkdownRule(content: string): {
16- frontmatter: RuleFrontmatter;
17- markdown: string;
18-} {
19- // Normalize line endings to \n
20- const normalizedContent = content.replace(/\r\n/g, "\n");
21-
22- // More reliable frontmatter detection
23- const parts = normalizedContent.split(/^---\s*$/m);
24-
25- // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
26- if (parts.length >= 3) {
27- const frontmatterStr = parts[1];
28- // Join the remaining parts back together (in case there are more --- in the markdown)
29- const markdownContent = parts.slice(2).join("---");
30-
31- try {
32- // Parse YAML frontmatter
33- const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
34- return { frontmatter, markdown: markdownContent.trim() };
35- } catch (e) {
36- // Error parsing frontmatter, treat as markdown only
37- console.warn("Error parsing markdown frontmatter:", e);
38- return { frontmatter: {}, markdown: normalizedContent };
39- }
40- }
41-
42- // No frontmatter found
43- return { frontmatter: {}, markdown: normalizedContent };
44-}
45-
46-/**
47- * Converts a markdown file with YAML frontmatter to a RuleWithSource object
48- */
49-export function convertMarkdownRuleToContinueRule(
50- path: string,
51- content: string,
52-): RuleWithSource {
53- const { frontmatter, markdown } = parseMarkdownRule(content);
54-
55- // Try to extract title from first heading if no name in frontmatter
56- let name = frontmatter.name;
57- if (!name) {
58- // Look for a heading in the markdown
59- const headingMatch = markdown.match(/^#\s+(.+)$/m);
60- if (headingMatch) {
61- name = headingMatch[1].trim();
62- } else {
63- // Fall back to filename
64- name = basename(path).replace(/\.md$/, "");
65- }
66- }
67-
68- return {
69- name,
70- rule: markdown,
71- globs: frontmatter.globs,
72- description: frontmatter.description,
73- alwaysApply: frontmatter.alwaysApply,
74- source: "rules-block",
75- ruleFile: path,
76- };
77-}
added core/config/markdown/utils.ts +21 −0
@@ -0,0 +1,21 @@
1+import {
2+ RULE_FILE_EXTENSION,
3+ sanitizeRuleName,
4+} from "@continuedev/config-yaml";
5+import { joinPathsToUri } from "../../util/uri";
6+
7+/**
8+ * Creates the file path for a rule in the workspace .continue/rules directory
9+ */
10+export function createRuleFilePath(
11+ workspaceDir: string,
12+ ruleName: string,
13+): string {
14+ const safeRuleName = sanitizeRuleName(ruleName);
15+ return joinPathsToUri(
16+ workspaceDir,
17+ ".continue",
18+ "rules",
19+ `${safeRuleName}.${RULE_FILE_EXTENSION}`,
20+ );
21+}
added core/config/markdown/utils.vitest.ts +19 −0
@@ -0,0 +1,19 @@
1+import { describe, expect, it } from "vitest";
2+import { createRuleFilePath } from "./utils";
3+
4+describe("createRuleFilePath", () => {
5+ it("should create correct rule file path", () => {
6+ const result = createRuleFilePath("/workspace", "My Test Rule");
7+ expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
8+ });
9+
10+ it("should handle special characters in rule name", () => {
11+ const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
12+ expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
13+ });
14+
15+ it("should handle edge case rule names", () => {
16+ const result = createRuleFilePath("/test", " Multiple Spaces ");
17+ expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
18+ });
19+});
modified core/config/migrateSharedConfig.ts +1 −1
@@ -211,6 +211,6 @@
211211 new GlobalContext().updateSharedConfig(shareConfigUpdates);
212212 }
213213 } catch (e) {
214- throw new Error(`Migration: Failed to parse config.json: ${e}`);
214+ console.error(`Migration: Failed to parse config.json: ${e}`);
215215 }
216216 }
modified core/config/profile/doLoadConfig.ts +24 −9
@@ -16,10 +16,11 @@
1616 ILLMLogger,
1717 RuleWithSource,
1818 SerializedContinueConfig,
19+ SlashCommandDescWithSource,
1920 Tool,
2021 } from "../../";
21-import { constructMcpSlashCommand } from "../../commands/slash/mcp";
2222 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
23+import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
2324 import MCPContextProvider from "../../context/providers/MCPContextProvider";
2425 import RulesContextProvider from "../../context/providers/RulesContextProvider";
2526 import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
@@ -152,6 +153,17 @@
152153 newConfig.rules.unshift(...rules);
153154 newConfig.contextProviders.push(new RulesContextProvider({}));
154155
156+ // Add current file as context if setting is enabled
157+ if (
158+ newConfig.experimental?.useCurrentFileAsContext === true &&
159+ !newConfig.contextProviders.find(
160+ (c) =>
161+ c.description.title === CurrentFileContextProvider.description.title,
162+ )
163+ ) {
164+ newConfig.contextProviders.push(new CurrentFileContextProvider({}));
165+ }
166+
155167 // Add rules from colocated rules.md files in the codebase
156168 const { rules: codebaseRules, errors: codebaseRulesErrors } =
157169 await loadCodebaseRules(ide);
@@ -190,14 +202,15 @@
190202 }));
191203 newConfig.tools.push(...serverTools);
192204
193- const serverSlashCommands = server.prompts.map((prompt) =>
194- constructMcpSlashCommand(
195- server.client,
196- prompt.name,
197- prompt.description,
198- prompt.arguments?.map((a: any) => a.name),
199- ),
200- );
205+ const serverSlashCommands: SlashCommandDescWithSource[] =
206+ server.prompts.map((prompt) => ({
207+ name: prompt.name,
208+ description: prompt.description ?? "MCP Prompt",
209+ source: "mcp-prompt",
210+ isLegacy: false,
211+ mcpServerName: server.name, // Used in client to retrieve prompt
212+ mcpArgs: prompt.arguments,
213+ }));
201214 newConfig.slashCommands.push(...serverSlashCommands);
202215
203216 const submenuItems = server.resources
@@ -229,6 +242,8 @@
229242 newConfig.tools.push(
230243 ...getConfigDependentToolDefinitions({
231244 rules: newConfig.rules,
245+ enableExperimentalTools:
246+ newConfig.experimental?.enableExperimentalTools ?? false,
232247 }),
233248 );
234249
modified core/config/sharedConfig.ts +21 −0
@@ -19,6 +19,10 @@
1919 readResponseTTS: z.boolean(),
2020 promptPath: z.string(),
2121 useCurrentFileAsContext: z.boolean(),
22+ logEditingData: z.boolean(),
23+ optInNextEditFeature: z.boolean(),
24+ enableExperimentalTools: z.boolean(),
25+ codebaseToolCallingOnly: z.boolean(),
2226
2327 // `ui` in `ContinueConfig`
2428 showSessionTabs: z.boolean(),
@@ -157,6 +161,12 @@
157161 configCopy.experimental = {
158162 ...configCopy.experimental,
159163 };
164+
165+ if (sharedConfig.enableExperimentalTools !== undefined) {
166+ configCopy.experimental.enableExperimentalTools =
167+ sharedConfig.enableExperimentalTools;
168+ }
169+
160170 if (sharedConfig.promptPath !== undefined) {
161171 configCopy.experimental.promptPath = sharedConfig.promptPath;
162172 }
@@ -171,6 +181,17 @@
171181 configCopy.experimental.useCurrentFileAsContext =
172182 sharedConfig.useCurrentFileAsContext;
173183 }
184+ if (sharedConfig.logEditingData !== undefined) {
185+ configCopy.experimental.logEditingData = sharedConfig.logEditingData;
186+ }
187+ if (sharedConfig.optInNextEditFeature !== undefined) {
188+ configCopy.experimental.optInNextEditFeature =
189+ sharedConfig.optInNextEditFeature;
190+ }
191+ if (sharedConfig.codebaseToolCallingOnly !== undefined) {
192+ configCopy.experimental.codebaseToolCallingOnly =
193+ sharedConfig.codebaseToolCallingOnly;
194+ }
174195
175196 return configCopy;
176197 }
modified core/config/types.ts +3 −1
@@ -719,7 +719,7 @@
719719
720720 getPinnedFiles(): Promise<string[]>;
721721
722- getSearchResults(query: string): Promise<string>;
722+ getSearchResults(query: string, maxResults?: number): Promise<string>;
723723
724724 subprocess(command: string, cwd?: string): Promise<[string, string]>;
725725
@@ -1004,6 +1004,8 @@
10041004 type: "stdio";
10051005 command: string;
10061006 args: string[];
1007+ env?: Record<string, string>;
1008+ cwd?: string;
10071009 }
10081010
10091011 interface WebSocketOptions {
deleted core/config/usesFreeTrialApiKey.test.ts +0 −344
@@ -1,344 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { BrowserSerializedContinueConfig } from "..";
3-
4-// Create the mock before importing anything else
5-const mockDecodeSecretLocation = jest.fn();
6-
7-// Mock the module
8-jest.unstable_mockModule("@continuedev/config-yaml", () => ({
9- SecretType: {
10- User: "user",
11- Organization: "organization",
12- FreeTrial: "free_trial",
13- },
14- decodeSecretLocation: mockDecodeSecretLocation,
15-}));
16-
17-// Import after mocking
18-const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
19-const { SecretType } = await import("@continuedev/config-yaml");
20-
21-beforeEach(() => {
22- mockDecodeSecretLocation.mockReset();
23-});
24-
25-test("usesFreeTrialApiKey should return false when config is null", () => {
26- const result = usesFreeTrialApiKey(null);
27- expect(result).toBe(false);
28-});
29-
30-test("usesFreeTrialApiKey should return false when config is undefined", () => {
31- const result = usesFreeTrialApiKey(undefined as any);
32- expect(result).toBe(false);
33-});
34-
35-test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
36- const config: BrowserSerializedContinueConfig = {
37- modelsByRole: {
38- chat: [
39- {
40- title: "Model 1",
41- provider: "test",
42- model: "test-model",
43- underlyingProviderName: "test",
44- },
45- {
46- title: "Model 2",
47- provider: "test",
48- model: "test-model-2",
49- underlyingProviderName: "test",
50- },
51- ],
52- edit: [],
53- apply: [],
54- summarize: [],
55- autocomplete: [],
56- rerank: [],
57- embed: [],
58- },
59- selectedModelByRole: {
60- chat: null,
61- edit: null,
62- apply: null,
63- summarize: null,
64- autocomplete: null,
65- rerank: null,
66- embed: null,
67- },
68- contextProviders: [],
69- slashCommands: [],
70- tools: [],
71- mcpServerStatuses: [],
72- usePlatform: false,
73- rules: [],
74- };
75-
76- const result = usesFreeTrialApiKey(config);
77- expect(result).toBe(false);
78-});
79-
80-test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
81- const config: BrowserSerializedContinueConfig = {
82- modelsByRole: {
83- chat: [
84- {
85- title: "Model 1",
86- provider: "test",
87- model: "test-model",
88- apiKeyLocation: "user:testuser/api-key",
89- underlyingProviderName: "test",
90- },
91- ],
92- edit: [
93- {
94- title: "Model 2",
95- provider: "test",
96- model: "test-model-2",
97- apiKeyLocation: "organization:testorg/api-key",
98- underlyingProviderName: "test",
99- },
100- ],
101- apply: [],
102- summarize: [],
103- autocomplete: [],
104- rerank: [],
105- embed: [],
106- },
107- selectedModelByRole: {
108- chat: null,
109- edit: null,
110- apply: null,
111- summarize: null,
112- autocomplete: null,
113- rerank: null,
114- embed: null,
115- },
116- contextProviders: [],
117- slashCommands: [],
118- tools: [],
119- mcpServerStatuses: [],
120- usePlatform: false,
121- rules: [],
122- };
123-
124- mockDecodeSecretLocation
125- .mockReturnValueOnce({
126- secretType: SecretType.User,
127- userSlug: "testuser",
128- secretName: "api-key",
129- })
130- .mockReturnValueOnce({
131- secretType: SecretType.Organization,
132- orgSlug: "testorg",
133- secretName: "api-key",
134- });
135-
136- const result = usesFreeTrialApiKey(config);
137- expect(result).toBe(false);
138- expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
139-});
140-
141-test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
142- const config: BrowserSerializedContinueConfig = {
143- modelsByRole: {
144- chat: [
145- {
146- title: "Model 1",
147- provider: "test",
148- model: "test-model",
149- apiKeyLocation: "user:testuser/api-key",
150- underlyingProviderName: "test",
151- },
152- {
153- title: "Free Trial Model",
154- provider: "test",
155- model: "free-trial-model",
156- apiKeyLocation: "free_trial:owner/package/api-key",
157- underlyingProviderName: "test",
158- },
159- ],
160- edit: [],
161- apply: [],
162- summarize: [],
163- autocomplete: [],
164- rerank: [],
165- embed: [],
166- },
167- selectedModelByRole: {
168- chat: null,
169- edit: null,
170- apply: null,
171- summarize: null,
172- autocomplete: null,
173- rerank: null,
174- embed: null,
175- },
176- contextProviders: [],
177- slashCommands: [],
178- tools: [],
179- mcpServerStatuses: [],
180- usePlatform: false,
181- rules: [],
182- };
183-
184- mockDecodeSecretLocation
185- .mockReturnValueOnce({
186- secretType: SecretType.User,
187- userSlug: "testuser",
188- secretName: "api-key",
189- })
190- .mockReturnValueOnce({
191- secretType: SecretType.FreeTrial,
192- blockSlug: { ownerSlug: "owner", packageSlug: "package" },
193- secretName: "api-key",
194- });
195-
196- const result = usesFreeTrialApiKey(config);
197- expect(result).toBe(true);
198- expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
199-});
200-
201-test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
202- const config: BrowserSerializedContinueConfig = {
203- modelsByRole: {
204- chat: [
205- {
206- title: "Model 1",
207- provider: "test",
208- model: "test-model",
209- apiKeyLocation: "user:testuser/api-key",
210- underlyingProviderName: "test",
211- },
212- ],
213- edit: [
214- {
215- title: "Free Trial Edit Model",
216- provider: "test",
217- model: "free-trial-edit-model",
218- apiKeyLocation: "free_trial:owner/package/api-key",
219- underlyingProviderName: "test",
220- },
221- ],
222- apply: [],
223- summarize: [],
224- autocomplete: [],
225- rerank: [],
226- embed: [],
227- },
228- selectedModelByRole: {
229- chat: null,
230- edit: null,
231- apply: null,
232- summarize: null,
233- autocomplete: null,
234- rerank: null,
235- embed: null,
236- },
237- contextProviders: [],
238- slashCommands: [],
239- tools: [],
240- mcpServerStatuses: [],
241- usePlatform: false,
242- rules: [],
243- };
244-
245- mockDecodeSecretLocation
246- .mockReturnValueOnce({
247- secretType: SecretType.User,
248- userSlug: "testuser",
249- secretName: "api-key",
250- })
251- .mockReturnValueOnce({
252- secretType: SecretType.FreeTrial,
253- blockSlug: { ownerSlug: "owner", packageSlug: "package" },
254- secretName: "api-key",
255- });
256-
257- const result = usesFreeTrialApiKey(config);
258- expect(result).toBe(true);
259-});
260-
261-test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
262- const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
263-
264- const config: BrowserSerializedContinueConfig = {
265- modelsByRole: {
266- chat: [
267- {
268- title: "Model 1",
269- provider: "test",
270- model: "test-model",
271- apiKeyLocation: "invalid-secret-location",
272- underlyingProviderName: "test",
273- },
274- ],
275- edit: [],
276- apply: [],
277- summarize: [],
278- autocomplete: [],
279- rerank: [],
280- embed: [],
281- },
282- selectedModelByRole: {
283- chat: null,
284- edit: null,
285- apply: null,
286- summarize: null,
287- autocomplete: null,
288- rerank: null,
289- embed: null,
290- },
291- contextProviders: [],
292- slashCommands: [],
293- tools: [],
294- mcpServerStatuses: [],
295- usePlatform: false,
296- rules: [],
297- };
298-
299- mockDecodeSecretLocation.mockImplementation(() => {
300- throw new Error("Invalid secret location format");
301- });
302-
303- const result = usesFreeTrialApiKey(config);
304- expect(result).toBe(false);
305- expect(consoleSpy).toHaveBeenCalledWith(
306- "Error checking for free trial API key:",
307- expect.any(Error),
308- );
309-
310- consoleSpy.mockRestore();
311-});
312-
313-test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
314- const config: BrowserSerializedContinueConfig = {
315- modelsByRole: {
316- chat: [],
317- edit: [],
318- apply: [],
319- summarize: [],
320- autocomplete: [],
321- rerank: [],
322- embed: [],
323- },
324- selectedModelByRole: {
325- chat: null,
326- edit: null,
327- apply: null,
328- summarize: null,
329- autocomplete: null,
330- rerank: null,
331- embed: null,
332- },
333- contextProviders: [],
334- slashCommands: [],
335- tools: [],
336- mcpServerStatuses: [],
337- usePlatform: false,
338- rules: [],
339- };
340-
341- const result = usesFreeTrialApiKey(config);
342- expect(result).toBe(false);
343- expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
344-});
added core/config/usesFreeTrialApiKey.vitest.ts +348 −0
@@ -0,0 +1,348 @@
1+import { beforeEach, describe, expect, test, vi } from "vitest";
2+import { BrowserSerializedContinueConfig } from "..";
3+
4+// Create the mock before importing anything else
5+const mockDecodeSecretLocation = vi.fn();
6+
7+// Mock the module
8+vi.mock("@continuedev/config-yaml", () => ({
9+ SecretType: {
10+ User: "user",
11+ Organization: "organization",
12+ FreeTrial: "free_trial",
13+ },
14+ decodeSecretLocation: mockDecodeSecretLocation,
15+}));
16+
17+describe("usesFreeTrialApiKey", () => {
18+ let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
19+ let SecretType: typeof import("@continuedev/config-yaml").SecretType;
20+
21+ beforeEach(async () => {
22+ mockDecodeSecretLocation.mockReset();
23+ usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
24+ .usesFreeTrialApiKey;
25+ SecretType = (await import("@continuedev/config-yaml")).SecretType;
26+ });
27+
28+ test("usesFreeTrialApiKey should return false when config is null", () => {
29+ const result = usesFreeTrialApiKey(null);
30+ expect(result).toBe(false);
31+ });
32+
33+ test("usesFreeTrialApiKey should return false when config is undefined", () => {
34+ const result = usesFreeTrialApiKey(undefined as any);
35+ expect(result).toBe(false);
36+ });
37+
38+ test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
39+ const config: BrowserSerializedContinueConfig = {
40+ modelsByRole: {
41+ chat: [
42+ {
43+ title: "Model 1",
44+ provider: "test",
45+ model: "test-model",
46+ underlyingProviderName: "test",
47+ },
48+ {
49+ title: "Model 2",
50+ provider: "test",
51+ model: "test-model-2",
52+ underlyingProviderName: "test",
53+ },
54+ ],
55+ edit: [],
56+ apply: [],
57+ summarize: [],
58+ autocomplete: [],
59+ rerank: [],
60+ embed: [],
61+ },
62+ selectedModelByRole: {
63+ chat: null,
64+ edit: null,
65+ apply: null,
66+ summarize: null,
67+ autocomplete: null,
68+ rerank: null,
69+ embed: null,
70+ },
71+ contextProviders: [],
72+ slashCommands: [],
73+ tools: [],
74+ mcpServerStatuses: [],
75+ usePlatform: false,
76+ rules: [],
77+ };
78+
79+ const result = usesFreeTrialApiKey(config);
80+ expect(result).toBe(false);
81+ });
82+
83+ test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
84+ const config: BrowserSerializedContinueConfig = {
85+ modelsByRole: {
86+ chat: [
87+ {
88+ title: "Model 1",
89+ provider: "test",
90+ model: "test-model",
91+ apiKeyLocation: "user:testuser/api-key",
92+ underlyingProviderName: "test",
93+ },
94+ ],
95+ edit: [
96+ {
97+ title: "Model 2",
98+ provider: "test",
99+ model: "test-model-2",
100+ apiKeyLocation: "organization:testorg/api-key",
101+ underlyingProviderName: "test",
102+ },
103+ ],
104+ apply: [],
105+ summarize: [],
106+ autocomplete: [],
107+ rerank: [],
108+ embed: [],
109+ },
110+ selectedModelByRole: {
111+ chat: null,
112+ edit: null,
113+ apply: null,
114+ summarize: null,
115+ autocomplete: null,
116+ rerank: null,
117+ embed: null,
118+ },
119+ contextProviders: [],
120+ slashCommands: [],
121+ tools: [],
122+ mcpServerStatuses: [],
123+ usePlatform: false,
124+ rules: [],
125+ };
126+
127+ mockDecodeSecretLocation
128+ .mockReturnValueOnce({
129+ secretType: SecretType.User,
130+ userSlug: "testuser",
131+ secretName: "api-key",
132+ })
133+ .mockReturnValueOnce({
134+ secretType: SecretType.Organization,
135+ orgSlug: "testorg",
136+ secretName: "api-key",
137+ });
138+
139+ const result = usesFreeTrialApiKey(config);
140+ expect(result).toBe(false);
141+ expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
142+ });
143+
144+ test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
145+ const config: BrowserSerializedContinueConfig = {
146+ modelsByRole: {
147+ chat: [
148+ {
149+ title: "Model 1",
150+ provider: "test",
151+ model: "test-model",
152+ apiKeyLocation: "user:testuser/api-key",
153+ underlyingProviderName: "test",
154+ },
155+ {
156+ title: "Free Trial Model",
157+ provider: "test",
158+ model: "free-trial-model",
159+ apiKeyLocation: "free_trial:owner/package/api-key",
160+ underlyingProviderName: "test",
161+ },
162+ ],
163+ edit: [],
164+ apply: [],
165+ summarize: [],
166+ autocomplete: [],
167+ rerank: [],
168+ embed: [],
169+ },
170+ selectedModelByRole: {
171+ chat: null,
172+ edit: null,
173+ apply: null,
174+ summarize: null,
175+ autocomplete: null,
176+ rerank: null,
177+ embed: null,
178+ },
179+ contextProviders: [],
180+ slashCommands: [],
181+ tools: [],
182+ mcpServerStatuses: [],
183+ usePlatform: false,
184+ rules: [],
185+ };
186+
187+ mockDecodeSecretLocation
188+ .mockReturnValueOnce({
189+ secretType: SecretType.User,
190+ userSlug: "testuser",
191+ secretName: "api-key",
192+ })
193+ .mockReturnValueOnce({
194+ secretType: SecretType.FreeTrial,
195+ blockSlug: { ownerSlug: "owner", packageSlug: "package" },
196+ secretName: "api-key",
197+ });
198+
199+ const result = usesFreeTrialApiKey(config);
200+ expect(result).toBe(true);
201+ expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
202+ });
203+
204+ test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
205+ const config: BrowserSerializedContinueConfig = {
206+ modelsByRole: {
207+ chat: [
208+ {
209+ title: "Model 1",
210+ provider: "test",
211+ model: "test-model",
212+ apiKeyLocation: "user:testuser/api-key",
213+ underlyingProviderName: "test",
214+ },
215+ ],
216+ edit: [
217+ {
218+ title: "Free Trial Edit Model",
219+ provider: "test",
220+ model: "free-trial-edit-model",
221+ apiKeyLocation: "free_trial:owner/package/api-key",
222+ underlyingProviderName: "test",
223+ },
224+ ],
225+ apply: [],
226+ summarize: [],
227+ autocomplete: [],
228+ rerank: [],
229+ embed: [],
230+ },
231+ selectedModelByRole: {
232+ chat: null,
233+ edit: null,
234+ apply: null,
235+ summarize: null,
236+ autocomplete: null,
237+ rerank: null,
238+ embed: null,
239+ },
240+ contextProviders: [],
241+ slashCommands: [],
242+ tools: [],
243+ mcpServerStatuses: [],
244+ usePlatform: false,
245+ rules: [],
246+ };
247+
248+ mockDecodeSecretLocation
249+ .mockReturnValueOnce({
250+ secretType: SecretType.User,
251+ userSlug: "testuser",
252+ secretName: "api-key",
253+ })
254+ .mockReturnValueOnce({
255+ secretType: SecretType.FreeTrial,
256+ blockSlug: { ownerSlug: "owner", packageSlug: "package" },
257+ secretName: "api-key",
258+ });
259+
260+ const result = usesFreeTrialApiKey(config);
261+ expect(result).toBe(true);
262+ });
263+
264+ test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
265+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
266+
267+ const config: BrowserSerializedContinueConfig = {
268+ modelsByRole: {
269+ chat: [
270+ {
271+ title: "Model 1",
272+ provider: "test",
273+ model: "test-model",
274+ apiKeyLocation: "invalid-secret-location",
275+ underlyingProviderName: "test",
276+ },
277+ ],
278+ edit: [],
279+ apply: [],
280+ summarize: [],
281+ autocomplete: [],
282+ rerank: [],
283+ embed: [],
284+ },
285+ selectedModelByRole: {
286+ chat: null,
287+ edit: null,
288+ apply: null,
289+ summarize: null,
290+ autocomplete: null,
291+ rerank: null,
292+ embed: null,
293+ },
294+ contextProviders: [],
295+ slashCommands: [],
296+ tools: [],
297+ mcpServerStatuses: [],
298+ usePlatform: false,
299+ rules: [],
300+ };
301+
302+ mockDecodeSecretLocation.mockImplementation(() => {
303+ throw new Error("Invalid secret location format");
304+ });
305+
306+ const result = usesFreeTrialApiKey(config);
307+ expect(result).toBe(false);
308+ expect(consoleSpy).toHaveBeenCalledWith(
309+ "Error checking for free trial API key:",
310+ expect.any(Error),
311+ );
312+
313+ consoleSpy.mockRestore();
314+ });
315+
316+ test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
317+ const config: BrowserSerializedContinueConfig = {
318+ modelsByRole: {
319+ chat: [],
320+ edit: [],
321+ apply: [],
322+ summarize: [],
323+ autocomplete: [],
324+ rerank: [],
325+ embed: [],
326+ },
327+ selectedModelByRole: {
328+ chat: null,
329+ edit: null,
330+ apply: null,
331+ summarize: null,
332+ autocomplete: null,
333+ rerank: null,
334+ embed: null,
335+ },
336+ contextProviders: [],
337+ slashCommands: [],
338+ tools: [],
339+ mcpServerStatuses: [],
340+ usePlatform: false,
341+ rules: [],
342+ };
343+
344+ const result = usesFreeTrialApiKey(config);
345+ expect(result).toBe(false);
346+ expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
347+ });
348+});
deleted core/config/util.test.ts +0 −45
@@ -1,45 +0,0 @@
1-import { PromptTemplate } from "..";
2-import { serializePromptTemplates } from "./util";
3-
4-describe("serializePromptTemplates", () => {
5- it("should return undefined for undefined input", () => {
6- expect(serializePromptTemplates(undefined)).toBeUndefined();
7- });
8-
9- it("should convert function templates to empty strings", () => {
10- const functionTemplate: PromptTemplate = () => "Generated template";
11- const templates: Record<string, PromptTemplate> = {
12- template1: functionTemplate,
13- };
14-
15- const result = serializePromptTemplates(templates);
16-
17- expect(result).toEqual({ template1: "" });
18- });
19-
20- it("should pass through string templates unchanged", () => {
21- const templates: Record<string, PromptTemplate> = {
22- template1: "This is a static template",
23- template2: "Another static template",
24- };
25-
26- const result = serializePromptTemplates(templates);
27-
28- expect(result).toEqual(templates);
29- });
30-
31- it("should handle mixed template types", () => {
32- const functionTemplate: PromptTemplate = () => "Generated template";
33- const templates: Record<string, PromptTemplate> = {
34- function: functionTemplate,
35- string: "This is a static template",
36- };
37-
38- const result = serializePromptTemplates(templates);
39-
40- expect(result).toEqual({
41- function: "",
42- string: "This is a static template",
43- });
44- });
45-});
modified core/config/util.ts +1 −1
@@ -10,7 +10,7 @@
1010 JSONModelDescription,
1111 PromptTemplate,
1212 } from "../";
13-import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
13+import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
1414 import { GlobalContext } from "../util/GlobalContext";
1515 import { editConfigFile } from "../util/paths";
1616
added core/config/util.vitest.ts +46 −0
@@ -0,0 +1,46 @@
1+import { describe, expect, it } from "vitest";
2+import { PromptTemplate } from "..";
3+import { serializePromptTemplates } from "./util";
4+
5+describe("serializePromptTemplates", () => {
6+ it("should return undefined for undefined input", () => {
7+ expect(serializePromptTemplates(undefined)).toBeUndefined();
8+ });
9+
10+ it("should convert function templates to empty strings", () => {
11+ const functionTemplate: PromptTemplate = () => "Generated template";
12+ const templates: Record<string, PromptTemplate> = {
13+ template1: functionTemplate,
14+ };
15+
16+ const result = serializePromptTemplates(templates);
17+
18+ expect(result).toEqual({ template1: "" });
19+ });
20+
21+ it("should pass through string templates unchanged", () => {
22+ const templates: Record<string, PromptTemplate> = {
23+ template1: "This is a static template",
24+ template2: "Another static template",
25+ };
26+
27+ const result = serializePromptTemplates(templates);
28+
29+ expect(result).toEqual(templates);
30+ });
31+
32+ it("should handle mixed template types", () => {
33+ const functionTemplate: PromptTemplate = () => "Generated template";
34+ const templates: Record<string, PromptTemplate> = {
35+ function: functionTemplate,
36+ string: "This is a static template",
37+ };
38+
39+ const result = serializePromptTemplates(templates);
40+
41+ expect(result).toEqual({
42+ function: "",
43+ string: "This is a static template",
44+ });
45+ });
46+});
deleted core/config/workspace/workspaceBlocks.test.ts +0 −170
@@ -1,170 +0,0 @@
1-import { BlockType } from "@continuedev/config-yaml";
2-import { describe, expect, test } from "@jest/globals";
3-import { RULE_FILE_EXTENSION } from "../markdown";
4-import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
5-
6-describe("getFileContent", () => {
7- test("returns markdown content for rules block type", () => {
8- const result = getFileContent("rules");
9- expect(result).toContain("# New Rule");
10- expect(result).toContain("Your rule content");
11- expect(result).toContain("A description of your rule");
12- });
13-
14- test("returns YAML content for non-rules block types", () => {
15- const result = getFileContent("models");
16- expect(result).toContain("name: New model");
17- expect(result).toContain("version: 0.0.1");
18- expect(result).toContain("schema: v1");
19- expect(result).toContain("models:");
20- expect(result).toContain("provider: anthropic");
21- });
22-
23- test("generates correct YAML for different block types", () => {
24- const contextResult = getFileContent("context");
25- expect(contextResult).toContain("name: New context");
26- expect(contextResult).toContain("context:");
27- expect(contextResult).toContain("provider: file");
28-
29- const docsResult = getFileContent("docs");
30- expect(docsResult).toContain("name: New doc");
31- expect(docsResult).toContain("docs:");
32- expect(docsResult).toContain("startUrl: https://docs.continue.dev");
33-
34- const promptsResult = getFileContent("prompts");
35- expect(promptsResult).toContain("name: New prompt");
36- expect(promptsResult).toContain("prompts:");
37- expect(promptsResult).toContain("thorough suite of unit tests");
38-
39- const mcpResult = getFileContent("mcpServers");
40- expect(mcpResult).toContain("name: New MCP server");
41- expect(mcpResult).toContain("mcpServers:");
42- expect(mcpResult).toContain("command: npx");
43- });
44-});
45-
46-describe("findAvailableFilename", () => {
47- test("returns base filename when it doesn't exist", async () => {
48- const mockFileExists = async (uri: string) => false;
49-
50- const result = await findAvailableFilename(
51- "/workspace/.continue/models",
52- "models",
53- mockFileExists,
54- );
55-
56- expect(result).toBe("/workspace/.continue/models/new-model.yaml");
57- });
58-
59- test("returns filename with counter when base exists", async () => {
60- const mockFileExists = async (uri: string) => {
61- return uri === "/workspace/.continue/models/new-model.yaml";
62- };
63-
64- const result = await findAvailableFilename(
65- "/workspace/.continue/models",
66- "models",
67- mockFileExists,
68- );
69-
70- expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
71- });
72-
73- test("increments counter until available filename is found", async () => {
74- const existingFiles = new Set([
75- "/workspace/.continue/context/new-context.yaml",
76- "/workspace/.continue/context/new-context-1.yaml",
77- "/workspace/.continue/context/new-context-2.yaml",
78- ]);
79-
80- const mockFileExists = async (uri: string) => {
81- return existingFiles.has(uri);
82- };
83-
84- const result = await findAvailableFilename(
85- "/workspace/.continue/context",
86- "context",
87- mockFileExists,
88- );
89-
90- expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
91- });
92-
93- test("handles different block types correctly with proper extensions", async () => {
94- const mockFileExists = async (uri: string) => false;
95-
96- const testCases: Array<{ blockType: BlockType; expected: string }> = [
97- { blockType: "models", expected: "/test/new-model.yaml" },
98- { blockType: "context", expected: "/test/new-context.yaml" },
99- { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
100- { blockType: "docs", expected: "/test/new-doc.yaml" },
101- { blockType: "prompts", expected: "/test/new-prompt.yaml" },
102- { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
103- ];
104-
105- for (const { blockType, expected } of testCases) {
106- const result = await findAvailableFilename(
107- "/test",
108- blockType,
109- mockFileExists,
110- );
111- expect(result).toBe(expected);
112- }
113- });
114-
115- test("respects custom extension parameter", async () => {
116- const mockFileExists = async (uri: string) => false;
117-
118- const result = await findAvailableFilename(
119- "/test",
120- "models",
121- mockFileExists,
122- "json",
123- );
124-
125- expect(result).toBe("/test/new-model.json");
126- });
127-
128- test("handles rules markdown files with counter", async () => {
129- const existingFiles = new Set([
130- `/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
131- `/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
132- ]);
133-
134- const mockFileExists = async (uri: string) => {
135- return existingFiles.has(uri);
136- };
137-
138- const result = await findAvailableFilename(
139- "/workspace/.continue/rules",
140- "rules",
141- mockFileExists,
142- );
143-
144- expect(result).toBe(
145- `/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
146- );
147- });
148-
149- test("handles large counter values", async () => {
150- const existingFiles = new Set(
151- Array.from({ length: 100 }, (_, i) =>
152- i === 0
153- ? "/workspace/.continue/prompts/new-prompt.yaml"
154- : `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
155- ),
156- );
157-
158- const mockFileExists = async (uri: string) => {
159- return existingFiles.has(uri);
160- };
161-
162- const result = await findAvailableFilename(
163- "/workspace/.continue/prompts",
164- "prompts",
165- mockFileExists,
166- );
167-
168- expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
169- });
170-});
modified core/config/workspace/workspaceBlocks.ts +6 −2
@@ -1,8 +1,12 @@
1-import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
1+import {
2+ BlockType,
3+ ConfigYaml,
4+ createRuleMarkdown,
5+ RULE_FILE_EXTENSION,
6+} from "@continuedev/config-yaml";
27 import * as YAML from "yaml";
38 import { IDE } from "../..";
49 import { joinPathsToUri } from "../../util/uri";
5-import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
610
711 const BLOCK_TYPE_CONFIG: Record<
812 BlockType,
added core/config/workspace/workspaceBlocks.vitest.ts +168 −0
@@ -0,0 +1,168 @@
1+import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
2+import { describe, expect, test } from "vitest";
3+import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
4+
5+describe("getFileContent", () => {
6+ test("returns markdown content for rules block type", () => {
7+ const result = getFileContent("rules");
8+ expect(result).toContain("Your rule content");
9+ expect(result).toContain("A description of your rule");
10+ });
11+
12+ test("returns YAML content for non-rules block types", () => {
13+ const result = getFileContent("models");
14+ expect(result).toContain("name: New model");
15+ expect(result).toContain("version: 0.0.1");
16+ expect(result).toContain("schema: v1");
17+ expect(result).toContain("models:");
18+ expect(result).toContain("provider: anthropic");
19+ });
20+
21+ test("generates correct YAML for different block types", () => {
22+ const contextResult = getFileContent("context");
23+ expect(contextResult).toContain("name: New context");
24+ expect(contextResult).toContain("context:");
25+ expect(contextResult).toContain("provider: file");
26+
27+ const docsResult = getFileContent("docs");
28+ expect(docsResult).toContain("name: New doc");
29+ expect(docsResult).toContain("docs:");
30+ expect(docsResult).toContain("startUrl: https://docs.continue.dev");
31+
32+ const promptsResult = getFileContent("prompts");
33+ expect(promptsResult).toContain("name: New prompt");
34+ expect(promptsResult).toContain("prompts:");
35+ expect(promptsResult).toContain("thorough suite of unit tests");
36+
37+ const mcpResult = getFileContent("mcpServers");
38+ expect(mcpResult).toContain("name: New MCP server");
39+ expect(mcpResult).toContain("mcpServers:");
40+ expect(mcpResult).toContain("command: npx");
41+ });
42+});
43+
44+describe("findAvailableFilename", () => {
45+ test("returns base filename when it doesn't exist", async () => {
46+ const mockFileExists = async (uri: string) => false;
47+
48+ const result = await findAvailableFilename(
49+ "/workspace/.continue/models",
50+ "models",
51+ mockFileExists,
52+ );
53+
54+ expect(result).toBe("/workspace/.continue/models/new-model.yaml");
55+ });
56+
57+ test("returns filename with counter when base exists", async () => {
58+ const mockFileExists = async (uri: string) => {
59+ return uri === "/workspace/.continue/models/new-model.yaml";
60+ };
61+
62+ const result = await findAvailableFilename(
63+ "/workspace/.continue/models",
64+ "models",
65+ mockFileExists,
66+ );
67+
68+ expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
69+ });
70+
71+ test("increments counter until available filename is found", async () => {
72+ const existingFiles = new Set([
73+ "/workspace/.continue/context/new-context.yaml",
74+ "/workspace/.continue/context/new-context-1.yaml",
75+ "/workspace/.continue/context/new-context-2.yaml",
76+ ]);
77+
78+ const mockFileExists = async (uri: string) => {
79+ return existingFiles.has(uri);
80+ };
81+
82+ const result = await findAvailableFilename(
83+ "/workspace/.continue/context",
84+ "context",
85+ mockFileExists,
86+ );
87+
88+ expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
89+ });
90+
91+ test("handles different block types correctly with proper extensions", async () => {
92+ const mockFileExists = async (uri: string) => false;
93+
94+ const testCases: Array<{ blockType: BlockType; expected: string }> = [
95+ { blockType: "models", expected: "/test/new-model.yaml" },
96+ { blockType: "context", expected: "/test/new-context.yaml" },
97+ { blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
98+ { blockType: "docs", expected: "/test/new-doc.yaml" },
99+ { blockType: "prompts", expected: "/test/new-prompt.yaml" },
100+ { blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
101+ ];
102+
103+ for (const { blockType, expected } of testCases) {
104+ const result = await findAvailableFilename(
105+ "/test",
106+ blockType,
107+ mockFileExists,
108+ );
109+ expect(result).toBe(expected);
110+ }
111+ });
112+
113+ test("respects custom extension parameter", async () => {
114+ const mockFileExists = async (uri: string) => false;
115+
116+ const result = await findAvailableFilename(
117+ "/test",
118+ "models",
119+ mockFileExists,
120+ "json",
121+ );
122+
123+ expect(result).toBe("/test/new-model.json");
124+ });
125+
126+ test("handles rules markdown files with counter", async () => {
127+ const existingFiles = new Set([
128+ `/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
129+ `/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
130+ ]);
131+
132+ const mockFileExists = async (uri: string) => {
133+ return existingFiles.has(uri);
134+ };
135+
136+ const result = await findAvailableFilename(
137+ "/workspace/.continue/rules",
138+ "rules",
139+ mockFileExists,
140+ );
141+
142+ expect(result).toBe(
143+ `/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
144+ );
145+ });
146+
147+ test("handles large counter values", async () => {
148+ const existingFiles = new Set(
149+ Array.from({ length: 100 }, (_, i) =>
150+ i === 0
151+ ? "/workspace/.continue/prompts/new-prompt.yaml"
152+ : `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
153+ ),
154+ );
155+
156+ const mockFileExists = async (uri: string) => {
157+ return existingFiles.has(uri);
158+ };
159+
160+ const result = await findAvailableFilename(
161+ "/workspace/.continue/prompts",
162+ "prompts",
163+ mockFileExists,
164+ );
165+
166+ expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
167+ });
168+});
modified core/config/yaml/LocalPlatformClient.vitest.ts +0 −1
@@ -123,7 +123,6 @@
123123 expect(
124124 (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
125125 ).toBe(secretValue);
126- console.log("debug1 resolved fqsn", resolvedFQSNs);
127126 });
128127 });
129128
modified core/config/yaml/loadYaml.ts +15 −26
@@ -25,21 +25,20 @@
2525 ILLMLogger,
2626 RuleWithSource,
2727 } from "../..";
28-import { slashFromCustomCommand } from "../../commands";
2928 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
30-import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
3129 import DocsContextProvider from "../../context/providers/DocsContextProvider";
3230 import FileContextProvider from "../../context/providers/FileContextProvider";
3331 import { contextProviderClassFromName } from "../../context/providers/index";
3432 import { ControlPlaneClient } from "../../control-plane/client";
3533 import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
36-import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
37-import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
34+import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
3835 import { GlobalContext } from "../../util/GlobalContext";
3936 import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
4037
38+import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
39+import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
4140 import { getControlPlaneEnvSync } from "../../control-plane/env";
42-import { baseToolDefinitions } from "../../tools";
41+import { getToolsForIde } from "../../tools";
4342 import { getCleanUriPath } from "../../util/uri";
4443 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4544 import { LocalPlatformClient } from "./LocalPlatformClient";
@@ -70,6 +69,7 @@
7069 command: server.command,
7170 args: server.args ?? [],
7271 env: server.env,
72+ cwd: server.cwd,
7373 } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
7474 timeout: server.connectionTimeout,
7575 };
@@ -97,7 +97,7 @@
9797 for (const blockType of BLOCK_TYPES) {
9898 const localBlocks = await getAllDotContinueDefinitionFiles(
9999 ide,
100- { includeGlobal: true, includeWorkspace: true },
100+ { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
101101 blockType,
102102 );
103103 allLocalBlocks.push(
@@ -134,6 +134,7 @@
134134 rootPath,
135135 }),
136136 {
137+ renderSecrets: true,
137138 currentUserSlug: "",
138139 onPremProxyUrl: null,
139140 orgScopeId,
@@ -142,9 +143,7 @@
142143 controlPlaneClient,
143144 ide,
144145 ),
145- renderSecrets: true,
146146 injectBlocks: allLocalBlocks,
147- asConfigResult: true,
148147 },
149148 );
150149 config = unrollResult.config;
@@ -153,13 +152,8 @@
153152 }
154153 }
155154
156- if (config) {
157- isAssistantUnrolledNonNullable(config)
158- ? errors.push(...validateConfigYaml(config))
159- : errors.push({
160- fatal: true,
161- message: "Assistant includes blocks that don't exist",
162- });
155+ if (config && isAssistantUnrolledNonNullable(config)) {
156+ errors.push(...validateConfigYaml(config));
163157 }
164158
165159 if (errors?.some((error) => error.fatal)) {
@@ -193,7 +187,7 @@
193187
194188 const continueConfig: ContinueConfig = {
195189 slashCommands: [],
196- tools: [...baseToolDefinitions],
190+ tools: await getToolsForIde(ide),
197191 mcpServerStatuses: [],
198192 contextProviders: [],
199193 modelsByRole: {
@@ -223,7 +217,8 @@
223217 config: continueConfig,
224218 errors: [
225219 {
226- message: "Found missing blocks in config.yaml",
220+ message:
221+ "Failed to load config due to missing blocks, see which blocks are missing below",
227222 fatal: true,
228223 },
229224 ],
@@ -268,7 +263,7 @@
268263
269264 promptFiles.forEach((file) => {
270265 try {
271- const slashCommand = slashCommandFromPromptFileV1(
266+ const slashCommand = slashCommandFromPromptFile(
272267 file.path,
273268 file.content,
274269 );
@@ -291,7 +286,7 @@
291286
292287 config.prompts?.forEach((prompt) => {
293288 try {
294- const slashCommand = slashFromCustomCommand(prompt);
289+ const slashCommand = convertPromptBlockToSlashCommand(prompt);
295290 continueConfig.slashCommands?.push(slashCommand);
296291 } catch (e) {
297292 localErrors.push({
@@ -390,13 +385,7 @@
390385 }
391386
392387 // Context providers
393- const codebaseContextParams: IContextProvider[] =
394- (config.context || []).find((cp) => cp.provider === "codebase")?.params ||
395- {};
396- const DEFAULT_CONTEXT_PROVIDERS = [
397- new FileContextProvider({}),
398- new CodebaseContextProvider(codebaseContextParams),
399- ];
388+ const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
400389
401390 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
402391 ({ description: { title } }) => title,
added core/config/yaml/loadYaml.vitest.ts +128 −0
@@ -0,0 +1,128 @@
1+import { describe, it, expect } from "vitest";
2+import {
3+ validateConfigYaml,
4+ AssistantUnrolledNonNullable,
5+} from "@continuedev/config-yaml";
6+
7+describe("MCP Server cwd configuration", () => {
8+ describe("YAML schema validation", () => {
9+ it("should accept valid MCP server with cwd", () => {
10+ const config: AssistantUnrolledNonNullable = {
11+ name: "test-assistant",
12+ version: "1.0.0",
13+ mcpServers: [
14+ {
15+ name: "test-server",
16+ command: "node",
17+ args: ["server.js"],
18+ env: { NODE_ENV: "production" },
19+ cwd: "/path/to/project",
20+ connectionTimeout: 5000,
21+ },
22+ ],
23+ };
24+
25+ const errors = validateConfigYaml(config);
26+ expect(errors).toHaveLength(0);
27+ });
28+
29+ it("should accept MCP server without cwd", () => {
30+ const config: AssistantUnrolledNonNullable = {
31+ name: "test-assistant",
32+ version: "1.0.0",
33+ mcpServers: [
34+ {
35+ name: "test-server",
36+ command: "python",
37+ args: ["-m", "server"],
38+ },
39+ ],
40+ };
41+
42+ const errors = validateConfigYaml(config);
43+ expect(errors).toHaveLength(0);
44+ });
45+
46+ it("should accept relative paths in cwd", () => {
47+ const config: AssistantUnrolledNonNullable = {
48+ name: "test-assistant",
49+ version: "1.0.0",
50+ mcpServers: [
51+ {
52+ name: "test-server",
53+ command: "cargo",
54+ args: ["run"],
55+ cwd: "./rust-project",
56+ },
57+ ],
58+ };
59+
60+ const errors = validateConfigYaml(config);
61+ expect(errors).toHaveLength(0);
62+ });
63+
64+ it("should accept empty string cwd", () => {
65+ const config: AssistantUnrolledNonNullable = {
66+ name: "test-assistant",
67+ version: "1.0.0",
68+ mcpServers: [
69+ {
70+ name: "test-server",
71+ command: "deno",
72+ args: ["run", "server.ts"],
73+ cwd: "",
74+ },
75+ ],
76+ };
77+
78+ const errors = validateConfigYaml(config);
79+ expect(errors).toHaveLength(0);
80+ });
81+ });
82+
83+ describe("MCP server configuration examples", () => {
84+ it("should support common MCP server patterns with cwd", () => {
85+ const configs = [
86+ {
87+ name: "Local project MCP server",
88+ server: {
89+ name: "project-mcp",
90+ command: "npm",
91+ args: ["run", "mcp-server"],
92+ cwd: "/Users/developer/my-project",
93+ },
94+ },
95+ {
96+ name: "Python MCP with virtual environment",
97+ server: {
98+ name: "python-mcp",
99+ command: "python",
100+ args: ["-m", "my_mcp_server"],
101+ env: { PYTHONPATH: "./src" },
102+ cwd: "/home/user/python-project",
103+ },
104+ },
105+ {
106+ name: "Relative path MCP server",
107+ server: {
108+ name: "relative-mcp",
109+ command: "node",
110+ args: ["index.js"],
111+ cwd: "../mcp-servers/filesystem",
112+ },
113+ },
114+ ];
115+
116+ configs.forEach(({ name, server }) => {
117+ const config: AssistantUnrolledNonNullable = {
118+ name: "test-assistant",
119+ version: "1.0.0",
120+ mcpServers: [server],
121+ };
122+
123+ const errors = validateConfigYaml(config);
124+ expect(errors).toHaveLength(0);
125+ });
126+ });
127+ });
128+});
modified core/config/yaml/models.ts +7 −0
@@ -63,6 +63,7 @@
6363 template: model.promptTemplates?.chat,
6464 promptTemplates: model.promptTemplates,
6565 baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
66+ basePlanSystemMessage: model.chatOptions?.basePlanSystemMessage,
6667 baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
6768 capabilities: {
6869 tools: model.capabilities?.includes("tool_use"),
@@ -126,6 +127,12 @@
126127 if ("profile" in env && typeof env.profile === "string") {
127128 options.profile = env.profile;
128129 }
130+ if ("accessKeyId" in env && typeof env.accessKeyId === "string") {
131+ options.accessKeyId = env.accessKeyId;
132+ }
133+ if ("secretAccessKey" in env && typeof env.secretAccessKey === "string") {
134+ options.secretAccessKey = env.secretAccessKey;
135+ }
129136 if ("modelArn" in env && typeof env.modelArn === "string") {
130137 options.modelArn = env.modelArn;
131138 }
deleted core/context/mcp/MCPConnection.test.ts +0 −288
@@ -1,288 +0,0 @@
1-import { jest } from "@jest/globals";
2-import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3-import MCPConnection from "./MCPConnection";
4-
5-describe("MCPConnection", () => {
6- beforeEach(() => {
7- jest.restoreAllMocks();
8- });
9-
10- describe("constructor", () => {
11- it("should create instance with stdio transport", () => {
12- const options = {
13- name: "test-mcp",
14- id: "test-id",
15- transport: {
16- type: "stdio" as const,
17- command: "test-cmd",
18- args: ["--test"],
19- env: { TEST: "true" },
20- },
21- };
22-
23- const conn = new MCPConnection(options);
24- expect(conn).toBeInstanceOf(MCPConnection);
25- expect(conn.status).toBe("not-connected");
26- });
27-
28- it("should create instance with websocket transport", () => {
29- const options = {
30- name: "test-mcp",
31- id: "test-id",
32- transport: {
33- type: "websocket" as const,
34- url: "ws://test.com",
35- },
36- };
37-
38- const conn = new MCPConnection(options);
39- expect(conn).toBeInstanceOf(MCPConnection);
40- expect(conn.status).toBe("not-connected");
41- });
42-
43- it("should create instance with SSE transport", () => {
44- const options = {
45- name: "test-mcp",
46- id: "test-id",
47- transport: {
48- type: "sse" as const,
49- url: "http://test.com/events",
50- },
51- };
52-
53- const conn = new MCPConnection(options);
54- expect(conn).toBeInstanceOf(MCPConnection);
55- expect(conn.status).toBe("not-connected");
56- });
57-
58- it("should create instance with SSE transport and custom headers", () => {
59- const options = {
60- name: "test-mcp",
61- id: "test-id",
62- transport: {
63- type: "sse" as const,
64- url: "http://test.com/events",
65- requestOptions: {
66- headers: {
67- Authorization: "Bearer token123",
68- "X-Custom-Header": "custom-value",
69- },
70- },
71- },
72- };
73-
74- const conn = new MCPConnection(options);
75- expect(conn).toBeInstanceOf(MCPConnection);
76- expect(conn.status).toBe("not-connected");
77- });
78-
79- it("should throw on invalid transport type", () => {
80- const options = {
81- name: "test-mcp",
82- id: "test-id",
83- transport: {
84- type: "invalid",
85- } as any,
86- };
87-
88- expect(() => new MCPConnection(options)).toThrow(
89- "Unsupported transport type: invalid",
90- );
91- });
92- });
93-
94- describe("getStatus", () => {
95- it("should return current status", () => {
96- const options = {
97- name: "test-mcp",
98- id: "test-id",
99- transport: {
100- type: "stdio" as const,
101- command: "test",
102- args: [],
103- },
104- };
105-
106- const conn = new MCPConnection(options);
107- const status = conn.getStatus();
108-
109- expect(status).toEqual({
110- ...options,
111- errors: [],
112- prompts: [],
113- resources: [],
114- resourceTemplates: [],
115- tools: [],
116- status: "not-connected",
117- });
118- });
119- });
120-
121- describe("connectClient", () => {
122- const options = {
123- name: "test-mcp",
124- id: "test-id",
125- transport: {
126- type: "stdio" as const,
127- command: "test-cmd",
128- args: [],
129- },
130- };
131-
132- it("should connect successfully", async () => {
133- const conn = new MCPConnection(options);
134- const mockConnect = jest
135- .spyOn(Client.prototype, "connect")
136- .mockResolvedValue(undefined);
137- const mockGetServerCapabilities = jest
138- .spyOn(Client.prototype, "getServerCapabilities")
139- .mockReturnValue({
140- resources: {},
141- tools: {},
142- prompts: {},
143- });
144-
145- const mockListResources = jest
146- .spyOn(Client.prototype, "listResources")
147- .mockResolvedValue({
148- resources: [{ name: "test-resource", uri: "test-uri" }],
149- });
150- const mockListTools = jest
151- .spyOn(Client.prototype, "listTools")
152- .mockResolvedValue({
153- tools: [
154- {
155- name: "test-tool",
156- inputSchema: {
157- type: "object",
158- },
159- },
160- ],
161- });
162- const mockListPrompts = jest
163- .spyOn(Client.prototype, "listPrompts")
164- .mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
165-
166- const abortController = new AbortController();
167- await conn.connectClient(false, abortController.signal);
168-
169- expect(conn.status).toBe("connected");
170- expect(conn.resources).toHaveLength(1);
171- expect(conn.tools).toHaveLength(1);
172- expect(conn.prompts).toHaveLength(1);
173- expect(mockConnect).toHaveBeenCalled();
174- });
175-
176- it("should handle custom connection timeout", async () => {
177- const conn = new MCPConnection({ ...options, timeout: 1500 });
178- const mockConnect = jest
179- .spyOn(Client.prototype, "connect")
180- .mockImplementation(
181- () => new Promise((resolve) => setTimeout(resolve, 1000)),
182- );
183-
184- const abortController = new AbortController();
185- await conn.connectClient(false, abortController.signal);
186-
187- expect(conn.status).toBe("connected");
188- expect(mockConnect).toHaveBeenCalled();
189- });
190-
191- it("should handle connection timeout", async () => {
192- const conn = new MCPConnection({ ...options, timeout: 1 });
193- const mockConnect = jest
194- .spyOn(Client.prototype, "connect")
195- .mockImplementation(
196- () => new Promise((resolve) => setTimeout(resolve, 100)),
197- );
198-
199- const abortController = new AbortController();
200- await conn.connectClient(false, abortController.signal);
201-
202- expect(conn.status).toBe("error");
203- expect(conn.errors[0]).toContain("Failed to connect");
204- expect(mockConnect).toHaveBeenCalled();
205- });
206-
207- it("should handle already connected state", async () => {
208- const conn = new MCPConnection(options);
209- conn.status = "connected";
210-
211- const mockConnect = jest.spyOn(Client.prototype, "connect");
212- const abortController = new AbortController();
213-
214- await conn.connectClient(false, abortController.signal);
215-
216- expect(mockConnect).not.toHaveBeenCalled();
217- expect(conn.status).toBe("connected");
218- });
219-
220- it("should handle transport errors", async () => {
221- const conn = new MCPConnection(options);
222- const mockConnect = jest
223- .spyOn(Client.prototype, "connect")
224- .mockRejectedValue(new Error("spawn test-cmd ENOENT"));
225-
226- const abortController = new AbortController();
227- await conn.connectClient(false, abortController.signal);
228-
229- expect(conn.status).toBe("error");
230- expect(conn.errors[0]).toContain('command "test-cmd" not found');
231- expect(mockConnect).toHaveBeenCalled();
232- });
233-
234- it.skip("should include stderr output in error message when stdio command fails", async () => {
235- // Clear any existing mocks to ensure we get real behavior
236- jest.restoreAllMocks();
237-
238- // Use a command that will definitely fail and produce stderr output
239- const failingOptions = {
240- name: "failing-mcp",
241- id: "failing-id",
242- transport: {
243- type: "stdio" as const,
244- command: "node",
245- args: [
246- "-e",
247- "console.error('Custom error message from stderr'); process.exit(1);",
248- ],
249- },
250- timeout: 5000, // Give enough time for the command to run and fail
251- };
252-
253- const conn = new MCPConnection(failingOptions);
254- const abortController = new AbortController();
255-
256- await conn.connectClient(false, abortController.signal);
257-
258- expect(conn.status).toBe("error");
259- expect(conn.errors).toHaveLength(1);
260- expect(conn.errors[0]).toContain("Failed to connect");
261- expect(conn.errors[0]).toContain("Process output:");
262- expect(conn.errors[0]).toContain("STDERR:");
263- expect(conn.errors[0]).toContain("Custom error message from stderr");
264- });
265- });
266-
267- describe.skip("actually connect to Filesystem MCP", () => {
268- it("should connect and include correct tools", async () => {
269- const conn = new MCPConnection({
270- id: "filesystem",
271- name: "Filesystem",
272- transport: {
273- type: "stdio" as const,
274- command: "npx",
275- args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
276- },
277- });
278-
279- try {
280- const abortController = new AbortController();
281- await conn.connectClient(false, abortController.signal);
282- expect(conn.status).toBe("connected");
283- } finally {
284- await conn.disconnect();
285- }
286- });
287- });
288-});
modified core/context/mcp/MCPConnection.ts +9 −4
@@ -47,7 +47,8 @@
4747 };
4848
4949 constructor(public options: MCPOptions) {
50- this.transport = this.constructTransport(options);
50+ // Don't construct transport in constructor to avoid blocking
51+ this.transport = {} as Transport; // Will be set in connectClient
5152
5253 this.client = new Client(
5354 {
@@ -132,7 +133,8 @@
132133 });
133134 }),
134135 (async () => {
135- this.transport = this.constructTransport(this.options);
136+ this.transport = await this.constructTransportAsync(this.options);
137+
136138 try {
137139 await this.client.connect(this.transport);
138140 } catch (error) {
@@ -295,7 +297,9 @@
295297 };
296298 }
297299
298- private constructTransport(options: MCPOptions): Transport {
300+ private async constructTransportAsync(
301+ options: MCPOptions,
302+ ): Promise<Transport> {
299303 switch (options.transport.type) {
300304 case "stdio":
301305 const env: Record<string, string> = options.transport.env
@@ -309,7 +313,7 @@
309313 // For non-Windows platforms, try to get the PATH from user shell
310314 if (process.platform !== "win32") {
311315 try {
312- const shellEnvPath = getEnvPathFromUserShell();
316+ const shellEnvPath = await getEnvPathFromUserShell();
313317 if (shellEnvPath && shellEnvPath !== process.env.PATH) {
314318 env.PATH = shellEnvPath;
315319 }
@@ -329,6 +333,7 @@
329333 command,
330334 args,
331335 env,
336+ cwd: options.transport.cwd,
332337 stderr: "pipe",
333338 });
334339
added core/context/mcp/MCPConnection.vitest.ts +333 −0
@@ -0,0 +1,333 @@
1+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2+import { beforeEach, describe, expect, it, vi } from "vitest";
3+import MCPConnection from "./MCPConnection";
4+import { StdioOptions } from "../../index.d.js";
5+
6+// Mock the shell path utility
7+vi.mock("../../util/shellPath", () => ({
8+ getEnvPathFromUserShell: vi
9+ .fn()
10+ .mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
11+}));
12+
13+describe("MCPConnection", () => {
14+ beforeEach(() => {
15+ vi.restoreAllMocks();
16+ });
17+
18+ describe("constructor", () => {
19+ it("should create instance with stdio transport", () => {
20+ const options = {
21+ name: "test-mcp",
22+ id: "test-id",
23+ transport: {
24+ type: "stdio" as const,
25+ command: "test-cmd",
26+ args: ["--test"],
27+ env: { TEST: "true" },
28+ },
29+ };
30+
31+ const conn = new MCPConnection(options);
32+ expect(conn).toBeInstanceOf(MCPConnection);
33+ expect(conn.status).toBe("not-connected");
34+ });
35+
36+ it("should create instance with stdio transport including cwd", () => {
37+ const options = {
38+ name: "test-mcp",
39+ id: "test-id",
40+ transport: {
41+ type: "stdio" as const,
42+ command: "test-cmd",
43+ args: ["--test"],
44+ env: { TEST: "true" },
45+ cwd: "/path/to/working/directory",
46+ },
47+ };
48+
49+ const conn = new MCPConnection(options);
50+ expect(conn).toBeInstanceOf(MCPConnection);
51+ expect(conn.status).toBe("not-connected");
52+ if (conn.options.transport.type === "stdio") {
53+ expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
54+ }
55+ });
56+
57+ it("should create instance with websocket transport", () => {
58+ const options = {
59+ name: "test-mcp",
60+ id: "test-id",
61+ transport: {
62+ type: "websocket" as const,
63+ url: "ws://test.com",
64+ },
65+ };
66+
67+ const conn = new MCPConnection(options);
68+ expect(conn).toBeInstanceOf(MCPConnection);
69+ expect(conn.status).toBe("not-connected");
70+ });
71+
72+ it("should create instance with SSE transport", () => {
73+ const options = {
74+ name: "test-mcp",
75+ id: "test-id",
76+ transport: {
77+ type: "sse" as const,
78+ url: "http://test.com/events",
79+ },
80+ };
81+
82+ const conn = new MCPConnection(options);
83+ expect(conn).toBeInstanceOf(MCPConnection);
84+ expect(conn.status).toBe("not-connected");
85+ });
86+
87+ it("should create instance with SSE transport and custom headers", () => {
88+ const options = {
89+ name: "test-mcp",
90+ id: "test-id",
91+ transport: {
92+ type: "sse" as const,
93+ url: "http://test.com/events",
94+ requestOptions: {
95+ headers: {
96+ Authorization: "Bearer token123",
97+ "X-Custom-Header": "custom-value",
98+ },
99+ },
100+ },
101+ };
102+
103+ const conn = new MCPConnection(options);
104+ expect(conn).toBeInstanceOf(MCPConnection);
105+ expect(conn.status).toBe("not-connected");
106+ });
107+
108+ it("should throw on invalid transport type", async () => {
109+ const options = {
110+ name: "test-mcp",
111+ id: "test-id",
112+ transport: {
113+ type: "invalid",
114+ } as any,
115+ };
116+
117+ const conn = new MCPConnection(options);
118+ const abortController = new AbortController();
119+
120+ // The validation now happens during connectClient, not constructor
121+ await conn.connectClient(false, abortController.signal);
122+
123+ expect(conn.status).toBe("error");
124+ expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
125+ });
126+ });
127+
128+ describe("getStatus", () => {
129+ it("should return current status", () => {
130+ const options = {
131+ name: "test-mcp",
132+ id: "test-id",
133+ transport: {
134+ type: "stdio" as const,
135+ command: "test",
136+ args: [],
137+ },
138+ };
139+
140+ const conn = new MCPConnection(options);
141+ const status = conn.getStatus();
142+
143+ expect(status).toEqual({
144+ ...options,
145+ errors: [],
146+ prompts: [],
147+ resources: [],
148+ resourceTemplates: [],
149+ tools: [],
150+ status: "not-connected",
151+ });
152+ });
153+ });
154+
155+ describe("connectClient", () => {
156+ const options = {
157+ name: "test-mcp",
158+ id: "test-id",
159+ transport: {
160+ type: "stdio" as const,
161+ command: "test-cmd",
162+ args: [],
163+ },
164+ };
165+
166+ it("should connect successfully", async () => {
167+ const conn = new MCPConnection(options);
168+ const mockConnect = vi
169+ .spyOn(Client.prototype, "connect")
170+ .mockResolvedValue(undefined);
171+ const mockGetServerCapabilities = vi
172+ .spyOn(Client.prototype, "getServerCapabilities")
173+ .mockReturnValue({
174+ resources: {},
175+ tools: {},
176+ prompts: {},
177+ });
178+
179+ const mockListResources = vi
180+ .spyOn(Client.prototype, "listResources")
181+ .mockResolvedValue({
182+ resources: [{ name: "test-resource", uri: "test-uri" }],
183+ });
184+ const mockListTools = vi
185+ .spyOn(Client.prototype, "listTools")
186+ .mockResolvedValue({
187+ tools: [
188+ {
189+ name: "test-tool",
190+ inputSchema: {
191+ type: "object",
192+ },
193+ },
194+ ],
195+ });
196+ const mockListPrompts = vi
197+ .spyOn(Client.prototype, "listPrompts")
198+ .mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
199+
200+ const abortController = new AbortController();
201+ await conn.connectClient(false, abortController.signal);
202+
203+ expect(conn.status).toBe("connected");
204+ expect(conn.resources).toHaveLength(1);
205+ expect(conn.tools).toHaveLength(1);
206+ expect(conn.prompts).toHaveLength(1);
207+ expect(mockConnect).toHaveBeenCalled();
208+ });
209+
210+ it("should handle custom connection timeout", async () => {
211+ const conn = new MCPConnection({ ...options, timeout: 1500 });
212+ const mockConnect = vi
213+ .spyOn(Client.prototype, "connect")
214+ .mockImplementation(
215+ () => new Promise((resolve) => setTimeout(resolve, 1000)),
216+ );
217+
218+ // Mock the required methods for successful connection
219+ const mockGetServerCapabilities = vi
220+ .spyOn(Client.prototype, "getServerCapabilities")
221+ .mockReturnValue({
222+ resources: {},
223+ tools: {},
224+ prompts: {},
225+ });
226+
227+ const abortController = new AbortController();
228+ await conn.connectClient(false, abortController.signal);
229+
230+ expect(conn.status).toBe("connected");
231+ expect(mockConnect).toHaveBeenCalled();
232+ });
233+
234+ it("should handle connection timeout", async () => {
235+ const conn = new MCPConnection({ ...options, timeout: 50 });
236+ const mockConnect = vi
237+ .spyOn(Client.prototype, "connect")
238+ .mockImplementation(
239+ () => new Promise((resolve) => setTimeout(resolve, 100)),
240+ );
241+
242+ const abortController = new AbortController();
243+ await conn.connectClient(false, abortController.signal);
244+
245+ expect(conn.status).toBe("error");
246+ expect(conn.errors[0]).toContain("Failed to connect");
247+ // The connection should timeout before connect is called due to transport construction
248+ // Since transport construction happens first, and we're not mocking that,
249+ // the timeout will happen during transport construction or connect attempt
250+ });
251+
252+ it("should handle already connected state", async () => {
253+ const conn = new MCPConnection(options);
254+ conn.status = "connected";
255+
256+ const mockConnect = vi.spyOn(Client.prototype, "connect");
257+ const abortController = new AbortController();
258+
259+ await conn.connectClient(false, abortController.signal);
260+
261+ expect(mockConnect).not.toHaveBeenCalled();
262+ expect(conn.status).toBe("connected");
263+ });
264+
265+ it("should handle transport errors", async () => {
266+ const conn = new MCPConnection(options);
267+ const mockConnect = vi
268+ .spyOn(Client.prototype, "connect")
269+ .mockRejectedValue(new Error("spawn test-cmd ENOENT"));
270+
271+ const abortController = new AbortController();
272+ await conn.connectClient(false, abortController.signal);
273+
274+ expect(conn.status).toBe("error");
275+ expect(conn.errors[0]).toContain('command "test-cmd" not found');
276+ expect(mockConnect).toHaveBeenCalled();
277+ });
278+
279+ it.skip("should include stderr output in error message when stdio command fails", async () => {
280+ // Clear any existing mocks to ensure we get real behavior
281+ vi.restoreAllMocks();
282+
283+ // Use a command that will definitely fail and produce stderr output
284+ const failingOptions = {
285+ name: "failing-mcp",
286+ id: "failing-id",
287+ transport: {
288+ type: "stdio" as const,
289+ command: "node",
290+ args: [
291+ "-e",
292+ "console.error('Custom error message from stderr'); process.exit(1);",
293+ ],
294+ },
295+ timeout: 5000, // Give enough time for the command to run and fail
296+ };
297+
298+ const conn = new MCPConnection(failingOptions);
299+ const abortController = new AbortController();
300+
301+ await conn.connectClient(false, abortController.signal);
302+
303+ expect(conn.status).toBe("error");
304+ expect(conn.errors).toHaveLength(1);
305+ expect(conn.errors[0]).toContain("Failed to connect");
306+ expect(conn.errors[0]).toContain("Process output:");
307+ expect(conn.errors[0]).toContain("STDERR:");
308+ expect(conn.errors[0]).toContain("Custom error message from stderr");
309+ });
310+ });
311+
312+ describe.skip("actually connect to Filesystem MCP", () => {
313+ it("should connect and include correct tools", async () => {
314+ const conn = new MCPConnection({
315+ id: "filesystem",
316+ name: "Filesystem",
317+ transport: {
318+ type: "stdio" as const,
319+ command: "npx",
320+ args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
321+ },
322+ });
323+
324+ try {
325+ const abortController = new AbortController();
326+ await conn.connectClient(false, abortController.signal);
327+ expect(conn.status).toBe("connected");
328+ } finally {
329+ await conn.disconnect();
330+ }
331+ });
332+ });
333+});
deleted core/context/mcp/MCPManagerSingleton.test.ts +0 −219
@@ -1,219 +0,0 @@
1-import { MCPOptions } from "../..";
2-import MCPConnection from "./MCPConnection";
3-import { MCPManagerSingleton } from "./MCPManagerSingleton";
4-
5-// Create test versions with stubbed behavior
6-class TestMCPConnection extends MCPConnection {
7- constructor(options: MCPOptions) {
8- super(options);
9-
10- // Override with test implementations
11- this.client = {
12- close: async () => {},
13- connect: async () => {},
14- getServerCapabilities: () => ({}),
15- listResources: async () => ({ resources: [] }),
16- listTools: async () => ({ tools: [] }),
17- listPrompts: async () => ({ prompts: [] }),
18- } as any;
19-
20- this.abortController = new AbortController();
21- this.connectClient = jest.fn().mockResolvedValue(undefined);
22- this.getStatus = jest
23- .fn()
24- .mockReturnValue({ status: "connected", errors: [] });
25- }
26-}
27-
28-describe("MCPManagerSingleton", () => {
29- let manager: MCPManagerSingleton;
30- const testOptions: MCPOptions = {
31- name: "test-mcp",
32- id: "test-id",
33- transport: {
34- type: "stdio",
35- command: "test-command",
36- args: [],
37- },
38- };
39-
40- beforeEach(() => {
41- // Reset singleton
42- (MCPManagerSingleton as any).instance = undefined;
43- manager = MCPManagerSingleton.getInstance();
44-
45- // Replace the connections map with our own that will use TestMCPConnection
46- const connectionsMap = new Map<string, MCPConnection>();
47- Object.defineProperty(manager, "connections", {
48- value: connectionsMap,
49- writable: true,
50- });
51-
52- // Override createConnection to use our TestMCPConnection
53- manager.createConnection = function (
54- id: string,
55- options: MCPOptions,
56- ): MCPConnection {
57- if (!this.connections.has(id)) {
58- const connection = new TestMCPConnection(options);
59- this.connections.set(id, connection);
60- return connection;
61- } else {
62- return this.connections.get(id)!;
63- }
64- };
65- });
66-
67- describe("getInstance", () => {
68- it("should create singleton instance", () => {
69- const instance1 = MCPManagerSingleton.getInstance();
70- const instance2 = MCPManagerSingleton.getInstance();
71- expect(instance1).toBe(instance2);
72- });
73- });
74-
75- describe("createConnection", () => {
76- it("should create new connection if none exists", () => {
77- const connection = manager.createConnection("test-id", testOptions);
78- expect(connection).toBeInstanceOf(MCPConnection);
79- });
80-
81- it("should return existing connection if exists", () => {
82- const connection1 = manager.createConnection("test-id", testOptions);
83- const connection2 = manager.createConnection("test-id", testOptions);
84- expect(connection1).toBe(connection2);
85- });
86- });
87-
88- describe("getConnection", () => {
89- it("should return undefined for non-existent connection", () => {
90- expect(manager.getConnection("non-existent")).toBeUndefined();
91- });
92-
93- it("should return existing connection", () => {
94- const connection = manager.createConnection("test-id", testOptions);
95- expect(manager.getConnection("test-id")).toBe(connection);
96- });
97- });
98-
99- describe("removeConnection", () => {
100- it("should remove connection and close client", async () => {
101- // Create a spy on the close method
102- const connection = manager.createConnection(
103- "test-id",
104- testOptions,
105- ) as TestMCPConnection;
106- const closeSpy = jest.spyOn(connection.client, "close");
107-
108- await manager.removeConnection("test-id");
109-
110- expect(closeSpy).toHaveBeenCalled();
111- expect(manager.getConnection("test-id")).toBeUndefined();
112- });
113-
114- it("should handle non-existent connection", async () => {
115- await expect(
116- manager.removeConnection("non-existent"),
117- ).resolves.toBeUndefined();
118- });
119- });
120-
121- describe("setConnections", () => {
122- it("should add new connections", () => {
123- const servers = [testOptions];
124- manager.setConnections(servers, false);
125- expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
126- MCPConnection,
127- );
128- });
129-
130- it("should remove old connections", () => {
131- // Create initial connection
132- const connection = manager.createConnection(
133- "test-id",
134- testOptions,
135- ) as TestMCPConnection;
136- const abortSpy = jest.spyOn(connection.abortController, "abort");
137- const closeSpy = jest.spyOn(connection.client, "close");
138-
139- // Remove it by setting empty server list
140- manager.setConnections([], false);
141-
142- expect(abortSpy).toHaveBeenCalled();
143- expect(closeSpy).toHaveBeenCalled();
144- expect(manager.getConnection("test-id")).toBeUndefined();
145- });
146- });
147-
148- describe("refreshConnection", () => {
149- it("should refresh specific connection", async () => {
150- const connection = manager.createConnection(
151- "test-id",
152- testOptions,
153- ) as TestMCPConnection;
154-
155- await manager.refreshConnection("test-id");
156-
157- expect(connection.connectClient).toHaveBeenCalledWith(
158- true,
159- expect.any(AbortSignal),
160- );
161- });
162-
163- it("should throw error for non-existent connection", async () => {
164- await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
165- "MCP Connection non-existent not found",
166- );
167- });
168- });
169-
170- describe("refreshConnections", () => {
171- it("should refresh all connections", async () => {
172- const connection1 = manager.createConnection("test-id-1", {
173- ...testOptions,
174- id: "test-id-1",
175- }) as TestMCPConnection;
176-
177- const connection2 = manager.createConnection("test-id-2", {
178- ...testOptions,
179- id: "test-id-2",
180- }) as TestMCPConnection;
181-
182- await manager.refreshConnections(true);
183-
184- expect(connection1.connectClient).toHaveBeenCalledWith(
185- true,
186- expect.any(AbortSignal),
187- );
188- expect(connection2.connectClient).toHaveBeenCalledWith(
189- true,
190- expect.any(AbortSignal),
191- );
192- });
193-
194- it("should call onConnectionsRefreshed if defined", async () => {
195- const mockCallback = jest.fn();
196- manager.onConnectionsRefreshed = mockCallback;
197- manager.createConnection("test-id", testOptions);
198-
199- await manager.refreshConnections(true);
200-
201- expect(mockCallback).toHaveBeenCalled();
202- });
203- });
204-
205- describe("getStatuses", () => {
206- it("should return statuses for all connections", () => {
207- const connection = manager.createConnection(
208- "test-id",
209- testOptions,
210- ) as TestMCPConnection;
211- const mockStatus = { status: "connected", errors: [] };
212- connection.getStatus = jest.fn().mockReturnValue(mockStatus);
213-
214- const statuses = manager.getStatuses();
215- expect(statuses).toHaveLength(1);
216- expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
217- });
218- });
219-});
modified core/context/mcp/MCPManagerSingleton.ts +17 −0
@@ -161,4 +161,21 @@
161161 client: connection.client,
162162 }));
163163 }
164+
165+ async getPrompt(
166+ serverName: string,
167+ promptName: string,
168+ args: Record<string, string> = {},
169+ ) {
170+ const connection = this.connections.get(serverName);
171+ if (!connection) {
172+ throw new Error(
173+ `Error getting prompt: MCP Connection ${serverName} not found`,
174+ );
175+ }
176+ return await connection.client.getPrompt({
177+ name: promptName,
178+ arguments: args,
179+ });
180+ }
164181 }
added core/context/mcp/MCPManagerSingleton.vitest.ts +219 −0
@@ -0,0 +1,219 @@
1+import { beforeEach, describe, expect, it, vi } from "vitest";
2+import { MCPOptions } from "../..";
3+import MCPConnection from "./MCPConnection";
4+import { MCPManagerSingleton } from "./MCPManagerSingleton";
5+
6+// Create test versions with stubbed behavior
7+class TestMCPConnection extends MCPConnection {
8+ constructor(options: MCPOptions) {
9+ super(options);
10+
11+ // Override with test implementations
12+ this.client = {
13+ close: async () => {},
14+ connect: async () => {},
15+ getServerCapabilities: () => ({}),
16+ listResources: async () => ({ resources: [] }),
17+ listTools: async () => ({ tools: [] }),
18+ listPrompts: async () => ({ prompts: [] }),
19+ } as any;
20+
21+ this.abortController = new AbortController();
22+ this.connectClient = vi.fn().mockResolvedValue(undefined);
23+ this.getStatus = vi
24+ .fn()
25+ .mockReturnValue({ status: "connected", errors: [] });
26+ }
27+}
28+
29+describe("MCPManagerSingleton", () => {
30+ let manager: MCPManagerSingleton;
31+ const testOptions: MCPOptions = {
32+ name: "test-mcp",
33+ id: "test-id",
34+ transport: {
35+ type: "stdio",
36+ command: "test-command",
37+ args: [],
38+ },
39+ };
40+
41+ beforeEach(() => {
42+ // Reset singleton
43+ (MCPManagerSingleton as any).instance = undefined;
44+ manager = MCPManagerSingleton.getInstance();
45+
46+ // Replace the connections map with our own that will use TestMCPConnection
47+ const connectionsMap = new Map<string, MCPConnection>();
48+ Object.defineProperty(manager, "connections", {
49+ value: connectionsMap,
50+ writable: true,
51+ });
52+
53+ // Override createConnection to use our TestMCPConnection
54+ manager.createConnection = function (
55+ id: string,
56+ options: MCPOptions,
57+ ): MCPConnection {
58+ if (this.connections.has(id)) {
59+ return this.connections.get(id)!;
60+ }
61+ const connection = new TestMCPConnection(options);
62+ this.connections.set(id, connection);
63+ return connection;
64+ };
65+ });
66+
67+ describe("getInstance", () => {
68+ it("should create singleton instance", () => {
69+ const instance1 = MCPManagerSingleton.getInstance();
70+ const instance2 = MCPManagerSingleton.getInstance();
71+ expect(instance1).toBe(instance2);
72+ });
73+ });
74+
75+ describe("createConnection", () => {
76+ it("should create new connection if none exists", () => {
77+ const connection = manager.createConnection("test-id", testOptions);
78+ expect(connection).toBeInstanceOf(MCPConnection);
79+ });
80+
81+ it("should return existing connection if exists", () => {
82+ const connection1 = manager.createConnection("test-id", testOptions);
83+ const connection2 = manager.createConnection("test-id", testOptions);
84+ expect(connection1).toBe(connection2);
85+ });
86+ });
87+
88+ describe("getConnection", () => {
89+ it("should return undefined for non-existent connection", () => {
90+ expect(manager.getConnection("non-existent")).toBeUndefined();
91+ });
92+
93+ it("should return existing connection", () => {
94+ const connection = manager.createConnection("test-id", testOptions);
95+ expect(manager.getConnection("test-id")).toBe(connection);
96+ });
97+ });
98+
99+ describe("removeConnection", () => {
100+ it("should remove connection and close client", async () => {
101+ // Create a spy on the close method
102+ const connection = manager.createConnection(
103+ "test-id",
104+ testOptions,
105+ ) as TestMCPConnection;
106+ const closeSpy = vi.spyOn(connection.client, "close");
107+
108+ await manager.removeConnection("test-id");
109+
110+ expect(closeSpy).toHaveBeenCalled();
111+ expect(manager.getConnection("test-id")).toBeUndefined();
112+ });
113+
114+ it("should handle non-existent connection", async () => {
115+ await expect(
116+ manager.removeConnection("non-existent"),
117+ ).resolves.toBeUndefined();
118+ });
119+ });
120+
121+ describe("setConnections", () => {
122+ it("should add new connections", () => {
123+ const servers = [testOptions];
124+ manager.setConnections(servers, false);
125+ expect(manager.getConnection(testOptions.id)).toBeInstanceOf(
126+ MCPConnection,
127+ );
128+ });
129+
130+ it("should remove old connections", () => {
131+ // Create initial connection
132+ const connection = manager.createConnection(
133+ "test-id",
134+ testOptions,
135+ ) as TestMCPConnection;
136+ const abortSpy = vi.spyOn(connection.abortController, "abort");
137+ const closeSpy = vi.spyOn(connection.client, "close");
138+
139+ // Remove it by setting empty server list
140+ manager.setConnections([], false);
141+
142+ expect(abortSpy).toHaveBeenCalled();
143+ expect(closeSpy).toHaveBeenCalled();
144+ expect(manager.getConnection("test-id")).toBeUndefined();
145+ });
146+ });
147+
148+ describe("refreshConnection", () => {
149+ it("should refresh specific connection", async () => {
150+ const connection = manager.createConnection(
151+ "test-id",
152+ testOptions,
153+ ) as TestMCPConnection;
154+
155+ await manager.refreshConnection("test-id");
156+
157+ expect(connection.connectClient).toHaveBeenCalledWith(
158+ true,
159+ expect.any(AbortSignal),
160+ );
161+ });
162+
163+ it("should throw error for non-existent connection", async () => {
164+ await expect(manager.refreshConnection("non-existent")).rejects.toThrow(
165+ "MCP Connection non-existent not found",
166+ );
167+ });
168+ });
169+
170+ describe("refreshConnections", () => {
171+ it("should refresh all connections", async () => {
172+ const connection1 = manager.createConnection("test-id-1", {
173+ ...testOptions,
174+ id: "test-id-1",
175+ }) as TestMCPConnection;
176+
177+ const connection2 = manager.createConnection("test-id-2", {
178+ ...testOptions,
179+ id: "test-id-2",
180+ }) as TestMCPConnection;
181+
182+ await manager.refreshConnections(true);
183+
184+ expect(connection1.connectClient).toHaveBeenCalledWith(
185+ true,
186+ expect.any(AbortSignal),
187+ );
188+ expect(connection2.connectClient).toHaveBeenCalledWith(
189+ true,
190+ expect.any(AbortSignal),
191+ );
192+ });
193+
194+ it("should call onConnectionsRefreshed if defined", async () => {
195+ const mockCallback = vi.fn();
196+ manager.onConnectionsRefreshed = mockCallback;
197+ manager.createConnection("test-id", testOptions);
198+
199+ await manager.refreshConnections(true);
200+
201+ expect(mockCallback).toHaveBeenCalled();
202+ });
203+ });
204+
205+ describe("getStatuses", () => {
206+ it("should return statuses for all connections", () => {
207+ const connection = manager.createConnection(
208+ "test-id",
209+ testOptions,
210+ ) as TestMCPConnection;
211+ const mockStatus = { status: "connected", errors: [] };
212+ connection.getStatus = vi.fn().mockReturnValue(mockStatus);
213+
214+ const statuses = manager.getStatuses();
215+ expect(statuses).toHaveLength(1);
216+ expect(statuses[0]).toEqual({ ...mockStatus, client: connection.client });
217+ });
218+ });
219+});
modified core/context/providers/DocsContextProvider.ts +13 −6
@@ -145,6 +145,11 @@
145145 async loadSubmenuItems(
146146 args: LoadSubmenuItemsArgs,
147147 ): Promise<ContextSubmenuItem[]> {
148+ const { config } = args;
149+ // This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
150+ const configDocsSet = new Set(
151+ config.docs?.map((doc) => doc.startUrl) || [],
152+ );
148153 // Get docs service
149154 const docsService = DocsService.getSingleton();
150155 if (!docsService) {
@@ -159,12 +164,14 @@
159164 // Get all indexed docs from the database
160165 const docs = (await docsService.listMetadata()) ?? [];
161166 for (const { startUrl, title, favicon } of docs) {
162- submenuItems.push({
163- title,
164- id: startUrl,
165- description: new URL(startUrl).hostname,
166- icon: favicon,
167- });
167+ if (configDocsSet.has(startUrl)) {
168+ submenuItems.push({
169+ title,
170+ id: startUrl,
171+ description: new URL(startUrl).hostname,
172+ icon: favicon,
173+ });
174+ }
168175 }
169176
170177 // Sort alphabetically
modified core/context/providers/HttpContextProvider.ts +4 −0
@@ -72,6 +72,10 @@
7272 description: item.description ?? "HTTP Context Item",
7373 content: item.content ?? "",
7474 name: item.name ?? this.options.title ?? "HTTP",
75+ uri: {
76+ type: item.uri.type,
77+ value: item.uri.value,
78+ },
7579 });
7680
7781 return Array.isArray(json)
modified core/context/providers/MCPContextProvider.ts +3 −1
@@ -56,7 +56,9 @@
5656 private insertInputToUriTemplate(uri: string, query: string): string {
5757 const TEMPLATE_VAR = "query";
5858 if (uri.includes(`{${TEMPLATE_VAR}}`)) {
59- return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
59+ // Sending an empty string will result in an error, so we instead send "null"
60+ const queryOrNull = query.trim() === "" ? "null" : query;
61+ return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull));
6062 }
6163 return uri;
6264 }
modified core/context/providers/SearchContextProvider.ts +7 −2
@@ -6,6 +6,7 @@
66 import { formatGrepSearchResults } from "../../util/grepSearch.js";
77 import { BaseContextProvider } from "../index.js";
88
9+const DEFAULT_MAX_SEARCH_CONTEXT_RESULTS = 200;
910 class SearchContextProvider extends BaseContextProvider {
1011 static description: ContextProviderDescription = {
1112 title: "search",
@@ -19,8 +20,12 @@
1920 query: string,
2021 extras: ContextProviderExtras,
2122 ): Promise<ContextItem[]> {
22- const results = await extras.ide.getSearchResults(query);
23- const formatted = formatGrepSearchResults(results);
23+ const results = await extras.ide.getSearchResults(
24+ query,
25+ this.options?.maxResults ?? DEFAULT_MAX_SEARCH_CONTEXT_RESULTS,
26+ );
27+ // Note, search context provider will not truncate result chars, but will limit number of results
28+ const { formatted } = formatGrepSearchResults(results);
2429 return [
2530 {
2631 description: "Search results",
modified core/context/providers/TerminalContextProvider.ts +3 −1
@@ -21,7 +21,9 @@
2121 return [
2222 {
2323 description: "The contents of the terminal",
24- content: `Current terminal contents:\n\n${content}`,
24+ content: `Current terminal contents:\n\n${
25+ content || "The terminal is empty."
26+ }`,
2527 name: "Terminal",
2628 },
2729 ];
deleted core/context/providers/_context-providers.test.ts +0 −69
@@ -1,69 +0,0 @@
1-import fetch from "node-fetch";
2-
3-import { contextProviderClassFromName } from ".";
4-import {
5- ContextProviderExtras,
6- ContextProviderWithParams,
7- IContextProvider,
8-} from "../..";
9-import { ConfigHandler } from "../../config/ConfigHandler";
10-import { LLMLogger } from "../../llm/logger";
11-import { TEST_DIR } from "../../test/testDir";
12-import FileSystemIde from "../../util/filesystem";
13-
14-const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
15- { name: "diff", params: {} },
16- { name: "currentFile", params: {} },
17- { name: "debugger", params: {} },
18- { name: "open", params: {} },
19- { name: "os", params: {} },
20- { name: "problems", params: {} },
21- { name: "terminal", params: {} },
22- { name: "tree", params: {} },
23-];
24-
25-async function getContextProviderExtras(
26- fullInput: string,
27-): Promise<ContextProviderExtras> {
28- const ide = new FileSystemIde(TEST_DIR);
29- const ideSettingsPromise = ide.getIdeSettings();
30- const llmLogger = new LLMLogger();
31- const configHandler = new ConfigHandler(
32- ide,
33- ideSettingsPromise,
34- llmLogger,
35- Promise.resolve(undefined),
36- );
37- const { config } = await configHandler.loadConfig();
38- if (!config) {
39- throw new Error("Config not found");
40- }
41-
42- return {
43- fullInput,
44- ide,
45- config,
46- embeddingsProvider: config.selectedModelByRole.embed,
47- fetch: fetch,
48- llm: config.modelsByRole.chat[0],
49- reranker: config.selectedModelByRole.rerank,
50- selectedCode: [],
51- };
52-}
53-
54-describe.skip("Should successfully run all context providers", () => {
55- const extrasPromise = getContextProviderExtras("Test");
56-
57- CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
58- test(`should successfully run ${provider.name} context provider`, async () => {
59- const cls = contextProviderClassFromName(provider.name) as any;
60- const instance: IContextProvider = new cls(provider.params);
61-
62- expect(instance.description.title).toBe(provider.name);
63-
64- const items = await instance.getContextItems("test", await extrasPromise);
65-
66- expect(Array.isArray(items)).toBe(true);
67- });
68- });
69-});
added core/context/providers/_context-providers.vitest.ts +76 −0
@@ -0,0 +1,76 @@
1+import fetch from "node-fetch";
2+
3+import { afterAll, describe, expect, test } from "vitest";
4+import { contextProviderClassFromName } from ".";
5+import {
6+ ContextProviderExtras,
7+ ContextProviderWithParams,
8+ IContextProvider,
9+} from "../..";
10+import { ConfigHandler } from "../../config/ConfigHandler";
11+import { LLMLogger } from "../../llm/logger";
12+import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
13+import FileSystemIde from "../../util/filesystem";
14+
15+const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
16+ { name: "diff", params: {} },
17+ { name: "currentFile", params: {} },
18+ { name: "debugger", params: {} },
19+ { name: "open", params: {} },
20+ { name: "os", params: {} },
21+ { name: "problems", params: {} },
22+ { name: "terminal", params: {} },
23+ { name: "tree", params: {} },
24+];
25+
26+async function getContextProviderExtras(
27+ fullInput: string,
28+): Promise<ContextProviderExtras> {
29+ setUpTestDir();
30+ const ide = new FileSystemIde(TEST_DIR);
31+ const ideSettingsPromise = ide.getIdeSettings();
32+ const llmLogger = new LLMLogger();
33+ const configHandler = new ConfigHandler(
34+ ide,
35+ ideSettingsPromise,
36+ llmLogger,
37+ Promise.resolve(undefined),
38+ );
39+ const { config } = await configHandler.loadConfig();
40+ if (!config) {
41+ throw new Error("Config not found");
42+ }
43+
44+ return {
45+ fullInput,
46+ ide,
47+ config,
48+ embeddingsProvider: config.selectedModelByRole.embed,
49+ fetch: fetch,
50+ llm: config.modelsByRole.chat[0],
51+ reranker: config.selectedModelByRole.rerank,
52+ selectedCode: [],
53+ isInAgentMode: true,
54+ };
55+}
56+
57+describe.skip("Should successfully run all context providers", () => {
58+ afterAll(() => {
59+ tearDownTestDir();
60+ });
61+
62+ const extrasPromise = getContextProviderExtras("Test");
63+
64+ CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {
65+ test(`should successfully run ${provider.name} context provider`, async () => {
66+ const cls = contextProviderClassFromName(provider.name) as any;
67+ const instance: IContextProvider = new cls(provider.params);
68+
69+ expect(instance.description.title).toBe(provider.name);
70+
71+ const items = await instance.getContextItems("test", await extrasPromise);
72+
73+ expect(Array.isArray(items)).toBe(true);
74+ });
75+ });
76+});
modified core/context/providers/index.ts +11 −1
@@ -1,7 +1,9 @@
11 import { BaseContextProvider } from "../";
22 import { ContextProviderName } from "../../";
3+import { Telemetry } from "../../util/posthog";
34
45 import ClipboardContextProvider from "./ClipboardContextProvider";
6+import CodebaseContextProvider from "./CodebaseContextProvider";
57 import CodeContextProvider from "./CodeContextProvider";
68 import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
79 import CurrentFileContextProvider from "./CurrentFileContextProvider";
@@ -56,6 +58,7 @@
5658 JiraIssuesContextProvider,
5759 PostgresContextProvider,
5860 DatabaseContextProvider,
61+ CodebaseContextProvider,
5962 CodeContextProvider,
6063 CurrentFileContextProvider,
6164 URLContextProvider,
@@ -73,5 +76,12 @@
7376 export function contextProviderClassFromName(
7477 name: ContextProviderName,
7578 ): typeof BaseContextProvider | undefined {
76- return Providers.find((cls) => cls.description.title === name);
79+ const provider = Providers.find((cls) => cls.description.title === name);
80+
81+ void Telemetry.capture("context_provider_load", {
82+ providerName: name,
83+ found: !!provider, // also capture those which user expected to be present
84+ });
85+
86+ return provider;
7787 }
modified core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +130 −1
@@ -1,14 +1,40 @@
11 // @ts-ignore
22 import nlp from "wink-nlp-utils";
33
4-import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
4+import {
5+ BranchAndDir,
6+ Chunk,
7+ ContextItem,
8+ ContinueConfig,
9+ IDE,
10+ ILLM,
11+ Tool,
12+ ToolExtras,
13+} from "../../../";
514 import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
615 import { chunkDocument } from "../../../indexing/chunk/chunk";
716 import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
817 import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
18+import { BuiltInToolNames } from "../../../tools/builtIn";
19+import { callBuiltInTool } from "../../../tools/callTool";
20+import { globSearchTool } from "../../../tools/definitions/globSearch";
21+import { grepSearchTool } from "../../../tools/definitions/grepSearch";
22+import { lsTool } from "../../../tools/definitions/lsTool";
23+import { readFileTool } from "../../../tools/definitions/readFile";
24+import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
25+import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
926
1027 const DEFAULT_CHUNK_SIZE = 384;
1128
29+const AVAILABLE_TOOLS: Tool[] = [
30+ globSearchTool,
31+ grepSearchTool,
32+ lsTool,
33+ readFileTool,
34+ viewRepoMapTool,
35+ viewSubdirectoryTool,
36+];
37+
1238 export interface RetrievalPipelineOptions {
1339 llm: ILLM;
1440 config: ContinueConfig;
@@ -155,4 +181,107 @@
155181 run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
156182 throw new Error("Not implemented");
157183 }
184+
185+ protected async retrieveWithTools(input: string): Promise<Chunk[]> {
186+ const toolSelectionPrompt = `Given the following user input: "${input}"
187+
188+Available tools:
189+${AVAILABLE_TOOLS.map((tool) => {
190+ const requiredParams = tool.function.parameters?.required || [];
191+ const properties = tool.function.parameters?.properties || {};
192+ const paramDescriptions = requiredParams
193+ .map(
194+ (param: any) => `${param}: ${properties[param]?.description || "string"}`,
195+ )
196+ .join(", ");
197+
198+ return `- ${tool.function.name}: ${tool.function.description}
199+ Required arguments: ${paramDescriptions || "none"}`;
200+}).join("\n")}
201+
202+Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
203+{
204+ "tools": [
205+ {
206+ "name": "<tool_name>",
207+ "args": { "<required_parameter_name>": "<required_parameter_value>" }
208+ }
209+ ]
210+}`;
211+
212+ // Get LLM response for tool selection
213+ const toolSelectionResponse = await this.options.llm.chat(
214+ [{ role: "user", content: toolSelectionPrompt }],
215+ new AbortController().signal,
216+ );
217+
218+ let toolCalls: { name: string; args: any }[] = [];
219+ try {
220+ const responseContent =
221+ typeof toolSelectionResponse.content === "string"
222+ ? toolSelectionResponse.content
223+ : toolSelectionResponse.content
224+ .map((part) => (part.type === "text" ? part.text : ""))
225+ .join("");
226+ const parsed = JSON.parse(responseContent);
227+ toolCalls = parsed.tools || [];
228+ } catch (e) {
229+ console.log(
230+ `Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`,
231+ e,
232+ );
233+ return [];
234+ }
235+
236+ // Execute tools and collect results
237+ const allContextItems: ContextItem[] = [];
238+
239+ const toolExtras: ToolExtras = {
240+ ide: this.options.ide,
241+ llm: this.options.llm,
242+ fetch: fetch,
243+ tool: grepSearchTool,
244+ config: this.options.config,
245+ };
246+
247+ for (const toolCall of toolCalls) {
248+ const tool = AVAILABLE_TOOLS.find(
249+ (t) => t.function.name === toolCall.name,
250+ )!;
251+
252+ const args = toolCall.args;
253+ if (toolCall.name === BuiltInToolNames.GrepSearch) {
254+ args.splitByFile = true;
255+ }
256+
257+ toolExtras.tool = tool;
258+ const contextItems = await callBuiltInTool(
259+ toolCall.name,
260+ args,
261+ toolExtras,
262+ );
263+ allContextItems.push(...contextItems);
264+ }
265+
266+ const chunks: Chunk[] = [];
267+
268+ // Transform ContextItem[] to Chunk[]
269+ for (let i = 0; i < allContextItems.length; i++) {
270+ const contextItem = allContextItems[i];
271+ const filepath = contextItem.uri?.value || contextItem.name || "unknown";
272+ const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
273+
274+ chunks.push({
275+ content: contextItem.content,
276+ startLine: -1,
277+ endLine: -1,
278+ digest: `file:///${cleanedFilepath}`,
279+ filepath: `file:///${cleanedFilepath}`,
280+ index: i,
281+ });
282+ }
283+
284+ console.log("retrieveWithTools chunks", chunks);
285+ return chunks;
286+ }
158287 }
modified core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +25 −7
@@ -1,4 +1,5 @@
11 import { Chunk } from "../../../";
2+import { Telemetry } from "../../../util/posthog";
23 import { findUriInDirs } from "../../../util/uri";
34 import { requestFilesFromRepoMap } from "../repoMapRequest";
45 import { deduplicateChunks } from "../util";
@@ -23,7 +24,8 @@
2324 try {
2425 ftsChunks = await this.retrieveFts(args, ftsNFinal);
2526 } catch (error) {
26- console.error("Error retrieving FTS chunks:", error);
27+ await Telemetry.captureError("no_reranker_fts_retrieval", error);
28+ // console.error("Error retrieving FTS chunks:", error);
2729 }
2830
2931 let embeddingsChunks: Chunk[] = [];
@@ -32,6 +34,7 @@
3234 ? await this.retrieveEmbeddings(input, embeddingsNFinal)
3335 : [];
3436 } catch (error) {
37+ await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
3538 console.error("Error retrieving embeddings:", error);
3639 }
3740
@@ -40,6 +43,10 @@
4043 recentlyEditedFilesChunks =
4144 await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
4245 } catch (error) {
46+ await Telemetry.captureError(
47+ "no_reranker_recently_edited_retrieval",
48+ error,
49+ );
4350 console.error("Error retrieving recently edited files:", error);
4451 }
4552
@@ -53,15 +60,26 @@
5360 filterDirectory,
5461 );
5562 } catch (error) {
63+ await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
5664 console.error("Error retrieving repo map chunks:", error);
5765 }
5866
59- retrievalResults.push(
60- ...recentlyEditedFilesChunks,
61- ...ftsChunks,
62- ...embeddingsChunks,
63- ...repoMapChunks,
64- );
67+ if (this.options.config.experimental?.codebaseToolCallingOnly) {
68+ let toolBasedChunks: Chunk[] = [];
69+ try {
70+ toolBasedChunks = await this.retrieveWithTools(input);
71+ } catch (error) {
72+ console.error("Error retrieving tool based chunks:", error);
73+ }
74+ retrievalResults.push(...toolBasedChunks);
75+ } else {
76+ retrievalResults.push(
77+ ...recentlyEditedFilesChunks,
78+ ...ftsChunks,
79+ ...embeddingsChunks,
80+ ...repoMapChunks,
81+ );
82+ }
6583
6684 if (filterDirectory) {
6785 // Backup if the individual retrieval methods don't listen
modified core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +24 −12
@@ -1,5 +1,6 @@
11 import { Chunk } from "../../..";
22 import { RETRIEVAL_PARAMS } from "../../../util/parameters";
3+import { Telemetry } from "../../../util/posthog";
34 import { findUriInDirs } from "../../../util/uri";
45 import { requestFilesFromRepoMap } from "../repoMapRequest";
56 import { deduplicateChunks } from "../util";
@@ -20,7 +21,8 @@
2021 try {
2122 ftsChunks = await this.retrieveFts(args, nRetrieve);
2223 } catch (error) {
23- console.error("Error retrieving FTS chunks:", error);
24+ await Telemetry.captureError("reranker_fts_retrieval", error);
25+ // console.error("Error retrieving FTS chunks:", error);
2426 }
2527
2628 let embeddingsChunks: Chunk[] = [];
@@ -29,6 +31,7 @@
2931 ? await this.retrieveEmbeddings(input, nRetrieve)
3032 : [];
3133 } catch (error) {
34+ await Telemetry.captureError("reranker_embeddings_retrieval", error);
3235 console.error("Error retrieving embeddings chunks:", error);
3336 }
3437
@@ -37,6 +40,7 @@
3740 recentlyEditedFilesChunks =
3841 await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
3942 } catch (error) {
43+ await Telemetry.captureError("reranker_recently_edited_retrieval", error);
4044 console.error("Error retrieving recently edited files chunks:", error);
4145 }
4246
@@ -50,15 +54,26 @@
5054 filterDirectory,
5155 );
5256 } catch (error) {
57+ await Telemetry.captureError("reranker_repo_map_retrieval", error);
5358 console.error("Error retrieving repo map chunks:", error);
5459 }
5560
56- retrievalResults.push(
57- ...recentlyEditedFilesChunks,
58- ...ftsChunks,
59- ...embeddingsChunks,
60- ...repoMapChunks,
61- );
61+ if (config.experimental?.codebaseToolCallingOnly) {
62+ let toolBasedChunks: Chunk[] = [];
63+ try {
64+ toolBasedChunks = await this.retrieveWithTools(input);
65+ } catch (error) {
66+ console.error("Error retrieving tool based chunks:", error);
67+ }
68+ retrievalResults.push(...toolBasedChunks);
69+ } else {
70+ retrievalResults.push(
71+ ...recentlyEditedFilesChunks,
72+ ...ftsChunks,
73+ ...embeddingsChunks,
74+ ...repoMapChunks,
75+ );
76+ }
6277
6378 if (filterDirectory) {
6479 // Backup if the individual retrieval methods don't listen
@@ -102,15 +117,12 @@
102117 chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
103118
104119 results.sort(
105- (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
120+ (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
106121 );
107122 results = results.slice(-this.options.nFinal);
108123 return results;
109124 } catch (e) {
110- void this.options.ide.showToast(
111- "warning",
112- `Failed to rerank retrieval results\n${e}`,
113- );
125+ console.warn(`Failed to rerank retrieval results\n${e}`);
114126 return chunks.slice(-this.options.nFinal);
115127 }
116128 }
modified core/context/retrieval/retrieval.ts +15 −6
@@ -79,14 +79,19 @@
7979
8080 if (results.length === 0) {
8181 if (extras.config.disableIndexing) {
82- void extras.ide.showToast("warning", "No results found.");
83- return [];
84- } else {
8582 void extras.ide.showToast(
8683 "warning",
87- "No results found. If you think this is an error, re-index your codebase.",
84+ "No results found (Indexing disabled).",
8885 );
89- // TODO - add "re-index" option to warning message which clears and reindexes codebase
86+ return [];
87+ }
88+ if (extras.isInAgentMode) {
89+ return [
90+ {
91+ ...INSTRUCTIONS_BASE_ITEM,
92+ content: "No results were found. Try using other tools.",
93+ },
94+ ];
9095 }
9196 return [];
9297 }
@@ -108,7 +113,11 @@
108113 }
109114
110115 return {
111- name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
116+ // Don't show line numbers for tool calls where startLine = -1
117+ name:
118+ r.startLine === -1
119+ ? baseName
120+ : `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
112121 description: last2Parts,
113122 content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
114123 uri: {
deleted core/context/retrieval/utils.test.ts +0 −117
@@ -1,117 +0,0 @@
1-// Generated by Continue
2-import { Chunk } from "../../index";
3-
4-import { deduplicateChunks } from "./util";
5-
6-describe("deduplicateChunks", () => {
7- it("returns an empty array when given an empty array", () => {
8- const chunks: Chunk[] = [];
9- const result = deduplicateChunks(chunks);
10- expect(result).toEqual([]);
11- });
12-
13- it("returns the same array when given an array with no duplicates", () => {
14- const chunks: Chunk[] = [
15- {
16- filepath: "file1.ts",
17- startLine: 0,
18- endLine: 1,
19- content: "chunk 1",
20- digest: "",
21- index: 0,
22- },
23- {
24- filepath: "file2.ts",
25- startLine: 2,
26- endLine: 3,
27- content: "chunk 2",
28- digest: "",
29- index: 1,
30- },
31- ];
32- const result = deduplicateChunks(chunks);
33- expect(result).toEqual(chunks);
34- });
35-
36- it("removes duplicate chunks", () => {
37- const chunks: Chunk[] = [
38- {
39- filepath: "file1.ts",
40- startLine: 0,
41- endLine: 1,
42- content: "chunk 1",
43- digest: "",
44- index: 0,
45- },
46- {
47- filepath: "file1.ts",
48- startLine: 0,
49- endLine: 1,
50- content: "chunk 1 duplicate",
51- digest: "",
52- index: 0,
53- },
54- {
55- filepath: "file2.ts",
56- startLine: 2,
57- endLine: 3,
58- content: "chunk 2",
59- digest: "",
60- index: 1,
61- },
62- ];
63- const result = deduplicateChunks(chunks);
64-
65- expect(result).toEqual([
66- {
67- filepath: "file1.ts",
68- startLine: 0,
69- endLine: 1,
70- content: "chunk 1",
71- digest: "",
72- index: 0,
73- },
74- {
75- filepath: "file2.ts",
76- startLine: 2,
77- endLine: 3,
78- content: "chunk 2",
79- digest: "",
80- index: 1,
81- },
82- ]);
83- });
84-
85- it("handles chunks with different contents but the same file lines as duplicates", () => {
86- const chunks: Chunk[] = [
87- {
88- filepath: "file1.ts",
89- startLine: 0,
90- endLine: 1,
91- content: "chunk 1",
92- digest: "",
93- index: 0,
94- },
95- {
96- filepath: "file1.ts",
97- startLine: 0,
98- endLine: 1,
99- content: "chunk 1 different content",
100- digest: "",
101- index: 0,
102- },
103- ];
104- const result = deduplicateChunks(chunks);
105-
106- expect(result).toEqual([
107- {
108- filepath: "file1.ts",
109- startLine: 0,
110- endLine: 1,
111- content: "chunk 1",
112- digest: "",
113- index: 0,
114- },
115- ]);
116- });
117-});
added core/context/retrieval/utils.vitest.ts +117 −0
@@ -0,0 +1,117 @@
1+// Generated by Continue
2+import { describe, expect, it } from "vitest";
3+import { Chunk } from "../../index";
4+import { deduplicateChunks } from "./util";
5+
6+describe("deduplicateChunks", () => {
7+ it("returns an empty array when given an empty array", () => {
8+ const chunks: Chunk[] = [];
9+ const result = deduplicateChunks(chunks);
10+ expect(result).toEqual([]);
11+ });
12+
13+ it("returns the same array when given an array with no duplicates", () => {
14+ const chunks: Chunk[] = [
15+ {
16+ filepath: "file1.ts",
17+ startLine: 0,
18+ endLine: 1,
19+ content: "chunk 1",
20+ digest: "",
21+ index: 0,
22+ },
23+ {
24+ filepath: "file2.ts",
25+ startLine: 2,
26+ endLine: 3,
27+ content: "chunk 2",
28+ digest: "",
29+ index: 1,
30+ },
31+ ];
32+ const result = deduplicateChunks(chunks);
33+ expect(result).toEqual(chunks);
34+ });
35+
36+ it("removes duplicate chunks", () => {
37+ const chunks: Chunk[] = [
38+ {
39+ filepath: "file1.ts",
40+ startLine: 0,
41+ endLine: 1,
42+ content: "chunk 1",
43+ digest: "",
44+ index: 0,
45+ },
46+ {
47+ filepath: "file1.ts",
48+ startLine: 0,
49+ endLine: 1,
50+ content: "chunk 1 duplicate",
51+ digest: "",
52+ index: 0,
53+ },
54+ {
55+ filepath: "file2.ts",
56+ startLine: 2,
57+ endLine: 3,
58+ content: "chunk 2",
59+ digest: "",
60+ index: 1,
61+ },
62+ ];
63+ const result = deduplicateChunks(chunks);
64+
65+ expect(result).toEqual([
66+ {
67+ filepath: "file1.ts",
68+ startLine: 0,
69+ endLine: 1,
70+ content: "chunk 1",
71+ digest: "",
72+ index: 0,
73+ },
74+ {
75+ filepath: "file2.ts",
76+ startLine: 2,
77+ endLine: 3,
78+ content: "chunk 2",
79+ digest: "",
80+ index: 1,
81+ },
82+ ]);
83+ });
84+
85+ it("handles chunks with different contents but the same file lines as duplicates", () => {
86+ const chunks: Chunk[] = [
87+ {
88+ filepath: "file1.ts",
89+ startLine: 0,
90+ endLine: 1,
91+ content: "chunk 1",
92+ digest: "",
93+ index: 0,
94+ },
95+ {
96+ filepath: "file1.ts",
97+ startLine: 0,
98+ endLine: 1,
99+ content: "chunk 1 different content",
100+ digest: "",
101+ index: 0,
102+ },
103+ ];
104+ const result = deduplicateChunks(chunks);
105+
106+ expect(result).toEqual([
107+ {
108+ filepath: "file1.ts",
109+ startLine: 0,
110+ endLine: 1,
111+ content: "chunk 1",
112+ digest: "",
113+ index: 0,
114+ },
115+ ]);
116+ });
117+});
deleted core/control-plane/mdm/mdm.test.ts +0 −210
@@ -1,210 +0,0 @@
1-import * as crypto from "crypto";
2-import { LicenseKeyData, validateLicenseKey } from "./mdm";
3-
4-// We'll create a real key pair once for all tests
5-const testKeyPair = crypto.generateKeyPairSync("rsa", {
6- modulusLength: 2048,
7- publicKeyEncoding: {
8- type: "spki",
9- format: "pem",
10- },
11- privateKeyEncoding: {
12- type: "pkcs8",
13- format: "pem",
14- },
15-});
16-
17-// Custom function to create test licenses with the new structure including unsignedData
18-function createTestLicense(
19- licenseData: LicenseKeyData,
20- apiUrl: string = "https://api.continue.dev",
21- useValidSignature: boolean = true,
22-): string {
23- // Convert license data to a string
24- const licenseDataStr = JSON.stringify(licenseData);
25-
26- // Create a signature with our generated private key
27- const sign = crypto.createSign("SHA256");
28- sign.update(licenseDataStr);
29- sign.end();
30-
31- let signature: string;
32- if (useValidSignature) {
33- signature = sign.sign(testKeyPair.privateKey, "base64");
34- } else {
35- // For invalid tests, create an intentionally wrong signature by signing different data
36- const wrongSign = crypto.createSign("SHA256");
37- wrongSign.update(licenseDataStr + "tampered");
38- wrongSign.end();
39- signature = wrongSign.sign(testKeyPair.privateKey, "base64");
40- }
41-
42- // Combine data, signature, and unsigned data into a license key
43- const licenseKeyObj = {
44- data: licenseDataStr,
45- signature: signature,
46- unsignedData: {
47- apiUrl: apiUrl,
48- },
49- };
50-
51- return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
52-}
53-
54-// We need to test the actual implementation - which we can't mock with ESM
55-// Instead, we'll have tests that bypass validation or are expected to fail
56-// depending on what we're testing
57-
58-test("validateLicenseKey returns false for malformed license key", () => {
59- // Test with a completely invalid license key
60- const invalidLicenseKey = "not-a-valid-license-key";
61-
62- // Test - no mocks, real validation
63- const result = validateLicenseKey(invalidLicenseKey);
64-
65- // Assert
66- expect(result.isValid).toBe(false);
67- expect(result.licenseKeyData).toBeUndefined();
68-});
69-
70-test("validateLicenseKey returns false for invalid JSON in license key", () => {
71- // Create a malformed but base64-encoded string
72- const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
73- "base64",
74- );
75-
76- // Test - no mocks, real validation
77- const result = validateLicenseKey(malformedLicenseKey);
78-
79- // Assert
80- expect(result.isValid).toBe(false);
81- expect(result.licenseKeyData).toBeUndefined();
82-});
83-
84-test("validateLicenseKey returns false for expired license", () => {
85- // Without mocking, we expect this to fail signature verification
86- // We're testing the date logic by itself
87- const licenseData: LicenseKeyData = {
88- customerId: "customer123",
89- createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
90- expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
91- };
92-
93- // Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
94- const expiredLicenseKey = createTestLicense(
95- licenseData,
96- "https://api.continue.dev",
97- );
98-
99- // Test - expect false, either due to signature or expiration - both are valid test cases
100- const result = validateLicenseKey(expiredLicenseKey);
101-
102- // Assert
103- expect(result.isValid).toBe(false);
104- expect(result.licenseKeyData).toBeUndefined();
105-});
106-
107-test("validateLicenseKey returns false for invalid signature", () => {
108- // Create license data with valid dates
109- const licenseData: LicenseKeyData = {
110- customerId: "customer123",
111- createdAt: new Date().toISOString(),
112- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
113- };
114-
115- // Create a license with an invalid signature but valid unsignedData structure
116- const invalidSignatureKey = createTestLicense(
117- licenseData,
118- "https://api.continue.dev",
119- false,
120- );
121-
122- // Test - no mocks, real validation
123- const result = validateLicenseKey(invalidSignatureKey);
124-
125- // Assert
126- expect(result.isValid).toBe(false);
127- expect(result.licenseKeyData).toBeUndefined();
128-});
129-
130-test("validateLicenseKey handles JSON parsing errors gracefully", () => {
131- // Create a base64 string that decodes to valid JSON but lacks required fields
132- const invalidStructureKey = Buffer.from(
133- JSON.stringify({
134- notTheRightField: "wrong structure",
135- }),
136- ).toString("base64");
137-
138- // Test - no mocks, real validation
139- const result = validateLicenseKey(invalidStructureKey);
140-
141- // Assert
142- expect(result.isValid).toBe(false);
143- expect(result.licenseKeyData).toBeUndefined();
144-});
145-
146-test("validateLicenseKey handles missing unsignedData gracefully", () => {
147- // Create a license key structure without unsignedData field
148- const licenseData: LicenseKeyData = {
149- customerId: "customer123",
150- createdAt: new Date().toISOString(),
151- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
152- };
153-
154- const licenseDataStr = JSON.stringify(licenseData);
155- const sign = crypto.createSign("SHA256");
156- sign.update(licenseDataStr);
157- sign.end();
158- const signature = sign.sign(testKeyPair.privateKey, "base64");
159-
160- // Create license key without unsignedData
161- const licenseKeyObj = {
162- data: licenseDataStr,
163- signature: signature,
164- // Missing unsignedData field
165- };
166-
167- const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
168- "base64",
169- );
170-
171- // Test - no mocks, real validation
172- const result = validateLicenseKey(licenseKey);
173-
174- // Assert - should fail due to signature verification with wrong public key
175- expect(result.isValid).toBe(false);
176- expect(result.licenseKeyData).toBeUndefined();
177-});
178-
179-test("validateLicenseKey handles invalid unsignedData structure", () => {
180- // Create license data with valid dates
181- const licenseData: LicenseKeyData = {
182- customerId: "customer123",
183- createdAt: new Date().toISOString(),
184- expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
185- };
186-
187- const licenseDataStr = JSON.stringify(licenseData);
188- const sign = crypto.createSign("SHA256");
189- sign.update(licenseDataStr);
190- sign.end();
191- const signature = sign.sign(testKeyPair.privateKey, "base64");
192-
193- // Create license key with invalid unsignedData structure
194- const licenseKeyObj = {
195- data: licenseDataStr,
196- signature: signature,
197- unsignedData: "not an object", // Should be an object with apiUrl
198- };
199-
200- const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
201- "base64",
202- );
203-
204- // Test - no mocks, real validation
205- const result = validateLicenseKey(licenseKey);
206-
207- // Assert - should fail due to signature verification with wrong public key
208- expect(result.isValid).toBe(false);
209- expect(result.licenseKeyData).toBeUndefined();
210-});
added core/control-plane/mdm/mdm.vitest.ts +211 −0
@@ -0,0 +1,211 @@
1+import * as crypto from "crypto";
2+import { expect, test } from "vitest";
3+import { LicenseKeyData, validateLicenseKey } from "./mdm";
4+
5+// We'll create a real key pair once for all tests
6+const testKeyPair = crypto.generateKeyPairSync("rsa", {
7+ modulusLength: 2048,
8+ publicKeyEncoding: {
9+ type: "spki",
10+ format: "pem",
11+ },
12+ privateKeyEncoding: {
13+ type: "pkcs8",
14+ format: "pem",
15+ },
16+});
17+
18+// Custom function to create test licenses with the new structure including unsignedData
19+function createTestLicense(
20+ licenseData: LicenseKeyData,
21+ apiUrl: string = "https://api.continue.dev",
22+ useValidSignature: boolean = true,
23+): string {
24+ // Convert license data to a string
25+ const licenseDataStr = JSON.stringify(licenseData);
26+
27+ // Create a signature with our generated private key
28+ const sign = crypto.createSign("SHA256");
29+ sign.update(licenseDataStr);
30+ sign.end();
31+
32+ let signature: string;
33+ if (useValidSignature) {
34+ signature = sign.sign(testKeyPair.privateKey, "base64");
35+ } else {
36+ // For invalid tests, create an intentionally wrong signature by signing different data
37+ const wrongSign = crypto.createSign("SHA256");
38+ wrongSign.update(licenseDataStr + "tampered");
39+ wrongSign.end();
40+ signature = wrongSign.sign(testKeyPair.privateKey, "base64");
41+ }
42+
43+ // Combine data, signature, and unsigned data into a license key
44+ const licenseKeyObj = {
45+ data: licenseDataStr,
46+ signature: signature,
47+ unsignedData: {
48+ apiUrl: apiUrl,
49+ },
50+ };
51+
52+ return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
53+}
54+
55+// We need to test the actual implementation - which we can't mock with ESM
56+// Instead, we'll have tests that bypass validation or are expected to fail
57+// depending on what we're testing
58+
59+test("validateLicenseKey returns false for malformed license key", () => {
60+ // Test with a completely invalid license key
61+ const invalidLicenseKey = "not-a-valid-license-key";
62+
63+ // Test - no mocks, real validation
64+ const result = validateLicenseKey(invalidLicenseKey);
65+
66+ // Assert
67+ expect(result.isValid).toBe(false);
68+ expect(result.licenseKeyData).toBeUndefined();
69+});
70+
71+test("validateLicenseKey returns false for invalid JSON in license key", () => {
72+ // Create a malformed but base64-encoded string
73+ const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
74+ "base64",
75+ );
76+
77+ // Test - no mocks, real validation
78+ const result = validateLicenseKey(malformedLicenseKey);
79+
80+ // Assert
81+ expect(result.isValid).toBe(false);
82+ expect(result.licenseKeyData).toBeUndefined();
83+});
84+
85+test("validateLicenseKey returns false for expired license", () => {
86+ // Without mocking, we expect this to fail signature verification
87+ // We're testing the date logic by itself
88+ const licenseData: LicenseKeyData = {
89+ customerId: "customer123",
90+ createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
91+ expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
92+ };
93+
94+ // Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
95+ const expiredLicenseKey = createTestLicense(
96+ licenseData,
97+ "https://api.continue.dev",
98+ );
99+
100+ // Test - expect false, either due to signature or expiration - both are valid test cases
101+ const result = validateLicenseKey(expiredLicenseKey);
102+
103+ // Assert
104+ expect(result.isValid).toBe(false);
105+ expect(result.licenseKeyData).toBeUndefined();
106+});
107+
108+test("validateLicenseKey returns false for invalid signature", () => {
109+ // Create license data with valid dates
110+ const licenseData: LicenseKeyData = {
111+ customerId: "customer123",
112+ createdAt: new Date().toISOString(),
113+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
114+ };
115+
116+ // Create a license with an invalid signature but valid unsignedData structure
117+ const invalidSignatureKey = createTestLicense(
118+ licenseData,
119+ "https://api.continue.dev",
120+ false,
121+ );
122+
123+ // Test - no mocks, real validation
124+ const result = validateLicenseKey(invalidSignatureKey);
125+
126+ // Assert
127+ expect(result.isValid).toBe(false);
128+ expect(result.licenseKeyData).toBeUndefined();
129+});
130+
131+test("validateLicenseKey handles JSON parsing errors gracefully", () => {
132+ // Create a base64 string that decodes to valid JSON but lacks required fields
133+ const invalidStructureKey = Buffer.from(
134+ JSON.stringify({
135+ notTheRightField: "wrong structure",
136+ }),
137+ ).toString("base64");
138+
139+ // Test - no mocks, real validation
140+ const result = validateLicenseKey(invalidStructureKey);
141+
142+ // Assert
143+ expect(result.isValid).toBe(false);
144+ expect(result.licenseKeyData).toBeUndefined();
145+});
146+
147+test("validateLicenseKey handles missing unsignedData gracefully", () => {
148+ // Create a license key structure without unsignedData field
149+ const licenseData: LicenseKeyData = {
150+ customerId: "customer123",
151+ createdAt: new Date().toISOString(),
152+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
153+ };
154+
155+ const licenseDataStr = JSON.stringify(licenseData);
156+ const sign = crypto.createSign("SHA256");
157+ sign.update(licenseDataStr);
158+ sign.end();
159+ const signature = sign.sign(testKeyPair.privateKey, "base64");
160+
161+ // Create license key without unsignedData
162+ const licenseKeyObj = {
163+ data: licenseDataStr,
164+ signature: signature,
165+ // Missing unsignedData field
166+ };
167+
168+ const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
169+ "base64",
170+ );
171+
172+ // Test - no mocks, real validation
173+ const result = validateLicenseKey(licenseKey);
174+
175+ // Assert - should fail due to signature verification with wrong public key
176+ expect(result.isValid).toBe(false);
177+ expect(result.licenseKeyData).toBeUndefined();
178+});
179+
180+test("validateLicenseKey handles invalid unsignedData structure", () => {
181+ // Create license data with valid dates
182+ const licenseData: LicenseKeyData = {
183+ customerId: "customer123",
184+ createdAt: new Date().toISOString(),
185+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
186+ };
187+
188+ const licenseDataStr = JSON.stringify(licenseData);
189+ const sign = crypto.createSign("SHA256");
190+ sign.update(licenseDataStr);
191+ sign.end();
192+ const signature = sign.sign(testKeyPair.privateKey, "base64");
193+
194+ // Create license key with invalid unsignedData structure
195+ const licenseKeyObj = {
196+ data: licenseDataStr,
197+ signature: signature,
198+ unsignedData: "not an object", // Should be an object with apiUrl
199+ };
200+
201+ const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
202+ "base64",
203+ );
204+
205+ // Test - no mocks, real validation
206+ const result = validateLicenseKey(licenseKey);
207+
208+ // Assert - should fail due to signature verification with wrong public key
209+ expect(result.isValid).toBe(false);
210+ expect(result.licenseKeyData).toBeUndefined();
211+});
modified core/core.ts +175 −85
@@ -10,9 +10,7 @@
1010 import { ConfigHandler } from "./config/ConfigHandler";
1111 import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
1212 import { addModel, deleteModel } from "./config/util";
13-import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
1413 import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
15-import { ContinueServerClient } from "./continueServer/stubs/client";
1614 import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
1715 import { getControlPlaneEnv } from "./control-plane/env";
1816 import { DevDataSqliteDb } from "./data/devdataSqlite";
@@ -21,7 +19,8 @@
2119 import DocsService from "./indexing/docs/DocsService";
2220 import { countTokens } from "./llm/countTokens";
2321 import Ollama from "./llm/llms/Ollama";
24-import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
22+import { EditAggregator } from "./nextEdit/context/aggregateEdits";
23+import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
2524 import { callTool } from "./tools/callTool";
2625 import { ChatDescriber } from "./util/chatDescriber";
2726 import { clipboardCache } from "./util/clipboardCache";
@@ -38,18 +37,21 @@
3837
3938 import {
4039 CompleteOnboardingPayload,
40+ ContextItemId,
4141 ContextItemWithId,
4242 IdeSettings,
4343 ModelDescription,
44+ Position,
4445 RangeInFile,
46+ ToolCall,
4547 type ContextItem,
46- type ContextItemId,
4748 type IDE,
4849 } from ".";
4950
50-import { ConfigYaml } from "@continuedev/config-yaml";
51+import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
5152 import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
52-import { isLocalAssistantFile } from "./config/loadLocalAssistants";
53+import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
54+import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
5355 import {
5456 setupLocalConfig,
5557 setupProviderConfig,
@@ -58,16 +60,18 @@
5860 import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
5961 import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
6062 import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
63+import { ApplyAbortManager } from "./edit/applyAbortManager";
6164 import { streamDiffLines } from "./edit/streamDiffLines";
6265 import { shouldIgnore } from "./indexing/shouldIgnore";
6366 import { walkDirCache } from "./indexing/walkDir";
6467 import { LLMLogger } from "./llm/logger";
6568 import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
6669 import { llmStreamChat } from "./llm/streamChat";
70+import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
71+import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
6772 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
6873 import { OnboardingModes } from "./protocol/core";
6974 import type { IMessenger, Message } from "./protocol/messenger";
70-import { StreamAbortManager } from "./util/abortManager";
7175 import { getUriPathBasename } from "./util/uri";
7276
7377 const hasRulesFiles = (uris: string[]): boolean => {
@@ -145,8 +149,20 @@
145149 this.messenger,
146150 );
147151
148- MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
149- await this.configHandler.reloadConfig();
152+ MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
153+ void this.configHandler.reloadConfig();
154+
155+ // Refresh @mention dropdown submenu items for MCP providers
156+ const mcpManager = MCPManagerSingleton.getInstance();
157+ const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
158+ (mcpId) => `mcp-${mcpId}`,
159+ );
160+
161+ if (mcpProviderNames.length > 0) {
162+ this.messenger.send("refreshSubmenuItems", {
163+ providers: mcpProviderNames,
164+ });
165+ }
150166 };
151167
152168 this.codeBaseIndexer = new CodebaseIndexer(
@@ -156,24 +172,26 @@
156172 this.globalContext.get("indexingPaused"),
157173 );
158174
159- this.configHandler.onConfigUpdate(async (result) => {
160- const serializedResult = await this.configHandler.getSerializedConfig();
161- this.messenger.send("configUpdate", {
162- result: serializedResult,
163- profileId:
164- this.configHandler.currentProfile?.profileDescription.id || null,
165- organizations: this.configHandler.getSerializedOrgs(),
166- selectedOrgId: this.configHandler.currentOrg.id,
167- });
168-
169- // update additional submenu context providers registered via VSCode API
170- const additionalProviders =
171- this.configHandler.getAdditionalSubmenuContextProviders();
172- if (additionalProviders.length > 0) {
173- this.messenger.send("refreshSubmenuItems", {
174- providers: additionalProviders,
175+ this.configHandler.onConfigUpdate((result) => {
176+ void (async () => {
177+ const serializedResult = await this.configHandler.getSerializedConfig();
178+ this.messenger.send("configUpdate", {
179+ result: serializedResult,
180+ profileId:
181+ this.configHandler.currentProfile?.profileDescription.id || null,
182+ organizations: this.configHandler.getSerializedOrgs(),
183+ selectedOrgId: this.configHandler.currentOrg.id,
175184 });
176- }
185+
186+ // update additional submenu context providers registered via VSCode API
187+ const additionalProviders =
188+ this.configHandler.getAdditionalSubmenuContextProviders();
189+ if (additionalProviders.length > 0) {
190+ this.messenger.send("refreshSubmenuItems", {
191+ providers: additionalProviders,
192+ });
193+ }
194+ })();
177195 });
178196
179197 // Dev Data Logger
@@ -183,11 +201,6 @@
183201 dataLogger.ideSettingsPromise = ideSettingsPromise;
184202
185203 void ideSettingsPromise.then((ideSettings) => {
186- const continueServerClient = new ContinueServerClient(
187- ideSettings.remoteConfigServerUrl,
188- ideSettings.userToken,
189- );
190-
191204 // Index on initialization
192205 void this.ide.getWorkspaceDirs().then(async (dirs) => {
193206 // Respect pauseCodebaseIndexOnStart user settings
@@ -366,6 +379,19 @@
366379 on("mcp/reloadServer", async (msg) => {
367380 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
368381 });
382+ on("mcp/getPrompt", async (msg) => {
383+ const { serverName, promptName, args } = msg.data;
384+ const prompt = await MCPManagerSingleton.getInstance().getPrompt(
385+ serverName,
386+ promptName,
387+ args,
388+ );
389+ const stringifiedPrompt = stringifyMcpPrompt(prompt);
390+ return {
391+ prompt: stringifiedPrompt,
392+ description: prompt.description,
393+ };
394+ });
369395 // Context providers
370396 on("context/addDocs", async (msg) => {
371397 void this.docsService.indexAndAdd(msg.data);
@@ -510,6 +536,11 @@
510536 throw new Error("No model selected");
511537 }
512538
539+ const abortManager = ApplyAbortManager.getInstance();
540+ const abortController = abortManager.get(
541+ data.fileUri ?? "current-file-stream",
542+ ); // not super important since currently cancelling apply will cancel all streams it's one file at a time
543+
513544 return streamDiffLines({
514545 highlighted: data.highlighted,
515546 prefix: data.prefix,
@@ -521,15 +552,14 @@
521552 : undefined,
522553 input: data.input,
523554 language: data.language,
524- onlyOneInsertion: false,
525555 overridePrompt: undefined,
526- abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
556+ abortController,
527557 });
528558 });
529559
530560 on("cancelApply", async (msg) => {
531- const abortManager = StreamAbortManager.getInstance();
532- abortManager.clear();
561+ const abortManager = ApplyAbortManager.getInstance();
562+ abortManager.clear(); // for now abort all streams
533563 });
534564
535565 on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
@@ -606,7 +636,7 @@
606636 // If it's a local assistant being created, we want to reload all assistants so it shows up in the list
607637 let localAssistantCreated = false;
608638 for (const uri of data.uris) {
609- if (isLocalAssistantFile(uri)) {
639+ if (isLocalDefinitionFile(uri)) {
610640 localAssistantCreated = true;
611641 }
612642 }
@@ -682,6 +712,52 @@
682712 }
683713 });
684714
715+ on("files/smallEdit", async ({ data }) => {
716+ const EDIT_AGGREGATION_OPTIONS = {
717+ deltaT: 1.0,
718+ deltaL: 5,
719+ maxEdits: 500,
720+ maxDuration: 120.0,
721+ contextSize: 5,
722+ };
723+
724+ EditAggregator.getInstance(
725+ EDIT_AGGREGATION_OPTIONS,
726+ (
727+ beforeAfterdiff: BeforeAfterDiff,
728+ cursorPosBeforeEdit: Position,
729+ cursorPosAfterPrevEdit: Position,
730+ ) => {
731+ void processSmallEdit(
732+ beforeAfterdiff,
733+ cursorPosBeforeEdit,
734+ cursorPosAfterPrevEdit,
735+ data.configHandler,
736+ data.getDefsFromLspFunction,
737+ this.ide,
738+ );
739+ },
740+ );
741+
742+ const workspaceDir =
743+ data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
744+
745+ // Store the latest context data
746+ const instance = EditAggregator.getInstance();
747+ (instance as any).latestContextData = {
748+ configHandler: data.configHandler,
749+ getDefsFromLspFunction: data.getDefsFromLspFunction,
750+ recentlyEditedRanges: data.recentlyEditedRanges,
751+ recentlyVisitedRanges: data.recentlyVisitedRanges,
752+ workspaceDir: workspaceDir,
753+ };
754+
755+ // queueMicrotask prevents blocking the UI thread during typing
756+ queueMicrotask(() => {
757+ void EditAggregator.getInstance().processEdits(data.actions);
758+ });
759+ });
760+
685761 // Docs, etc. indexing
686762 on("indexing/reindex", async (msg) => {
687763 if (msg.data.type === "docs") {
@@ -736,44 +812,9 @@
736812 return { url };
737813 });
738814
739- on("tools/call", async ({ data: { toolCall } }) => {
740- const { config } = await this.configHandler.loadConfig();
741- if (!config) {
742- throw new Error("Config not loaded");
743- }
744-
745- const tool = config.tools.find(
746- (t) => t.function.name === toolCall.function.name,
747- );
748-
749- if (!tool) {
750- throw new Error(`Tool ${toolCall.function.name} not found`);
751- }
752-
753- if (!config.selectedModelByRole.chat) {
754- throw new Error("No chat model selected");
755- }
756-
757- // Define a callback for streaming output updates
758- const onPartialOutput = (params: {
759- toolCallId: string;
760- contextItems: ContextItem[];
761- }) => {
762- this.messenger.send("toolCallPartialOutput", params);
763- };
764-
765- return await callTool(tool, toolCall, {
766- config,
767- ide: this.ide,
768- llm: config.selectedModelByRole.chat,
769- fetch: (url, init) =>
770- fetchwithRequestOptions(url, init, config.requestOptions),
771- tool,
772- toolCallId: toolCall.id,
773- onPartialOutput,
774- codeBaseIndexer: this.codeBaseIndexer,
775- });
776- });
815+ on("tools/call", async ({ data: { toolCall } }) =>
816+ this.handleToolCall(toolCall),
817+ );
777818
778819 on("isItemTooBig", async ({ data: { item } }) => {
779820 return this.isItemTooBig(item);
@@ -798,6 +839,47 @@
798839 });
799840 }
800841
842+ private async handleToolCall(toolCall: ToolCall) {
843+ const { config } = await this.configHandler.loadConfig();
844+ if (!config) {
845+ throw new Error("Config not loaded");
846+ }
847+
848+ const tool = config.tools.find(
849+ (t) => t.function.name === toolCall.function.name,
850+ );
851+
852+ if (!tool) {
853+ throw new Error(`Tool ${toolCall.function.name} not found`);
854+ }
855+
856+ if (!config.selectedModelByRole.chat) {
857+ throw new Error("No chat model selected");
858+ }
859+
860+ // Define a callback for streaming output updates
861+ const onPartialOutput = (params: {
862+ toolCallId: string;
863+ contextItems: ContextItem[];
864+ }) => {
865+ this.messenger.send("toolCallPartialOutput", params);
866+ };
867+
868+ const result = await callTool(tool, toolCall, {
869+ config,
870+ ide: this.ide,
871+ llm: config.selectedModelByRole.chat,
872+ fetch: (url, init) =>
873+ fetchwithRequestOptions(url, init, config.requestOptions),
874+ tool,
875+ toolCallId: toolCall.id,
876+ onPartialOutput,
877+ codeBaseIndexer: this.codeBaseIndexer,
878+ });
879+
880+ return result;
881+ }
882+
801883 private async isItemTooBig(item: ContextItemWithId) {
802884 const { config } = await this.configHandler.loadConfig();
803885 if (!config) {
@@ -885,7 +967,12 @@
885967 uri.endsWith(".prompt") ||
886968 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
887969 (uri.includes(".continue") && uri.endsWith(".yaml")) ||
888- uri.endsWith(RULES_MARKDOWN_FILENAME)
970+ uri.endsWith(RULES_MARKDOWN_FILENAME) ||
971+ BLOCK_TYPES.some(
972+ (blockType) =>
973+ uri.includes(`.continue/${blockType}`) ||
974+ uri.includes(`.continue\\${blockType}`),
975+ )
889976 ) {
890977 await this.configHandler.reloadConfig();
891978 } else if (
@@ -978,6 +1065,7 @@
9781065 query: string;
9791066 fullInput: string;
9801067 selectedCode: RangeInFile[];
1068+ isInAgentMode: boolean;
9811069 }>,
9821070 ) => {
9831071 const { config } = await this.configHandler.loadConfig();
@@ -1002,18 +1090,15 @@
10021090 // user doesn't need these in their config.json for the shortcuts to work
10031091 // option+enter
10041092 new CurrentFileContextProvider({}),
1005- // cmd+enter
1006- new CodebaseContextProvider({}),
10071093 ].find((provider) => provider.description.title === name);
10081094 if (!provider) {
10091095 return [];
10101096 }
10111097
10121098 try {
1013- const id: ContextItemId = {
1014- providerTitle: provider.description.title,
1015- itemId: uuidv4(),
1016- };
1099+ void Telemetry.capture("context_provider_get_context_items", {
1100+ name: provider.description.title,
1101+ });
10171102
10181103 const items = await provider.getContextItems(query, {
10191104 config,
@@ -1025,6 +1110,7 @@
10251110 reranker: config.selectedModelByRole.rerank,
10261111 fetch: (url, init) =>
10271112 fetchwithRequestOptions(url, init, config.requestOptions),
1113+ isInAgentMode: msg.data.isInAgentMode,
10281114 });
10291115
10301116 void Telemetry.capture(
@@ -1035,10 +1121,14 @@
10351121 true,
10361122 );
10371123
1038- return items.map((item) => ({
1039- ...item,
1040- id,
1041- }));
1124+ return items.map((item) => {
1125+ const id: ContextItemId = {
1126+ providerTitle: provider.description.title,
1127+ itemId: uuidv4(),
1128+ };
1129+
1130+ return { ...item, id };
1131+ });
10421132 } catch (e) {
10431133 let knownError = false;
10441134
deleted core/core_temp.ts +0 −0
deleted core/data/log.test.ts +0 −225
@@ -1,225 +0,0 @@
1-import { DevDataLogEvent } from "@continuedev/config-yaml";
2-import fs from "fs";
3-import path from "path";
4-import { IdeInfo, IdeSettings } from "..";
5-import { Core } from "../core";
6-import { getDevDataFilePath } from "../util/paths";
7-import { DataLogger } from "./log";
8-
9-// Only mock fetch, not fs
10-jest.mock("@continuedev/fetch");
11-
12-const TEST_EVENT: DevDataLogEvent = {
13- name: "tokensGenerated",
14- data: {
15- generatedTokens: 100,
16- model: "gpt-4",
17- promptTokens: 50,
18- provider: "openai",
19- },
20-};
21-
22-const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = {
23- name: "chatInteraction",
24- data: {
25- prompt: "Hello, world!",
26- completion: "Hello, world!",
27- modelProvider: "openai",
28- modelTitle: "gpt-4",
29- sessionId: "1234",
30- tools: ["test-tool1"],
31- },
32-};
33-
34-const SCHEMA = "0.2.0";
35-
36-describe("DataLogger", () => {
37- let dataLogger: DataLogger;
38- const tempDir = path.join(process.cwd(), "temp-test-data");
39- const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
40-
41- // Create temp directory for test files
42- beforeAll(() => {
43- if (!fs.existsSync(tempDir)) {
44- fs.mkdirSync(tempDir, { recursive: true });
45- }
46- });
47-
48- // Clean up temp directory after tests
49- afterAll(() => {
50- if (fs.existsSync(tempDir)) {
51- fs.rmSync(tempDir, { recursive: true, force: true });
52- }
53- });
54-
55- beforeEach(() => {
56- // Reset mocks
57- jest.clearAllMocks();
58-
59- // Remove test file if it exists
60- if (fs.existsSync(testFilePath)) {
61- fs.unlinkSync(testFilePath);
62- }
63-
64- // Get singleton instance
65- dataLogger = DataLogger.getInstance();
66-
67- // Mock core and required promises
68- dataLogger.core = {
69- configHandler: {
70- loadConfig: jest.fn().mockResolvedValue({
71- config: {
72- data: [],
73- },
74- }),
75- currentProfile: {
76- profileDescription: {
77- id: "test-profile-id",
78- },
79- },
80- controlPlaneClient: {
81- getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
82- },
83- },
84- } as unknown as Core;
85-
86- dataLogger.ideSettingsPromise = Promise.resolve({
87- userToken: "test-user-token",
88- } as IdeSettings);
89-
90- dataLogger.ideInfoPromise = Promise.resolve({
91- name: "VSCode",
92- version: "1.0.0",
93- extensionVersion: "0.1.0",
94- } as IdeInfo);
95- });
96-
97- describe("getInstance", () => {
98- it("should return the same instance when called multiple times", () => {
99- const instance1 = DataLogger.getInstance();
100- const instance2 = DataLogger.getInstance();
101- expect(instance1).toBe(instance2);
102- });
103- });
104-
105- describe("addBaseValues", () => {
106- it("should add base values to event data based on schema", async () => {
107- const mockZodSchema = {
108- shape: {
109- eventName: true,
110- timestamp: true,
111- schema: true,
112- userAgent: true,
113- selectedProfileId: true,
114- userId: true,
115- },
116- };
117-
118- const result = await dataLogger.addBaseValues(
119- { customField: "value" },
120- "testEvent",
121- SCHEMA,
122- mockZodSchema as any,
123- );
124-
125- expect(result).toEqual({
126- customField: "value",
127- eventName: "testEvent",
128- timestamp: expect.any(String),
129- schema: SCHEMA,
130- userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
131- selectedProfileId: "test-profile-id",
132- userId: "test-user-token",
133- });
134- });
135-
136- it("should not add fields not present in schema shape", async () => {
137- const mockZodSchema = {
138- shape: {
139- eventName: true,
140- // No other fields
141- },
142- };
143-
144- const result = await dataLogger.addBaseValues(
145- { customField: "value" },
146- "testEvent",
147- SCHEMA,
148- mockZodSchema as any,
149- );
150-
151- expect(result).toEqual({
152- customField: "value",
153- eventName: "testEvent",
154- });
155- });
156- });
157-
158- describe("logLocalData", () => {
159- it("should actually write data to the local file", async () => {
160- // Call the method to log data locally
161- await dataLogger.logLocalData(TEST_EVENT);
162-
163- // Verify the file was created
164- const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
165- expect(fs.existsSync(filepath)).toBe(true);
166-
167- // Read file contents and verify
168- const fileContent = fs.readFileSync(filepath, "utf8");
169- expect(fileContent).toContain('"generatedTokens":100');
170- expect(fileContent).toContain('"model":"gpt-4"');
171- expect(fileContent).toContain('"eventName":"tokensGenerated"');
172- });
173-
174- it("should write agent interaction data to local file", async () => {
175- // Call the method to log data locally
176- await dataLogger.logLocalData(TEST_AGENT_INTERACTION_EVENT);
177-
178- // Verify the file was created
179- const filepath = getDevDataFilePath(
180- TEST_AGENT_INTERACTION_EVENT.name,
181- SCHEMA,
182- );
183- expect(fs.existsSync(filepath)).toBe(true);
184-
185- // Read file contents and verify
186- const fileContent = fs.readFileSync(filepath, "utf8");
187- console.log("debug1 filecontent", fileContent);
188- expect(fileContent).toContain('"eventName":"chatInteraction"');
189- expect(fileContent).toContain('"prompt":"Hello, world!"');
190- expect(fileContent).toContain('"completion":"Hello, world!"');
191- expect(fileContent).toContain('"tools":["test-tool1"]');
192- });
193- });
194-
195- describe("logDevData", () => {
196- it("should log data locally and to configured destinations", async () => {
197- // Spy on logLocalData and logToOneDestination
198- const logLocalDataSpy = jest
199- .spyOn(dataLogger, "logLocalData")
200- .mockResolvedValue();
201- const logToOneDestinationSpy = jest
202- .spyOn(dataLogger, "logToOneDestination")
203- .mockResolvedValue();
204-
205- // Mock config with multiple data destinations
206- const mockConfig = {
207- config: {
208- data: [
209- { destination: "https://example.com/logs", schema: SCHEMA },
210- { destination: "file:///logs", schema: SCHEMA },
211- ],
212- },
213- };
214-
215- dataLogger.core!.configHandler.loadConfig = jest
216- .fn()
217- .mockResolvedValue(mockConfig);
218-
219- await dataLogger.logDevData(TEST_EVENT);
220-
221- expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
222- expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
223- });
224- });
225-});
added core/data/log.vitest.ts +233 −0
@@ -0,0 +1,233 @@
1+import { DevDataLogEvent } from "@continuedev/config-yaml";
2+import fs from "fs";
3+import path from "path";
4+import {
5+ afterAll,
6+ beforeAll,
7+ beforeEach,
8+ describe,
9+ expect,
10+ it,
11+ vi,
12+} from "vitest";
13+import { IdeInfo, IdeSettings } from "..";
14+import { Core } from "../core";
15+import { getDevDataFilePath } from "../util/paths";
16+import { DataLogger } from "./log";
17+
18+// Only mock fetch, not fs
19+vi.mock("@continuedev/fetch");
20+
21+const TEST_EVENT: DevDataLogEvent = {
22+ name: "tokensGenerated",
23+ data: {
24+ generatedTokens: 100,
25+ model: "gpt-4",
26+ promptTokens: 50,
27+ provider: "openai",
28+ },
29+};
30+
31+const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = {
32+ name: "chatInteraction",
33+ data: {
34+ prompt: "Hello, world!",
35+ completion: "Hello, world!",
36+ modelProvider: "openai",
37+ modelTitle: "gpt-4",
38+ sessionId: "1234",
39+ tools: ["test-tool1"],
40+ },
41+};
42+
43+const SCHEMA = "0.2.0";
44+
45+describe("DataLogger", () => {
46+ let dataLogger: DataLogger;
47+ const tempDir = path.join(process.cwd(), "temp-test-data");
48+ const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
49+
50+ // Create temp directory for test files
51+ beforeAll(() => {
52+ if (!fs.existsSync(tempDir)) {
53+ fs.mkdirSync(tempDir, { recursive: true });
54+ }
55+ });
56+
57+ // Clean up temp directory after tests
58+ afterAll(() => {
59+ if (fs.existsSync(tempDir)) {
60+ fs.rmSync(tempDir, { recursive: true, force: true });
61+ }
62+ });
63+
64+ beforeEach(() => {
65+ // Reset mocks
66+ vi.clearAllMocks();
67+
68+ // Remove test file if it exists
69+ if (fs.existsSync(testFilePath)) {
70+ fs.unlinkSync(testFilePath);
71+ }
72+
73+ // Get singleton instance
74+ dataLogger = DataLogger.getInstance();
75+
76+ // Mock core and required promises
77+ dataLogger.core = {
78+ configHandler: {
79+ loadConfig: vi.fn().mockResolvedValue({
80+ config: {
81+ data: [],
82+ },
83+ }),
84+ currentProfile: {
85+ profileDescription: {
86+ id: "test-profile-id",
87+ },
88+ },
89+ controlPlaneClient: {
90+ getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
91+ },
92+ },
93+ } as unknown as Core;
94+
95+ dataLogger.ideSettingsPromise = Promise.resolve({
96+ userToken: "test-user-token",
97+ } as IdeSettings);
98+
99+ dataLogger.ideInfoPromise = Promise.resolve({
100+ name: "VSCode",
101+ version: "1.0.0",
102+ extensionVersion: "0.1.0",
103+ } as IdeInfo);
104+ });
105+
106+ describe("getInstance", () => {
107+ it("should return the same instance when called multiple times", () => {
108+ const instance1 = DataLogger.getInstance();
109+ const instance2 = DataLogger.getInstance();
110+ expect(instance1).toBe(instance2);
111+ });
112+ });
113+
114+ describe("addBaseValues", () => {
115+ it("should add base values to event data based on schema", async () => {
116+ const mockZodSchema = {
117+ shape: {
118+ eventName: true,
119+ timestamp: true,
120+ schema: true,
121+ userAgent: true,
122+ selectedProfileId: true,
123+ userId: true,
124+ },
125+ };
126+
127+ const result = await dataLogger.addBaseValues(
128+ { customField: "value" },
129+ "testEvent",
130+ SCHEMA,
131+ mockZodSchema as any,
132+ );
133+
134+ expect(result).toEqual({
135+ customField: "value",
136+ eventName: "testEvent",
137+ timestamp: expect.any(String),
138+ schema: SCHEMA,
139+ userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
140+ selectedProfileId: "test-profile-id",
141+ userId: "test-user-token",
142+ });
143+ });
144+
145+ it("should not add fields not present in schema shape", async () => {
146+ const mockZodSchema = {
147+ shape: {
148+ eventName: true,
149+ // No other fields
150+ },
151+ };
152+
153+ const result = await dataLogger.addBaseValues(
154+ { customField: "value" },
155+ "testEvent",
156+ SCHEMA,
157+ mockZodSchema as any,
158+ );
159+
160+ expect(result).toEqual({
161+ customField: "value",
162+ eventName: "testEvent",
163+ });
164+ });
165+ });
166+
167+ describe("logLocalData", () => {
168+ it("should actually write data to the local file", async () => {
169+ // Call the method to log data locally
170+ await dataLogger.logLocalData(TEST_EVENT);
171+
172+ // Verify the file was created
173+ const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
174+ expect(fs.existsSync(filepath)).toBe(true);
175+
176+ // Read file contents and verify
177+ const fileContent = fs.readFileSync(filepath, "utf8");
178+ expect(fileContent).toContain('"generatedTokens":100');
179+ expect(fileContent).toContain('"model":"gpt-4"');
180+ expect(fileContent).toContain('"eventName":"tokensGenerated"');
181+ });
182+
183+ it("should write agent interaction data to local file", async () => {
184+ // Call the method to log data locally
185+ await dataLogger.logLocalData(TEST_AGENT_INTERACTION_EVENT);
186+
187+ // Verify the file was created
188+ const filepath = getDevDataFilePath(
189+ TEST_AGENT_INTERACTION_EVENT.name,
190+ SCHEMA,
191+ );
192+ expect(fs.existsSync(filepath)).toBe(true);
193+
194+ // Read file contents and verify
195+ const fileContent = fs.readFileSync(filepath, "utf8");
196+ expect(fileContent).toContain('"eventName":"chatInteraction"');
197+ expect(fileContent).toContain('"prompt":"Hello, world!"');
198+ expect(fileContent).toContain('"completion":"Hello, world!"');
199+ expect(fileContent).toContain('"tools":["test-tool1"]');
200+ });
201+ });
202+
203+ describe("logDevData", () => {
204+ it("should log data locally and to configured destinations", async () => {
205+ // Spy on logLocalData and logToOneDestination
206+ const logLocalDataSpy = vi
207+ .spyOn(dataLogger, "logLocalData")
208+ .mockResolvedValue();
209+ const logToOneDestinationSpy = vi
210+ .spyOn(dataLogger, "logToOneDestination")
211+ .mockResolvedValue();
212+
213+ // Mock config with multiple data destinations
214+ const mockConfig = {
215+ config: {
216+ data: [
217+ { destination: "https://example.com/logs", schema: SCHEMA },
218+ { destination: "file:///logs", schema: SCHEMA },
219+ ],
220+ },
221+ };
222+
223+ dataLogger.core!.configHandler.loadConfig = vi
224+ .fn()
225+ .mockResolvedValue(mockConfig);
226+
227+ await dataLogger.logDevData(TEST_EVENT);
228+
229+ expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
230+ expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
231+ });
232+ });
233+});
deleted core/diff/myers.test.ts +0 −56
@@ -1,56 +0,0 @@
1-import { dedent } from "../util";
2-
3-import { myersDiff } from "./myers";
4-
5-describe("Test myers diff function", () => {
6- test("should ...", () => {
7- const linesA = dedent`
8- A
9- B
10- C
11- D
12- E
13- `;
14- const linesB = dedent`
15- A
16- B
17- C'
18- D'
19- E
20- `;
21- const diffLines = myersDiff(linesA, linesB);
22- expect(diffLines).toEqual([
23- { type: "same", line: "A" },
24- { type: "same", line: "B" },
25- { type: "old", line: "C" },
26- { type: "old", line: "D" },
27- { type: "new", line: "C'" },
28- { type: "new", line: "D'" },
29- { type: "same", line: "E" },
30- ]);
31- });
32-
33- test("should ignore newline differences at end", () => {
34- const linesA = "A\nB\nC\n";
35- const linesB = "A\nB\nC";
36-
37- const diffLines = myersDiff(linesA, linesB);
38- expect(diffLines).toEqual([
39- { type: "same", line: "A" },
40- { type: "same", line: "B" },
41- { type: "same", line: "C" },
42- ]);
43- });
44-
45- test("should ignore single-line whitespace-only differences", () => {
46- const linesA = "A\n B\nC\n";
47- const linesB = "A\nB\nC";
48-
49- const diffLines = myersDiff(linesA, linesB);
50- expect(diffLines).toEqual([
51- { type: "same", line: "A" },
52- { type: "same", line: " B" },
53- { type: "same", line: "C" },
54- ]);
55- });
56-});
added core/diff/myers.vitest.ts +58 −0
@@ -0,0 +1,58 @@
1+import { describe, expect, test } from "vitest";
2+
3+import { dedent } from "../util";
4+
5+import { myersDiff } from "./myers";
6+
7+describe("Test myers diff function", () => {
8+ test("should ...", () => {
9+ const linesA = dedent`
10+ A
11+ B
12+ C
13+ D
14+ E
15+ `;
16+ const linesB = dedent`
17+ A
18+ B
19+ C'
20+ D'
21+ E
22+ `;
23+ const diffLines = myersDiff(linesA, linesB);
24+ expect(diffLines).toEqual([
25+ { type: "same", line: "A" },
26+ { type: "same", line: "B" },
27+ { type: "old", line: "C" },
28+ { type: "old", line: "D" },
29+ { type: "new", line: "C'" },
30+ { type: "new", line: "D'" },
31+ { type: "same", line: "E" },
32+ ]);
33+ });
34+
35+ test("should ignore newline differences at end", () => {
36+ const linesA = "A\nB\nC\n";
37+ const linesB = "A\nB\nC";
38+
39+ const diffLines = myersDiff(linesA, linesB);
40+ expect(diffLines).toEqual([
41+ { type: "same", line: "A" },
42+ { type: "same", line: "B" },
43+ { type: "same", line: "C" },
44+ ]);
45+ });
46+
47+ test("should ignore single-line whitespace-only differences", () => {
48+ const linesA = "A\n B\nC\n";
49+ const linesB = "A\nB\nC";
50+
51+ const diffLines = myersDiff(linesA, linesB);
52+ expect(diffLines).toEqual([
53+ { type: "same", line: "A" },
54+ { type: "same", line: " B" },
55+ { type: "same", line: "C" },
56+ ]);
57+ });
58+});
deleted core/diff/streamDiff.test.ts +0 −340
@@ -1,340 +0,0 @@
1-import fs from "node:fs";
2-import path from "node:path";
3-
4-// @ts-ignore no typings available
5-import { changed, diff as myersDiff } from "myers-diff";
6-import { streamDiff } from "../diff/streamDiff.js";
7-import { DiffLine, DiffLineType } from "../index.js";
8-import { generateLines } from "./util.js";
9-
10-// "modification" is an extra type used to represent an "old" + "new" diff line
11-type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
12-
13-const UNIFIED_DIFF_SYMBOLS = {
14- same: "",
15- new: "+",
16- old: "-",
17-};
18-
19-async function collectDiffs(
20- oldLines: string[],
21- newLines: string[],
22-): Promise<{ streamDiffs: DiffLine[]; myersDiffs: any }> {
23- const streamDiffs: DiffLine[] = [];
24-
25- for await (const diffLine of streamDiff(oldLines, generateLines(newLines))) {
26- streamDiffs.push(diffLine);
27- }
28-
29- const myersDiffs = myersDiff(oldLines.join("\n"), newLines.join("\n"));
30-
31- return { streamDiffs, myersDiffs };
32-}
33-
34-function getMyersDiffType(diff: any): MyersDiffTypes | undefined {
35- if (changed(diff.rhs) && !changed(diff.lhs)) {
36- return "new";
37- }
38-
39- if (!changed(diff.rhs) && changed(diff.lhs)) {
40- return "old";
41- }
42-
43- if (changed(diff.rhs) && changed(diff.lhs)) {
44- return "modification";
45- }
46-
47- return undefined;
48-}
49-
50-function displayDiff(diff: DiffLine[]) {
51- return diff
52- .map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`)
53- .join("\n");
54-}
55-
56-async function expectDiff(file: string) {
57- const testFilePath = path.join(
58- __dirname,
59- "diff",
60- "test-examples",
61- file + ".diff",
62- );
63- const testFileContents = fs.readFileSync(testFilePath, "utf-8");
64- const [oldText, newText, expectedDiff] = testFileContents
65- .split("\n---\n")
66- .map((s) => s.replace(/^\n+/, "").trimEnd());
67- const oldLines = oldText.split("\n");
68- const newLines = newText.split("\n");
69- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
70- const displayedDiff = displayDiff(streamDiffs);
71-
72- if (!expectedDiff || expectedDiff.trim() === "") {
73- console.log(
74- "Expected diff was empty. Writing computed diff to the test file",
75- );
76- fs.writeFileSync(
77- testFilePath,
78- `${oldText}\n\n---\n\n${newText}\n\n---\n\n${displayedDiff}`,
79- );
80-
81- throw new Error("Expected diff is empty");
82- }
83-
84- expect(displayedDiff).toEqual(expectedDiff);
85-}
86-
87-// We use a longer `)` string here to not get
88-// caught by the fuzzy matcher
89-describe("streamDiff(", () => {
90- test("no changes", async () => {
91- const oldLines = ["first item", "second arg", "third param"];
92- const newLines = ["first item", "second arg", "third param"];
93-
94- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
95-
96- expect(streamDiffs).toEqual([
97- { type: "same", line: "first item" },
98- { type: "same", line: "second arg" },
99- { type: "same", line: "third param" },
100- ]);
101-
102- expect(myersDiffs).toEqual([]);
103- });
104-
105- test("add new line", async () => {
106- const oldLines = ["first item", "second arg"];
107- const newLines = ["first item", "second arg", "third param"];
108-
109- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
110-
111- expect(streamDiffs).toEqual([
112- { type: "same", line: "first item" },
113- { type: "same", line: "second arg" },
114- { type: "new", line: "third param" },
115- ]);
116-
117- expect(myersDiffs.length).toEqual(1);
118- expect(getMyersDiffType(myersDiffs[0])).toBe("new");
119- });
120-
121- test("remove line", async () => {
122- const oldLines = ["first item", "second arg", "third param"];
123- const newLines = ["first item", "third param"];
124-
125- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
126-
127- expect(streamDiffs).toEqual([
128- { type: "same", line: "first item" },
129- { type: "old", line: "second arg" },
130- { type: "same", line: "third param" },
131- ]);
132-
133- expect(myersDiffs.length).toEqual(1);
134- expect(getMyersDiffType(myersDiffs[0])).toBe("old");
135- });
136-
137- test("modify line", async () => {
138- const oldLines = ["first item", "second arg", "third param"];
139- const newLines = ["first item", "modified second arg", "third param"];
140-
141- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
142-
143- expect(streamDiffs).toEqual([
144- { type: "same", line: "first item" },
145- { type: "old", line: "second arg" },
146- { type: "new", line: "modified second arg" },
147- { type: "same", line: "third param" },
148- ]);
149-
150- expect(myersDiffs.length).toEqual(1);
151- expect(getMyersDiffType(myersDiffs[0])).toBe("modification");
152- });
153-
154- test("add multiple lines", async () => {
155- const oldLines = ["first item", "fourth val"];
156- const newLines = ["first item", "second arg", "third param", "fourth val"];
157-
158- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
159-
160- expect(streamDiffs).toEqual([
161- { type: "same", line: "first item" },
162- { type: "new", line: "second arg" },
163- { type: "new", line: "third param" },
164- { type: "same", line: "fourth val" },
165- ]);
166-
167- // Multi-line addition
168- expect(myersDiffs[0].rhs.add).toEqual(2);
169- expect(getMyersDiffType(myersDiffs[0])).toBe("new");
170- });
171-
172- test("remove multiple lines", async () => {
173- const oldLines = ["first item", "second arg", "third param", "fourth val"];
174- const newLines = ["first item", "fourth val"];
175-
176- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
177-
178- expect(streamDiffs).toEqual([
179- { type: "same", line: "first item" },
180- { type: "old", line: "second arg" },
181- { type: "old", line: "third param" },
182- { type: "same", line: "fourth val" },
183- ]);
184-
185- // Multi-line deletion
186- expect(myersDiffs[0].lhs.del).toEqual(2);
187- expect(getMyersDiffType(myersDiffs[0])).toBe("old");
188- });
189-
190- test("empty old lines", async () => {
191- const oldLines: string[] = [];
192- const newLines = ["first item", "second arg"];
193-
194- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
195-
196- expect(streamDiffs).toEqual([
197- { type: "new", line: "first item" },
198- { type: "new", line: "second arg" },
199- ]);
200-
201- // Multi-line addition
202- expect(myersDiffs[0].rhs.add).toEqual(2);
203- expect(getMyersDiffType(myersDiffs[0])).toBe("new");
204- });
205-
206- test("empty new lines", async () => {
207- const oldLines = ["first item", "second arg"];
208- const newLines: string[] = [];
209-
210- const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
211-
212- expect(streamDiffs).toEqual([
213- { type: "old", line: "first item" },
214- { type: "old", line: "second arg" },
215- ]);
216-
217- // Multi-line deletion
218- expect(myersDiffs[0].lhs.del).toEqual(2);
219- expect(getMyersDiffType(myersDiffs[0])).toBe("old");
220- });
221-
222- test("tabs vs. spaces differences are ignored", async () => {
223- await expectDiff("fastapi-tabs-vs-spaces.py");
224- });
225-
226- test("trailing whitespaces should match ", async () => {
227- const oldLines = ["first item ", "second arg ", "third param "];
228-
229- const newLines = ["first item", "second arg", "third param "];
230-
231- const { streamDiffs } = await collectDiffs(oldLines, newLines);
232-
233- expect(streamDiffs).toEqual([
234- { type: "same", line: "first item " },
235- { type: "same", line: "second arg " },
236- { type: "same", line: "third param " },
237- ]);
238- });
239-
240- //indentation and whitespace handling
241- test.each([false, true])(
242- "ignores indentation changes for sufficiently long lines (trailingWhitespace: %s)",
243- async (trailingWhitespace) => {
244- let oldLines = [
245- " short",
246- " middle",
247- " a long enough line",
248- " short2",
249- "indented line",
250- "final line",
251- ];
252-
253- let newLines = [
254- "short",
255- "middle",
256- "a long enough line",
257- "short2",
258- " indented line",
259- "final line",
260- ];
261-
262- if (trailingWhitespace) {
263- oldLines = oldLines.map((line) => line + " ");
264- }
265-
266- const { streamDiffs } = await collectDiffs(oldLines, newLines);
267- const expected = trailingWhitespace
268- ? [
269- { type: "old", line: " short " },
270- { type: "new", line: "short" },
271- { type: "old", line: " middle " },
272- { type: "new", line: "middle" },
273- { type: "same", line: " a long enough line " },
274- { type: "same", line: " short2 " },
275- { type: "same", line: "indented line " },
276- { type: "same", line: "final line " },
277- ]
278- : [
279- { type: "old", line: " short" },
280- { type: "new", line: "short" },
281- { type: "old", line: " middle" },
282- { type: "new", line: "middle" },
283- { type: "same", line: " a long enough line" },
284- { type: "same", line: " short2" },
285- { type: "same", line: "indented line" },
286- { type: "same", line: "final line" },
287- ];
288-
289- expect(streamDiffs).toEqual(expected);
290- },
291- );
292-
293- test("preserves original lines for minor reindentation in simple block", async () => {
294- const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
295- const newLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
296-
297- const { streamDiffs } = await collectDiffs(oldLines, newLines);
298-
299- expect(streamDiffs).toEqual([
300- { type: "same", line: "if (checkValueOf(x)) {" },
301- { type: "same", line: " doSomethingWith(x);" },
302- { type: "same", line: "}" },
303- ]);
304- });
305-
306- test("uses new lines for nested reindentation changes", async () => {
307- const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
308- const newLines = [
309- "if (checkValueOf(x)) {",
310- " if (reallyCheckValueOf(x)) {",
311- " doSomethingElseWith(x);",
312- " }",
313- "}",
314- ];
315-
316- const { streamDiffs } = await collectDiffs(oldLines, newLines);
317-
318- expect(streamDiffs).toEqual([
319- { type: "same", line: "if (checkValueOf(x)) {" },
320- { type: "new", line: " if (reallyCheckValueOf(x)) {" },
321- { type: "old", line: " doSomethingWith(x);" },
322- { type: "new", line: " doSomethingElseWith(x);" },
323- { type: "old", line: "}" },
324- { type: "new", line: " }" },
325- { type: "new", line: "}" },
326- ]);
327- });
328-
329- test("FastAPI example", async () => {
330- await expectDiff("fastapi.py");
331- });
332-
333- test("FastAPI comments", async () => {
334- await expectDiff("add-comments.py");
335- });
336-
337- test("Mock LLM example", async () => {
338- await expectDiff("mock-llm.ts");
339- });
340-});
added core/diff/streamDiff.vitest.ts +337 −0
@@ -0,0 +1,337 @@
1+import fs from "node:fs";
2+import path from "node:path";
3+
4+import { describe, expect, test } from "vitest";
5+
6+// @ts-ignore no typings available
7+import { changed, diff as myersDiff } from "myers-diff";
8+import { streamDiff } from "../diff/streamDiff.js";
9+import { DiffLine, DiffLineType } from "../index.js";
10+import { generateLines } from "./util.js";
11+
12+// "modification" is an extra type used to represent an "old" + "new" diff line
13+type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
14+
15+const UNIFIED_DIFF_SYMBOLS = {
16+ same: "",
17+ new: "+",
18+ old: "-",
19+};
20+
21+async function collectDiffs(
22+ oldLines: string[],
23+ newLines: string[],
24+): Promise<{ streamDiffs: DiffLine[]; myersDiffs: any }> {
25+ const streamDiffs: DiffLine[] = [];
26+
27+ for await (const diffLine of streamDiff(oldLines, generateLines(newLines))) {
28+ streamDiffs.push(diffLine);
29+ }
30+
31+ const myersDiffs = myersDiff(oldLines.join("\n"), newLines.join("\n"));
32+
33+ return { streamDiffs, myersDiffs };
34+}
35+
36+function getMyersDiffType(diff: any): MyersDiffTypes | undefined {
37+ if (changed(diff.rhs) && !changed(diff.lhs)) {
38+ return "new";
39+ }
40+
41+ if (!changed(diff.rhs) && changed(diff.lhs)) {
42+ return "old";
43+ }
44+
45+ if (changed(diff.rhs) && changed(diff.lhs)) {
46+ return "modification";
47+ }
48+
49+ return undefined;
50+}
51+
52+function displayDiff(diff: DiffLine[]) {
53+ return diff
54+ .map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`)
55+ .join("\n");
56+}
57+
58+async function expectDiff(file: string) {
59+ const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
60+ const testFileContents = fs.readFileSync(testFilePath, "utf-8");
61+ const [oldText, newText, expectedDiff] = testFileContents
62+ .split("\n---\n")
63+ .map((s) => s.replace(/^\n+/, "").trimEnd());
64+ const oldLines = oldText.split("\n");
65+ const newLines = newText.split("\n");
66+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
67+ const displayedDiff = displayDiff(streamDiffs);
68+
69+ if (!expectedDiff || expectedDiff.trim() === "") {
70+ console.log(
71+ "Expected diff was empty. Writing computed diff to the test file",
72+ );
73+ fs.writeFileSync(
74+ testFilePath,
75+ `${oldText}\n\n---\n\n${newText}\n\n---\n\n${displayedDiff}`,
76+ );
77+
78+ throw new Error("Expected diff is empty");
79+ }
80+
81+ expect(displayedDiff).toEqual(expectedDiff);
82+}
83+
84+// We use a longer `)` string here to not get
85+// caught by the fuzzy matcher
86+describe("streamDiff(", () => {
87+ test("no changes", async () => {
88+ const oldLines = ["first item", "second arg", "third param"];
89+ const newLines = ["first item", "second arg", "third param"];
90+
91+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
92+
93+ expect(streamDiffs).toEqual([
94+ { type: "same", line: "first item" },
95+ { type: "same", line: "second arg" },
96+ { type: "same", line: "third param" },
97+ ]);
98+
99+ expect(myersDiffs).toEqual([]);
100+ });
101+
102+ test("add new line", async () => {
103+ const oldLines = ["first item", "second arg"];
104+ const newLines = ["first item", "second arg", "third param"];
105+
106+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
107+
108+ expect(streamDiffs).toEqual([
109+ { type: "same", line: "first item" },
110+ { type: "same", line: "second arg" },
111+ { type: "new", line: "third param" },
112+ ]);
113+
114+ expect(myersDiffs.length).toEqual(1);
115+ expect(getMyersDiffType(myersDiffs[0])).toBe("new");
116+ });
117+
118+ test("remove line", async () => {
119+ const oldLines = ["first item", "second arg", "third param"];
120+ const newLines = ["first item", "third param"];
121+
122+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
123+
124+ expect(streamDiffs).toEqual([
125+ { type: "same", line: "first item" },
126+ { type: "old", line: "second arg" },
127+ { type: "same", line: "third param" },
128+ ]);
129+
130+ expect(myersDiffs.length).toEqual(1);
131+ expect(getMyersDiffType(myersDiffs[0])).toBe("old");
132+ });
133+
134+ test("modify line", async () => {
135+ const oldLines = ["first item", "second arg", "third param"];
136+ const newLines = ["first item", "modified second arg", "third param"];
137+
138+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
139+
140+ expect(streamDiffs).toEqual([
141+ { type: "same", line: "first item" },
142+ { type: "old", line: "second arg" },
143+ { type: "new", line: "modified second arg" },
144+ { type: "same", line: "third param" },
145+ ]);
146+
147+ expect(myersDiffs.length).toEqual(1);
148+ expect(getMyersDiffType(myersDiffs[0])).toBe("modification");
149+ });
150+
151+ test("add multiple lines", async () => {
152+ const oldLines = ["first item", "fourth val"];
153+ const newLines = ["first item", "second arg", "third param", "fourth val"];
154+
155+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
156+
157+ expect(streamDiffs).toEqual([
158+ { type: "same", line: "first item" },
159+ { type: "new", line: "second arg" },
160+ { type: "new", line: "third param" },
161+ { type: "same", line: "fourth val" },
162+ ]);
163+
164+ // Multi-line addition
165+ expect(myersDiffs[0].rhs.add).toEqual(2);
166+ expect(getMyersDiffType(myersDiffs[0])).toBe("new");
167+ });
168+
169+ test("remove multiple lines", async () => {
170+ const oldLines = ["first item", "second arg", "third param", "fourth val"];
171+ const newLines = ["first item", "fourth val"];
172+
173+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
174+
175+ expect(streamDiffs).toEqual([
176+ { type: "same", line: "first item" },
177+ { type: "old", line: "second arg" },
178+ { type: "old", line: "third param" },
179+ { type: "same", line: "fourth val" },
180+ ]);
181+
182+ // Multi-line deletion
183+ expect(myersDiffs[0].lhs.del).toEqual(2);
184+ expect(getMyersDiffType(myersDiffs[0])).toBe("old");
185+ });
186+
187+ test("empty old lines", async () => {
188+ const oldLines: string[] = [];
189+ const newLines = ["first item", "second arg"];
190+
191+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
192+
193+ expect(streamDiffs).toEqual([
194+ { type: "new", line: "first item" },
195+ { type: "new", line: "second arg" },
196+ ]);
197+
198+ // Multi-line addition
199+ expect(myersDiffs[0].rhs.add).toEqual(2);
200+ expect(getMyersDiffType(myersDiffs[0])).toBe("new");
201+ });
202+
203+ test("empty new lines", async () => {
204+ const oldLines = ["first item", "second arg"];
205+ const newLines: string[] = [];
206+
207+ const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
208+
209+ expect(streamDiffs).toEqual([
210+ { type: "old", line: "first item" },
211+ { type: "old", line: "second arg" },
212+ ]);
213+
214+ // Multi-line deletion
215+ expect(myersDiffs[0].lhs.del).toEqual(2);
216+ expect(getMyersDiffType(myersDiffs[0])).toBe("old");
217+ });
218+
219+ test("tabs vs. spaces differences are ignored", async () => {
220+ await expectDiff("fastapi-tabs-vs-spaces.py");
221+ });
222+
223+ test("trailing whitespaces should match ", async () => {
224+ const oldLines = ["first item ", "second arg ", "third param "];
225+
226+ const newLines = ["first item", "second arg", "third param "];
227+
228+ const { streamDiffs } = await collectDiffs(oldLines, newLines);
229+
230+ expect(streamDiffs).toEqual([
231+ { type: "same", line: "first item " },
232+ { type: "same", line: "second arg " },
233+ { type: "same", line: "third param " },
234+ ]);
235+ });
236+
237+ //indentation and whitespace handling
238+ test.each([false, true])(
239+ "ignores indentation changes for sufficiently long lines (trailingWhitespace: %s)",
240+ async (trailingWhitespace) => {
241+ let oldLines = [
242+ " short",
243+ " middle",
244+ " a long enough line",
245+ " short2",
246+ "indented line",
247+ "final line",
248+ ];
249+
250+ let newLines = [
251+ "short",
252+ "middle",
253+ "a long enough line",
254+ "short2",
255+ " indented line",
256+ "final line",
257+ ];
258+
259+ if (trailingWhitespace) {
260+ oldLines = oldLines.map((line) => line + " ");
261+ }
262+
263+ const { streamDiffs } = await collectDiffs(oldLines, newLines);
264+ const expected = trailingWhitespace
265+ ? [
266+ { type: "old", line: " short " },
267+ { type: "new", line: "short" },
268+ { type: "old", line: " middle " },
269+ { type: "new", line: "middle" },
270+ { type: "same", line: " a long enough line " },
271+ { type: "same", line: " short2 " },
272+ { type: "same", line: "indented line " },
273+ { type: "same", line: "final line " },
274+ ]
275+ : [
276+ { type: "old", line: " short" },
277+ { type: "new", line: "short" },
278+ { type: "old", line: " middle" },
279+ { type: "new", line: "middle" },
280+ { type: "same", line: " a long enough line" },
281+ { type: "same", line: " short2" },
282+ { type: "same", line: "indented line" },
283+ { type: "same", line: "final line" },
284+ ];
285+
286+ expect(streamDiffs).toEqual(expected);
287+ },
288+ );
289+
290+ test("preserves original lines for minor reindentation in simple block", async () => {
291+ const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
292+ const newLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
293+
294+ const { streamDiffs } = await collectDiffs(oldLines, newLines);
295+
296+ expect(streamDiffs).toEqual([
297+ { type: "same", line: "if (checkValueOf(x)) {" },
298+ { type: "same", line: " doSomethingWith(x);" },
299+ { type: "same", line: "}" },
300+ ]);
301+ });
302+
303+ test("uses new lines for nested reindentation changes", async () => {
304+ const oldLines = ["if (checkValueOf(x)) {", " doSomethingWith(x);", "}"];
305+ const newLines = [
306+ "if (checkValueOf(x)) {",
307+ " if (reallyCheckValueOf(x)) {",
308+ " doSomethingElseWith(x);",
309+ " }",
310+ "}",
311+ ];
312+
313+ const { streamDiffs } = await collectDiffs(oldLines, newLines);
314+
315+ expect(streamDiffs).toEqual([
316+ { type: "same", line: "if (checkValueOf(x)) {" },
317+ { type: "new", line: " if (reallyCheckValueOf(x)) {" },
318+ { type: "old", line: " doSomethingWith(x);" },
319+ { type: "new", line: " doSomethingElseWith(x);" },
320+ { type: "old", line: "}" },
321+ { type: "new", line: " }" },
322+ { type: "new", line: "}" },
323+ ]);
324+ });
325+
326+ test("FastAPI example", async () => {
327+ await expectDiff("fastapi.py");
328+ });
329+
330+ test("FastAPI comments", async () => {
331+ await expectDiff("add-comments.py");
332+ });
333+
334+ test("Mock LLM example", async () => {
335+ await expectDiff("mock-llm.ts");
336+ });
337+});
deleted core/diff/util.test.ts +0 −200
@@ -1,200 +0,0 @@
1-// Generated by continue
2-
3-import { matchLine, streamLines, generateLines } from "./util";
4-import { ChatMessage } from "../index";
5-import { jest } from "@jest/globals";
6-
7-describe.skip("matchLine", () => {
8- it("should match empty lines if the first old line is also empty", () => {
9- const newLine = " ";
10- const oldLines = [" ", "some code"];
11- const result = matchLine(newLine, oldLines);
12- expect(result).toEqual({
13- matchIndex: 0,
14- isPerfectMatch: true,
15- newLine: "",
16- });
17- });
18-
19- it("should return matchIndex -1 if newLine is an end bracket and i > 4", () => {
20- const newLine = "}";
21- const oldLines = ["line 1", "line 2", "line 3", "line 4", "line 5", "}"];
22- const result = matchLine(newLine, oldLines);
23- expect(result).toEqual({
24- matchIndex: -1,
25- isPerfectMatch: false,
26- newLine: "}",
27- });
28- });
29-
30- it("should match end bracket if within first 5 lines", () => {
31- const newLine = "}";
32- const oldLines = ["line 1", "line 2", "line 3", "}", "line 5", "}"];
33- const result = matchLine(newLine, oldLines);
34- expect(result).toEqual({
35- matchIndex: 3,
36- isPerfectMatch: true,
37- newLine: "}",
38- });
39- });
40-
41- it("should match lines perfectly", () => {
42- const newLine = "const a = 5;";
43- const oldLines = ["let b = 6;", "const a = 5;", "console.log(a);"];
44- const result = matchLine(newLine, oldLines);
45- expect(result).toEqual({
46- matchIndex: 1,
47- isPerfectMatch: true,
48- newLine: "const a = 5;",
49- });
50- });
51-
52- it("should match lines with tolerable differences", () => {
53- const newLine = "console.log(a);";
54- const oldLines = ["const a = 5;", "console.log(b);", "console.log( a );"];
55- const result = matchLine(newLine, oldLines);
56- expect(result).toEqual({
57- matchIndex: 2,
58- isPerfectMatch: false,
59- newLine: "console.log(a);",
60- });
61- });
62-
63- it("should return matchIndex -1 if no match found", () => {
64- const newLine = "new line that does not exist";
65- const oldLines = ["line 1", "line 2", "line 3"];
66- const result = matchLine(newLine, oldLines);
67- expect(result).toEqual({
68- matchIndex: -1,
69- isPerfectMatch: false,
70- newLine: "new line that does not exist",
71- });
72- });
73-
74- it("should fix indentation if permissible and line length > 8", () => {
75- const newLine = " const a = 5;";
76- const oldLines = ["const a = 5;"];
77- const result = matchLine(newLine, oldLines, false);
78- expect(result).toEqual({
79- matchIndex: 0,
80- isPerfectMatch: true,
81- newLine: "const a = 5;",
82- });
83- });
84-
85- it("should not fix indentation if not permissible and line length is short", () => {
86- const newLine = " for";
87- const oldLines = ["for"];
88- const result = matchLine(newLine, oldLines, false);
89- expect(result).toEqual({
90- matchIndex: 0,
91- isPerfectMatch: false,
92- newLine: " for",
93- });
94- });
95-
96- it("should fix indentation even if line length <=8 when permissiveAboutIndentation is true", () => {
97- const newLine = " for";
98- const oldLines = ["for"];
99- const result = matchLine(newLine, oldLines, true);
100- expect(result).toEqual({
101- matchIndex: 0,
102- isPerfectMatch: true,
103- newLine: "for",
104- });
105- });
106-
107- it("should match lines that are empty strings", () => {
108- const newLine = "";
109- const oldLines = [""];
110- const result = matchLine(newLine, oldLines);
111- expect(result).toEqual({
112- matchIndex: 0,
113- isPerfectMatch: true,
114- newLine: "",
115- });
116- });
117-});
118-
119-describe("streamLines", () => {
120- it("should split chunks into lines correctly", async () => {
121- async function* streamCompletion(): AsyncGenerator<string> {
122- yield "line1\nline";
123- yield "2\nline3\n";
124- yield "line4";
125- }
126-
127- const resultLines: string[] = [];
128- for await (const line of streamLines(streamCompletion())) {
129- resultLines.push(line);
130- }
131-
132- expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
133- });
134-
135- it("should handle ChatMessage chunks", async () => {
136- const messageChunk1: ChatMessage = {
137- role: "assistant",
138- content: "line1\nline",
139- };
140- const messageChunk2: ChatMessage = {
141- role: "assistant",
142- content: "2\nline3\n",
143- };
144- const messageChunk3: ChatMessage = {
145- role: "assistant",
146- content: "line4",
147- };
148-
149- // const spy = jest.spyOn(messageContentModule, "renderChatMessage");
150-
151- async function* streamCompletion(): AsyncGenerator<ChatMessage> {
152- yield messageChunk1;
153- yield messageChunk2;
154- yield messageChunk3;
155- }
156-
157- const resultLines: string[] = [];
158- for await (const line of streamLines(streamCompletion())) {
159- resultLines.push(line);
160- }
161-
162- expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
163- // expect(spy).toHaveBeenCalledTimes(3);
164- });
165-
166- it("should log lines if log parameter is true", async () => {
167- const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
168-
169- async function* streamCompletion(): AsyncGenerator<string> {
170- yield "line1\nline2\n";
171- yield "line3";
172- }
173-
174- const resultLines: string[] = [];
175- for await (const line of streamLines(streamCompletion(), true)) {
176- resultLines.push(line);
177- }
178-
179- expect(resultLines).toEqual(["line1", "line2", "line3"]);
180- expect(consoleSpy).toHaveBeenCalledWith(
181- "Streamed lines: ",
182- "line1\nline2\nline3",
183- );
184-
185- consoleSpy.mockRestore();
186- });
187-});
188-
189-describe("generateLines", () => {
190- it("should yield the lines provided in the array", async () => {
191- const lines = ["line1", "line2", "line3"];
192- const resultLines: string[] = [];
193-
194- for await (const line of generateLines(lines)) {
195- resultLines.push(line);
196- }
197-
198- expect(resultLines).toEqual(lines);
199- });
200-});
added core/diff/util.vitest.ts +200 −0
@@ -0,0 +1,200 @@
1+// Generated by continue
2+
3+import { describe, expect, it, vi } from "vitest";
4+import { ChatMessage } from "../index";
5+import { generateLines, matchLine, streamLines } from "./util";
6+
7+describe.skip("matchLine", () => {
8+ it("should match empty lines if the first old line is also empty", () => {
9+ const newLine = " ";
10+ const oldLines = [" ", "some code"];
11+ const result = matchLine(newLine, oldLines);
12+ expect(result).toEqual({
13+ matchIndex: 0,
14+ isPerfectMatch: true,
15+ newLine: "",
16+ });
17+ });
18+
19+ it("should return matchIndex -1 if newLine is an end bracket and i > 4", () => {
20+ const newLine = "}";
21+ const oldLines = ["line 1", "line 2", "line 3", "line 4", "line 5", "}"];
22+ const result = matchLine(newLine, oldLines);
23+ expect(result).toEqual({
24+ matchIndex: -1,
25+ isPerfectMatch: false,
26+ newLine: "}",
27+ });
28+ });
29+
30+ it("should match end bracket if within first 5 lines", () => {
31+ const newLine = "}";
32+ const oldLines = ["line 1", "line 2", "line 3", "}", "line 5", "}"];
33+ const result = matchLine(newLine, oldLines);
34+ expect(result).toEqual({
35+ matchIndex: 3,
36+ isPerfectMatch: true,
37+ newLine: "}",
38+ });
39+ });
40+
41+ it("should match lines perfectly", () => {
42+ const newLine = "const a = 5;";
43+ const oldLines = ["let b = 6;", "const a = 5;", "console.log(a);"];
44+ const result = matchLine(newLine, oldLines);
45+ expect(result).toEqual({
46+ matchIndex: 1,
47+ isPerfectMatch: true,
48+ newLine: "const a = 5;",
49+ });
50+ });
51+
52+ it("should match lines with tolerable differences", () => {
53+ const newLine = "console.log(a);";
54+ const oldLines = ["const a = 5;", "console.log(b);", "console.log( a );"];
55+ const result = matchLine(newLine, oldLines);
56+ expect(result).toEqual({
57+ matchIndex: 2,
58+ isPerfectMatch: false,
59+ newLine: "console.log(a);",
60+ });
61+ });
62+
63+ it("should return matchIndex -1 if no match found", () => {
64+ const newLine = "new line that does not exist";
65+ const oldLines = ["line 1", "line 2", "line 3"];
66+ const result = matchLine(newLine, oldLines);
67+ expect(result).toEqual({
68+ matchIndex: -1,
69+ isPerfectMatch: false,
70+ newLine: "new line that does not exist",
71+ });
72+ });
73+
74+ it("should fix indentation if permissible and line length > 8", () => {
75+ const newLine = " const a = 5;";
76+ const oldLines = ["const a = 5;"];
77+ const result = matchLine(newLine, oldLines, false);
78+ expect(result).toEqual({
79+ matchIndex: 0,
80+ isPerfectMatch: true,
81+ newLine: "const a = 5;",
82+ });
83+ });
84+
85+ it("should not fix indentation if not permissible and line length is short", () => {
86+ const newLine = " for";
87+ const oldLines = ["for"];
88+ const result = matchLine(newLine, oldLines, false);
89+ expect(result).toEqual({
90+ matchIndex: 0,
91+ isPerfectMatch: false,
92+ newLine: " for",
93+ });
94+ });
95+
96+ it("should fix indentation even if line length <=8 when permissiveAboutIndentation is true", () => {
97+ const newLine = " for";
98+ const oldLines = ["for"];
99+ const result = matchLine(newLine, oldLines, true);
100+ expect(result).toEqual({
101+ matchIndex: 0,
102+ isPerfectMatch: true,
103+ newLine: "for",
104+ });
105+ });
106+
107+ it("should match lines that are empty strings", () => {
108+ const newLine = "";
109+ const oldLines = [""];
110+ const result = matchLine(newLine, oldLines);
111+ expect(result).toEqual({
112+ matchIndex: 0,
113+ isPerfectMatch: true,
114+ newLine: "",
115+ });
116+ });
117+});
118+
119+describe("streamLines", () => {
120+ it("should split chunks into lines correctly", async () => {
121+ async function* streamCompletion(): AsyncGenerator<string> {
122+ yield "line1\nline";
123+ yield "2\nline3\n";
124+ yield "line4";
125+ }
126+
127+ const resultLines: string[] = [];
128+ for await (const line of streamLines(streamCompletion())) {
129+ resultLines.push(line);
130+ }
131+
132+ expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
133+ });
134+
135+ it("should handle ChatMessage chunks", async () => {
136+ const messageChunk1: ChatMessage = {
137+ role: "assistant",
138+ content: "line1\nline",
139+ };
140+ const messageChunk2: ChatMessage = {
141+ role: "assistant",
142+ content: "2\nline3\n",
143+ };
144+ const messageChunk3: ChatMessage = {
145+ role: "assistant",
146+ content: "line4",
147+ };
148+
149+ // const spy = vi.spyOn(messageContentModule, "renderChatMessage");
150+
151+ async function* streamCompletion(): AsyncGenerator<ChatMessage> {
152+ yield messageChunk1;
153+ yield messageChunk2;
154+ yield messageChunk3;
155+ }
156+
157+ const resultLines: string[] = [];
158+ for await (const line of streamLines(streamCompletion())) {
159+ resultLines.push(line);
160+ }
161+
162+ expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
163+ // expect(spy).toHaveBeenCalledTimes(3);
164+ });
165+
166+ it("should log lines if log parameter is true", async () => {
167+ const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
168+
169+ async function* streamCompletion(): AsyncGenerator<string> {
170+ yield "line1\nline2\n";
171+ yield "line3";
172+ }
173+
174+ const resultLines: string[] = [];
175+ for await (const line of streamLines(streamCompletion(), true)) {
176+ resultLines.push(line);
177+ }
178+
179+ expect(resultLines).toEqual(["line1", "line2", "line3"]);
180+ expect(consoleSpy).toHaveBeenCalledWith(
181+ "Streamed lines: ",
182+ "line1\nline2\nline3",
183+ );
184+
185+ consoleSpy.mockRestore();
186+ });
187+});
188+
189+describe("generateLines", () => {
190+ it("should yield the lines provided in the array", async () => {
191+ const lines = ["line1", "line2", "line3"];
192+ const resultLines: string[] = [];
193+
194+ for await (const line of generateLines(lines)) {
195+ resultLines.push(line);
196+ }
197+
198+ expect(resultLines).toEqual(lines);
199+ });
200+});
added core/edit/applyAbortManager.ts +37 −0
@@ -0,0 +1,37 @@
1+export class ApplyAbortManager {
2+ private static instance: ApplyAbortManager;
3+ private controllers: Map<string, AbortController>;
4+
5+ private constructor() {
6+ this.controllers = new Map();
7+ }
8+
9+ public static getInstance(): ApplyAbortManager {
10+ if (!ApplyAbortManager.instance) {
11+ ApplyAbortManager.instance = new ApplyAbortManager();
12+ }
13+ return ApplyAbortManager.instance;
14+ }
15+
16+ public get(id: string): AbortController {
17+ let controller = this.controllers.get(id);
18+ if (!controller) {
19+ controller = new AbortController();
20+ this.controllers.set(id, controller);
21+ }
22+ return controller;
23+ }
24+
25+ public abort(id: string): void {
26+ const controller = this.controllers.get(id);
27+ if (controller) {
28+ controller.abort();
29+ this.controllers.delete(id);
30+ }
31+ }
32+
33+ public clear(): void {
34+ this.controllers.forEach((controller) => controller.abort());
35+ this.controllers.clear();
36+ }
37+}
modified core/edit/lazy/applyCodeBlock.ts +8 −1
@@ -16,6 +16,7 @@
1616 newLazyFile: string,
1717 filename: string,
1818 llm: ILLM,
19+ abortController: AbortController,
1920 ): Promise<{
2021 isInstantApply: boolean;
2122 diffLinesGenerator: AsyncGenerator<DiffLine>;
@@ -51,6 +52,12 @@
5152
5253 return {
5354 isInstantApply: false,
54- diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
55+ diffLinesGenerator: streamLazyApply(
56+ oldFile,
57+ filename,
58+ newLazyFile,
59+ llm,
60+ abortController,
61+ ),
5562 };
5663 }
modified core/edit/lazy/replace.ts +2 −1
@@ -59,6 +59,7 @@
5959 linesBefore: string[],
6060 linesAfter: string[],
6161 llm: ILLM,
62+ abortController: AbortController,
6263 ): AsyncGenerator<string> {
6364 const userPrompt = dedent`
6465 ORIGINAL CODE:
@@ -88,7 +89,7 @@
8889 { role: "user", content: userPrompt },
8990 { role: "assistant", content: assistantPrompt },
9091 ],
91- new AbortController().signal,
92+ abortController.signal,
9293 );
9394
9495 let lines = streamLines(completion);
modified core/edit/lazy/streamLazyApply.ts +3 −4
@@ -16,6 +16,7 @@
1616 filename: string,
1717 newCode: string,
1818 llm: ILLM,
19+ abortController: AbortController,
1920 ): AsyncGenerator<DiffLine> {
2021 const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
2122 if (!promptFactory) {
@@ -23,10 +24,7 @@
2324 }
2425
2526 const promptMessages = promptFactory(oldCode, filename, newCode);
26- const lazyCompletion = llm.streamChat(
27- promptMessages,
28- new AbortController().signal,
29- );
27+ const lazyCompletion = llm.streamChat(promptMessages, abortController.signal);
3028
3129 // Do find and replace over the lazy edit response
3230 async function* replacementFunction(
@@ -39,6 +37,7 @@
3937 linesBefore,
4038 linesAfter,
4139 llm,
40+ abortController,
4241 )) {
4342 yield line;
4443 }
added core/edit/searchAndReplace/findSearchMatch.test.ts +768 −0
@@ -0,0 +1,768 @@
1+import { findSearchMatch } from "./findSearchMatch";
2+
3+describe("Exact matches", () => {
4+ it("should find exact match at the beginning of file", () => {
5+ const fileContent = `function hello() {
6+ console.log("world");
7+}`;
8+ const searchContent = `function hello() {
9+ console.log("world");
10+}`;
11+
12+ const result = findSearchMatch(fileContent, searchContent);
13+
14+ expect(result).toEqual({
15+ startIndex: 0,
16+ endIndex: fileContent.length,
17+ strategyName: "exactMatch",
18+ });
19+ });
20+
21+ it("should find exact match in the middle of file", () => {
22+ const fileContent = `const a = 1;
23+function hello() {
24+ console.log("world");
25+}
26+const b = 2;`;
27+ const searchContent = `function hello() {
28+ console.log("world");
29+}`;
30+
31+ const result = findSearchMatch(fileContent, searchContent);
32+
33+ expect(result).toEqual({
34+ startIndex: 13, // After "const a = 1;\n"
35+ endIndex: 13 + searchContent.length,
36+ strategyName: "exactMatch",
37+ });
38+ });
39+
40+ it("should find exact match at the end of file", () => {
41+ const fileContent = `const a = 1;
42+function hello() {
43+ console.log("world");
44+}`;
45+ const searchContent = `function hello() {
46+ console.log("world");
47+}`;
48+
49+ const result = findSearchMatch(fileContent, searchContent);
50+
51+ expect(result).toEqual({
52+ startIndex: 13, // After "const a = 1;\n"
53+ endIndex: fileContent.length,
54+ strategyName: "exactMatch",
55+ });
56+ });
57+
58+ it("should find exact match with single line", () => {
59+ const fileContent = `const a = 1;
60+const b = 2;
61+const c = 3;`;
62+ const searchContent = `const b = 2;`;
63+
64+ const result = findSearchMatch(fileContent, searchContent);
65+
66+ expect(result).toEqual({
67+ startIndex: 13, // After "const a = 1;\n"
68+ endIndex: 13 + searchContent.length,
69+ strategyName: "exactMatch",
70+ });
71+ });
72+
73+ it("should find exact match with whitespace preserved", () => {
74+ const fileContent = `function test() {
75+ const x = 1;
76+ const y = 2;
77+}`;
78+ const searchContent = ` const x = 1;
79+ const y = 2;`;
80+
81+ const result = findSearchMatch(fileContent, searchContent);
82+
83+ // The actual indexOf result is 18, not 17
84+ expect(result).toEqual({
85+ startIndex: 18,
86+ endIndex: 18 + searchContent.length,
87+ strategyName: "exactMatch",
88+ });
89+ });
90+});
91+
92+describe("Trimmed matches", () => {
93+ it("should find trimmed match when exact match fails due to leading newlines", () => {
94+ const fileContent = `function hello() {
95+ console.log("world");
96+}`;
97+ const searchContent = `\n\nfunction hello() {
98+ console.log("world");
99+}\n\n`;
100+
101+ const result = findSearchMatch(fileContent, searchContent);
102+
103+ expect(result).toEqual({
104+ startIndex: 0,
105+ endIndex: fileContent.length, // Uses trimmed length
106+ strategyName: "trimmedMatch",
107+ });
108+ });
109+
110+ it("should find trimmed match when exact match fails due to trailing newlines", () => {
111+ const fileContent = `const a = 1;
112+function hello() {
113+ return "world";
114+}
115+const b = 2;`;
116+ const searchContent = `\nfunction hello() {
117+ return "world";
118+}\n`;
119+
120+ const result = findSearchMatch(fileContent, searchContent);
121+
122+ // The function finds the exact match first (at index 12), not the trimmed match
123+ expect(result).toEqual({
124+ startIndex: 12,
125+ endIndex: 12 + searchContent.length,
126+ strategyName: "exactMatch",
127+ });
128+ });
129+
130+ it("should find trimmed match for single line with extra whitespace", () => {
131+ const fileContent = `const a = 1;
132+const b = 2;
133+const c = 3;`;
134+ const searchContent = `\n const b = 2; \n`;
135+
136+ const result = findSearchMatch(fileContent, searchContent);
137+
138+ const trimmedSearchContent = searchContent.trim();
139+ const expectedStart = fileContent.indexOf(trimmedSearchContent);
140+
141+ expect(result).toEqual({
142+ startIndex: expectedStart,
143+ endIndex: expectedStart + trimmedSearchContent.length,
144+ strategyName: "trimmedMatch",
145+ });
146+ });
147+});
148+
149+describe("Empty search content", () => {
150+ it("should match at beginning for empty search content", () => {
151+ const fileContent = `function hello() {
152+ console.log("world");
153+}`;
154+ const searchContent = "";
155+
156+ const result = findSearchMatch(fileContent, searchContent);
157+
158+ expect(result).toEqual({
159+ startIndex: 0,
160+ endIndex: 0,
161+ strategyName: "emptySearch",
162+ });
163+ });
164+
165+ it("should match at beginning for whitespace-only search content", () => {
166+ const fileContent = `function hello() {
167+ console.log("world");
168+}`;
169+ const searchContent = "\n\n \t \n";
170+
171+ const result = findSearchMatch(fileContent, searchContent);
172+
173+ expect(result).toEqual({
174+ startIndex: 0,
175+ endIndex: 0,
176+ strategyName: "emptySearch",
177+ });
178+ });
179+
180+ it("should match at beginning for empty file and empty search", () => {
181+ const fileContent = "";
182+ const searchContent = "";
183+
184+ const result = findSearchMatch(fileContent, searchContent);
185+
186+ expect(result).toEqual({
187+ startIndex: 0,
188+ endIndex: 0,
189+ strategyName: "emptySearch",
190+ });
191+ });
192+});
193+
194+describe("No matches", () => {
195+ it("should return null when search content is not found", () => {
196+ const fileContent = `function hello() {
197+ console.log("world");
198+}`;
199+ const searchContent = `function goodbye() {
200+ console.log("world");
201+}`;
202+
203+ const result = findSearchMatch(fileContent, searchContent);
204+
205+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
206+ });
207+
208+ it("should return only fuzzy result when trimmed search content is not found", () => {
209+ const fileContent = `function hello() {
210+ console.log("world");
211+}`;
212+ const searchContent = `\n\nfunction goodbye() {
213+ console.log("world");
214+}\n\n`;
215+
216+ const result = findSearchMatch(fileContent, searchContent);
217+
218+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
219+ });
220+});
221+
222+describe("Edge cases", () => {
223+ it("should handle empty file with non-empty search", () => {
224+ const fileContent = "";
225+ const searchContent = "function hello() {}";
226+
227+ const result = findSearchMatch(fileContent, searchContent);
228+
229+ expect(result).toBeNull();
230+ });
231+
232+ it("should handle very large content", () => {
233+ const repeatedLine = "const x = 1;\n";
234+ const fileContent =
235+ repeatedLine.repeat(1000) +
236+ "const target = 2;\n" +
237+ repeatedLine.repeat(1000);
238+ const searchContent = "const target = 2;";
239+
240+ const result = findSearchMatch(fileContent, searchContent);
241+
242+ const expectedStart = repeatedLine.length * 1000;
243+ expect(result).toEqual({
244+ startIndex: expectedStart,
245+ endIndex: expectedStart + searchContent.length,
246+ strategyName: "exactMatch",
247+ });
248+ });
249+
250+ it("should handle special characters and symbols", () => {
251+ const fileContent = `const regex = /[a-zA-Z]+/g;
252+const symbols = !@#$%^&*();
253+const unicode = "🚀 Hello 世界";`;
254+ const searchContent = `const symbols = !@#$%^&*();`;
255+
256+ const result = findSearchMatch(fileContent, searchContent);
257+
258+ const expectedStart = fileContent.indexOf(searchContent);
259+ expect(result).toEqual({
260+ startIndex: expectedStart,
261+ endIndex: expectedStart + searchContent.length,
262+ strategyName: "exactMatch",
263+ });
264+ });
265+
266+ it("should prefer exact match over trimmed match", () => {
267+ const fileContent = `function test() {
268+ const x = 1;
269+}
270+
271+function test() {
272+ const x = 1;
273+}`;
274+ const searchContent = `function test() {
275+ const x = 1;
276+}`;
277+
278+ const result = findSearchMatch(fileContent, searchContent);
279+
280+ // Should find the first exact match, not a trimmed version
281+ expect(result).toEqual({
282+ startIndex: 0,
283+ endIndex: searchContent.length,
284+ strategyName: "exactMatch",
285+ });
286+ });
287+
288+ it("should handle multiple occurrences and return first match", () => {
289+ const fileContent = `const a = 1;
290+const b = 2;
291+const a = 1;`;
292+ const searchContent = `const a = 1;`;
293+
294+ const result = findSearchMatch(fileContent, searchContent);
295+
296+ expect(result).toEqual({
297+ startIndex: 0,
298+ endIndex: searchContent.length,
299+ strategyName: "exactMatch",
300+ });
301+ });
302+});
303+
304+describe("Whitespace-ignored matches", () => {
305+ it("should match code with different indentation", () => {
306+ const fileContent = `function example() {
307+ const x = 1;
308+ const y = 2;
309+ return x + y;
310+}`;
311+ const searchContent = `const x=1;
312+const y=2;
313+return x+y;`;
314+
315+ const result = findSearchMatch(fileContent, searchContent);
316+
317+ expect(result).not.toBeNull();
318+ expect(result!.startIndex).toBe(20); // After "function example() {\n"
319+ expect(result!.endIndex).toBe(72); // End of " return x + y;"
320+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
321+
322+ // Verify the matched content contains the original whitespace
323+ const matchedContent = fileContent.substring(
324+ result!.startIndex,
325+ result!.endIndex,
326+ );
327+ expect(matchedContent).toBe(`
328+ const x = 1;
329+ const y = 2;
330+ return x + y;`);
331+ });
332+
333+ it("should match single line with different spacing", () => {
334+ const fileContent = `const a = 1;
335+const b = 2;
336+const c = 3;`;
337+ const searchContent = `const b=2;`;
338+
339+ const result = findSearchMatch(fileContent, searchContent);
340+
341+ expect(result).not.toBeNull();
342+ expect(result!.startIndex).toBe(12); // After "const a = 1;"
343+ expect(result!.endIndex).toBe(32); // End of "const b = 2;"
344+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
345+
346+ // Verify the matched content preserves original spacing
347+ const matchedContent = fileContent.substring(
348+ result!.startIndex,
349+ result!.endIndex,
350+ );
351+ expect(matchedContent).toBe(`
352+const b = 2;`);
353+ });
354+
355+ it("should match with tabs vs spaces", () => {
356+ const fileContent = `function test() {
357+\tif (condition) {
358+\t\treturn true;
359+\t}
360+}`;
361+ const searchContent = `if (condition) {
362+ return true;
363+}`;
364+
365+ const result = findSearchMatch(fileContent, searchContent);
366+
367+ expect(result).not.toBeNull();
368+ expect(result!.startIndex).toBe(17); // After "function test() {"
369+ expect(result!.endIndex).toBe(53); // End of "\t}"
370+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
371+
372+ // Verify the matched content preserves original tabs
373+ const matchedContent = fileContent.substring(
374+ result!.startIndex,
375+ result!.endIndex,
376+ );
377+ expect(matchedContent).toBe(`
378+\tif (condition) {
379+\t\treturn true;
380+\t}`);
381+ });
382+
383+ it("should match complex whitespace patterns", () => {
384+ const fileContent = `const obj = {
385+ key1 : 'value1',
386+ key2 : 'value2',
387+ key3 : 'value3'
388+};`;
389+ const searchContent = `key1:'value1',
390+key2:'value2',
391+key3:'value3'`;
392+
393+ const result = findSearchMatch(fileContent, searchContent);
394+
395+ expect(result).not.toBeNull();
396+ expect(result!.startIndex).toBe(13); // After "const obj = {"
397+ expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
398+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
399+
400+ // Verify the matched content preserves original formatting
401+ const matchedContent = fileContent.substring(
402+ result!.startIndex,
403+ result!.endIndex,
404+ );
405+ expect(matchedContent).toBe(`
406+ key1 : 'value1',
407+ key2 : 'value2',
408+ key3 : 'value3'`);
409+ });
410+
411+ it("should handle newlines and mixed whitespace", () => {
412+ const fileContent = `function calc() {
413+
414+
415+ let result = 0;
416+
417+ result += 5;
418+
419+
420+ return result;
421+}`;
422+ const searchContent = `let result=0;result+=5;return result;`;
423+
424+ const result = findSearchMatch(fileContent, searchContent);
425+
426+ expect(result).not.toBeNull();
427+ expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
428+ expect(result!.endIndex).toBe(78); // End of " return result;"
429+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
430+
431+ // Verify the matched content includes all original whitespace
432+ const matchedContent = fileContent.substring(
433+ result!.startIndex,
434+ result!.endIndex,
435+ );
436+ expect(matchedContent).toBe(`
437+
438+
439+ let result = 0;
440+
441+ result += 5;
442+
443+
444+ return result;`);
445+ });
446+
447+ it("should prefer exact match over whitespace-ignored match", () => {
448+ const fileContent = `const x=1;
449+const x = 1;`;
450+ const searchContent = `const x=1;`;
451+
452+ const result = findSearchMatch(fileContent, searchContent);
453+
454+ // Should find the exact match first (at index 0), not the whitespace-ignored match
455+ expect(result).toEqual({
456+ startIndex: 0,
457+ endIndex: 10,
458+ strategyName: "exactMatch",
459+ });
460+ });
461+
462+ it("should handle empty content after whitespace removal", () => {
463+ const fileContent = `function test() {
464+ return 1;
465+}`;
466+ const searchContent = `\n\n \t \n`;
467+
468+ const result = findSearchMatch(fileContent, searchContent);
469+
470+ // Should match at beginning for empty/whitespace-only content
471+ expect(result).toEqual({
472+ startIndex: 0,
473+ endIndex: 0,
474+ strategyName: "emptySearch",
475+ });
476+ });
477+
478+ it("should handle complex code blocks with different formatting", () => {
479+ const fileContent = `class Example {
480+ constructor(name) {
481+ this.name = name;
482+ this.value = 0;
483+ }
484+
485+ getValue() {
486+ return this.value;
487+ }
488+}`;
489+ const searchContent = `constructor(name){
490+this.name=name;
491+this.value=0;
492+}`;
493+
494+ const result = findSearchMatch(fileContent, searchContent);
495+
496+ expect(result).not.toBeNull();
497+ expect(result!.startIndex).toBe(15); // After "class Example {"
498+ expect(result!.endIndex).toBe(95); // End of " }"
499+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
500+
501+ // Verify the matched content preserves original formatting
502+ const matchedContent = fileContent.substring(
503+ result!.startIndex,
504+ result!.endIndex,
505+ );
506+ expect(matchedContent).toBe(`
507+ constructor(name) {
508+ this.name = name;
509+ this.value = 0;
510+ }`);
511+ });
512+
513+ it("should return null when no close match exists", () => {
514+ const fileContent = `function hello() {
515+ console.log("world");
516+}`;
517+ const searchContent = `this has nothing to do with the other option`;
518+
519+ const result = findSearchMatch(fileContent, searchContent);
520+
521+ expect(result).toBeNull();
522+ });
523+
524+ it("should handle multiple potential matches and return first", () => {
525+ const fileContent = `const a=1;
526+const a = 1;
527+const a = 1;`;
528+ const searchContent = `const a=1;`;
529+
530+ const result = findSearchMatch(fileContent, searchContent);
531+
532+ // Should find the first exact match
533+ expect(result).toEqual({
534+ startIndex: 0,
535+ endIndex: 10,
536+ strategyName: "exactMatch",
537+ });
538+ });
539+});
540+
541+describe("Real-world scenarios", () => {
542+ it("should match typical function replacement", () => {
543+ const fileContent = `class Calculator {
544+ constructor() {
545+ this.result = 0;
546+ }
547+
548+ reset() {
549+ this.result = 0;
550+ return this;
551+ }
552+
553+ add(value) {
554+ this.result += value;
555+ return this;
556+ }
557+}`;
558+ const searchContent = ` reset() {
559+ this.result = 0;
560+ return this;
561+ }`;
562+
563+ const result = findSearchMatch(fileContent, searchContent);
564+
565+ const expectedStart = fileContent.indexOf(searchContent);
566+ expect(result).toEqual({
567+ startIndex: expectedStart,
568+ endIndex: expectedStart + searchContent.length,
569+ strategyName: "exactMatch",
570+ });
571+ });
572+
573+ it("should match import statement", () => {
574+ const fileContent = `import React from 'react';
575+import { useState, useEffect } from 'react';
576+import './App.css';
577+
578+function App() {
579+ return <div>Hello World</div>;
580+}`;
581+ const searchContent = `import { useState, useEffect } from 'react';`;
582+
583+ const result = findSearchMatch(fileContent, searchContent);
584+
585+ const expectedStart = fileContent.indexOf(searchContent);
586+ expect(result).toEqual({
587+ startIndex: expectedStart,
588+ endIndex: expectedStart + searchContent.length,
589+ strategyName: "exactMatch",
590+ });
591+ });
592+
593+ it("should match comment block", () => {
594+ const fileContent = `/**
595+ * This is a comment
596+ * that spans multiple lines
597+ */
598+function test() {
599+ // Single line comment
600+ return true;
601+}`;
602+ const searchContent = `/**
603+ * This is a comment
604+ * that spans multiple lines
605+ */`;
606+
607+ const result = findSearchMatch(fileContent, searchContent);
608+
609+ expect(result).toEqual({
610+ startIndex: 0,
611+ endIndex: searchContent.length,
612+ strategyName: "exactMatch",
613+ });
614+ });
615+
616+ describe("Jaro-Winkler fuzzy matching", () => {
617+ describe("Basic fuzzy matching", () => {
618+ it("should find fuzzy match for similar strings", () => {
619+ const fileContent = `function calculateSum(a, b) {
620+ return a + b;
621+}`;
622+ const searchContent = `function calculateSum(x, y) {
623+ return x + y;
624+}`;
625+
626+ const result = findSearchMatch(fileContent, searchContent);
627+
628+ expect(result).not.toBeNull();
629+ });
630+
631+ it("should find fuzzy match with minor typos", () => {
632+ const fileContent = `const message = "Hello World";`;
633+ const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
634+
635+ const result = findSearchMatch(fileContent, searchContent);
636+
637+ expect(result).not.toBeNull();
638+ expect(result?.startIndex).toBe(0);
639+ });
640+
641+ it("should find fuzzy match with different variable names", () => {
642+ const fileContent = `let userAge = 25;
643+let userName = "John";`;
644+ const searchContent = `let age = 25;
645+let name = "John";`;
646+
647+ const result = findSearchMatch(fileContent, searchContent);
648+
649+ expect(result).not.toBeNull();
650+ });
651+
652+ it("should find fuzzy match for similar function signature", () => {
653+ const fileContent = `function processUserData(userData) {
654+ validateInput(userData);
655+ return formatOutput(userData);
656+}`;
657+ const searchContent = `function processData(data) {
658+ validateInput(data);
659+ return formatOutput(data);
660+}`;
661+
662+ const result = findSearchMatch(fileContent, searchContent);
663+
664+ expect(result).not.toBeNull();
665+ });
666+ });
667+
668+ describe("Multi-line fuzzy matching", () => {
669+ it("should find fuzzy match for multi-line blocks", () => {
670+ const fileContent = `class Calculator {
671+ constructor() {
672+ this.result = 0;
673+ }
674+
675+ add(value) {
676+ this.result += value;
677+ return this;
678+ }
679+}`;
680+ const searchContent = `class Calculator {
681+ constructor() {
682+ this.value = 0;
683+ }
684+
685+ add(num) {
686+ this.value += num;
687+ return this;
688+ }
689+}`;
690+
691+ const result = findSearchMatch(fileContent, searchContent);
692+
693+ expect(result).not.toBeNull();
694+ });
695+
696+ it("should find fuzzy match for partial blocks", () => {
697+ const fileContent = `function processData(input) {
698+ const validated = validateInput(input);
699+ const processed = transformData(validated);
700+ const result = formatOutput(processed);
701+ return result;
702+}`;
703+ const searchContent = `const validated = validateInput(input);
704+ const processed = transformData(validated);`;
705+
706+ const result = findSearchMatch(fileContent, searchContent);
707+
708+ expect(result).not.toBeNull();
709+ });
710+ });
711+
712+ describe("Edge cases with fuzzy matching", () => {
713+ it("should handle empty search content with fuzzy matching enabled", () => {
714+ const fileContent = `function test() {}`;
715+ const searchContent = "";
716+
717+ const result = findSearchMatch(fileContent, searchContent);
718+
719+ expect(result).toEqual({
720+ startIndex: 0,
721+ endIndex: 0,
722+ strategyName: "emptySearch",
723+ });
724+ });
725+
726+ it("should handle empty file content with fuzzy matching enabled", () => {
727+ const fileContent = "";
728+ const searchContent = "function test() {}";
729+
730+ const result = findSearchMatch(fileContent, searchContent);
731+
732+ expect(result).toBeNull();
733+ });
734+
735+ it("should prefer exact match over fuzzy match", () => {
736+ const fileContent = `function test() { return true; }
737+function test() { return false; }`;
738+ const searchContent = `function test() { return true; }`;
739+
740+ const result = findSearchMatch(fileContent, searchContent);
741+
742+ expect(result).not.toBeNull();
743+ expect(result?.startIndex).toBe(0);
744+ });
745+
746+ it("should handle very short strings", () => {
747+ const fileContent = `a b c`;
748+ const searchContent = `a c`;
749+
750+ const result = findSearchMatch(fileContent, searchContent);
751+
752+ // Should not match due to low similarity
753+ expect(result).toBeNull();
754+ });
755+
756+ it("should handle special characters in fuzzy matching", () => {
757+ const fileContent = `const regex = /[a-zA-Z]+/g;
758+const symbols = !@#$%^&*();`;
759+ const searchContent = `const regex = /[a-zA-Z0-9]+/g;
760+const symbols = !@#$%^&*();`;
761+
762+ const result = findSearchMatch(fileContent, searchContent);
763+
764+ expect(result).not.toBeNull();
765+ });
766+ });
767+ });
768+});
added core/edit/searchAndReplace/findSearchMatch.ts +317 −0
@@ -0,0 +1,317 @@
1+/**
2+ * Represents a basic match result with start and end character positions
3+ */
4+interface BasicMatchResult {
5+ /** The starting character index of the match in the file content */
6+ startIndex: number;
7+ /** The ending character index of the match in the file content */
8+ endIndex: number;
9+}
10+
11+/**
12+ * Represents a match result with start and end character positions
13+ */
14+export interface SearchMatchResult extends BasicMatchResult {
15+ /** The name of the strategy that successfully matched */
16+ strategyName: string;
17+}
18+
19+/**
20+ * Strategy function type for finding matches
21+ */
22+type MatchStrategy = (
23+ fileContent: string,
24+ searchContent: string,
25+) => BasicMatchResult | null;
26+
27+/**
28+ * Exact string matching strategy
29+ */
30+function exactMatch(
31+ fileContent: string,
32+ searchContent: string,
33+): BasicMatchResult | null {
34+ const exactIndex = fileContent.indexOf(searchContent);
35+ if (exactIndex !== -1) {
36+ return {
37+ startIndex: exactIndex,
38+ endIndex: exactIndex + searchContent.length,
39+ };
40+ }
41+ return null;
42+}
43+
44+/**
45+ * Trimmed content matching strategy
46+ */
47+function trimmedMatch(
48+ fileContent: string,
49+ searchContent: string,
50+): BasicMatchResult | null {
51+ const trimmedSearchContent = searchContent.trim();
52+ const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
53+ if (trimmedIndex !== -1) {
54+ return {
55+ startIndex: trimmedIndex,
56+ endIndex: trimmedIndex + trimmedSearchContent.length,
57+ };
58+ }
59+ return null;
60+}
61+
62+/**
63+ * Whitespace-ignored matching strategy
64+ * Removes all whitespace from both content and search, then finds the match
65+ */
66+function whitespaceIgnoredMatch(
67+ fileContent: string,
68+ searchContent: string,
69+): BasicMatchResult | null {
70+ // Remove all whitespace (spaces, tabs, newlines, etc.)
71+ const strippedFileContent = fileContent.replace(/\s/g, "");
72+ const strippedSearchContent = searchContent.replace(/\s/g, "");
73+
74+ if (strippedSearchContent === "") {
75+ return null; // Empty search after stripping whitespace
76+ }
77+
78+ const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
79+ if (strippedIndex === -1) {
80+ return null;
81+ }
82+
83+ // Map the stripped position back to the original file content
84+ let originalStartIndex = 0;
85+ let strippedCharCount = 0;
86+
87+ // Find the original position by counting non-whitespace characters
88+ for (let i = 0; i < fileContent.length; i++) {
89+ if (strippedCharCount === strippedIndex) {
90+ originalStartIndex = i;
91+ break;
92+ }
93+ if (!/\s/.test(fileContent[i])) {
94+ strippedCharCount++;
95+ }
96+ }
97+
98+ // Find the end position by counting the length of the search content
99+ let originalEndIndex = originalStartIndex;
100+ let matchedChars = 0;
101+
102+ for (
103+ let i = originalStartIndex;
104+ i < fileContent.length && matchedChars < strippedSearchContent.length;
105+ i++
106+ ) {
107+ if (!/\s/.test(fileContent[i])) {
108+ matchedChars++;
109+ }
110+ originalEndIndex = i + 1;
111+ }
112+
113+ return {
114+ startIndex: originalStartIndex,
115+ endIndex: originalEndIndex,
116+ };
117+}
118+
119+/**
120+ * Calculate the Jaro similarity between two strings
121+ */
122+function jaroSimilarity(s1: string, s2: string): number {
123+ if (s1 === s2) return 1.0;
124+ if (s1.length === 0 || s2.length === 0) return 0.0;
125+
126+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
127+ if (matchDistance < 0) return 0.0;
128+
129+ const s1Matches = new Array(s1.length).fill(false);
130+ const s2Matches = new Array(s2.length).fill(false);
131+
132+ let matches = 0;
133+ let transpositions = 0;
134+
135+ // Find matches
136+ for (let i = 0; i < s1.length; i++) {
137+ const start = Math.max(0, i - matchDistance);
138+ const end = Math.min(i + matchDistance + 1, s2.length);
139+
140+ for (let j = start; j < end; j++) {
141+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
142+ s1Matches[i] = true;
143+ s2Matches[j] = true;
144+ matches++;
145+ break;
146+ }
147+ }
148+
149+ if (matches === 0) return 0.0;
150+
151+ // Count transpositions
152+ let k = 0;
153+ for (let i = 0; i < s1.length; i++) {
154+ if (!s1Matches[i]) continue;
155+ while (!s2Matches[k]) k++;
156+ if (s1[i] !== s2[k]) transpositions++;
157+ k++;
158+ }
159+
160+ return (
161+ (matches / s1.length +
162+ matches / s2.length +
163+ (matches - transpositions / 2) / matches) /
164+ 3.0
165+ );
166+}
167+
168+/**
169+ * Calculate the Jaro-Winkler similarity between two strings
170+ */
171+function jaroWinklerSimilarity(
172+ s1: string,
173+ s2: string,
174+ prefixScale = 0.1,
175+): number {
176+ const jaroSim = jaroSimilarity(s1, s2);
177+
178+ if (jaroSim < 0.7) return jaroSim;
179+
180+ // Calculate common prefix length (up to 4 characters)
181+ let prefixLength = 0;
182+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
183+
184+ for (let i = 0; i < maxPrefix; i++) {
185+ if (s1[i] === s2[i]) {
186+ prefixLength++;
187+ } else {
188+ break;
189+ }
190+ }
191+
192+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
193+}
194+
195+/**
196+ * Find the best fuzzy match for search content in file content using Jaro-Winkler
197+ */
198+function findFuzzyMatch(
199+ fileContent: string,
200+ searchContent: string,
201+ threshold: number = 0.9,
202+): BasicMatchResult | null {
203+ const searchLines = searchContent.split("\n");
204+ const fileLines = fileContent.split("\n");
205+
206+ let bestMatch: BasicMatchResult | null = null;
207+ let bestSimilarity = 0;
208+
209+ // Try matching the search content as a whole block
210+ const searchBlock = searchContent.trim();
211+ if (searchBlock.length > 5) {
212+ // Require minimum length for meaningful matches
213+ // Use sliding window approach for multi-line search
214+ for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
215+ const candidateLines = fileLines.slice(i, i + searchLines.length);
216+ const candidateBlock = candidateLines.join("\n").trim();
217+
218+ if (candidateBlock.length < 5) continue; // Skip very short blocks
219+
220+ const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
221+
222+ if (similarity >= threshold && similarity > bestSimilarity) {
223+ // Calculate character positions
224+ const linesBeforeMatch = fileLines.slice(0, i);
225+ const startIndex =
226+ linesBeforeMatch.join("\n").length +
227+ (linesBeforeMatch.length > 0 ? 1 : 0);
228+ const endIndex = startIndex + candidateBlock.length;
229+
230+ bestMatch = {
231+ startIndex,
232+ endIndex,
233+ };
234+ bestSimilarity = similarity;
235+ }
236+ }
237+ }
238+
239+ // Also try line-by-line matching for better granularity
240+ for (
241+ let searchLineIdx = 0;
242+ searchLineIdx < searchLines.length;
243+ searchLineIdx++
244+ ) {
245+ const searchLine = searchLines[searchLineIdx].trim();
246+ if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
247+
248+ for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
249+ const fileLine = fileLines[fileLineIdx].trim();
250+ if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
251+
252+ const similarity = jaroWinklerSimilarity(searchLine, fileLine);
253+
254+ if (similarity >= threshold && similarity > bestSimilarity) {
255+ // Calculate character positions for the line
256+ const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
257+ const startIndex =
258+ linesBeforeMatch.join("\n").length +
259+ (linesBeforeMatch.length > 0 ? 1 : 0);
260+ const endIndex = startIndex + fileLines[fileLineIdx].length;
261+
262+ bestMatch = {
263+ startIndex,
264+ endIndex,
265+ };
266+ bestSimilarity = similarity;
267+ }
268+ }
269+ }
270+
271+ return bestMatch;
272+}
273+
274+/**
275+ * Ordered list of matching strategies to try with their names
276+ */
277+const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
278+ { strategy: exactMatch, name: "exactMatch" },
279+ { strategy: trimmedMatch, name: "trimmedMatch" },
280+ { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
281+ { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
282+];
283+
284+/**
285+ * Find the exact match position for search content in file content.
286+ * Uses multiple matching strategies in order of preference.
287+ *
288+ * Matching Strategy:
289+ * 1. If search content is empty, matches at the beginning of file (position 0)
290+ * 2. Try each matching strategy in order until one succeeds
291+ *
292+ * @param fileContent - The complete content of the file to search in
293+ * @param searchContent - The content to search for
294+ * @param config - Configuration options for matching behavior
295+ * @returns Match result with character positions, or null if no match found
296+ */
297+export function findSearchMatch(
298+ fileContent: string,
299+ searchContent: string,
300+): SearchMatchResult | null {
301+ const trimmedSearchContent = searchContent.trim();
302+
303+ if (trimmedSearchContent === "") {
304+ // Empty search content matches the beginning of the file
305+ return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
306+ }
307+
308+ // Try each matching strategy in order
309+ for (const { strategy, name } of matchingStrategies) {
310+ const result = strategy(fileContent, searchContent);
311+ if (result !== null) {
312+ return { ...result, strategyName: name };
313+ }
314+ }
315+
316+ return null;
317+}
added core/edit/searchAndReplace/parseSearchReplaceBlock.test.ts +390 −0
@@ -0,0 +1,390 @@
1+import {
2+ parseAllSearchReplaceBlocks,
3+ parseSearchReplaceBlock,
4+} from "./parseSearchReplaceBlock";
5+
6+describe("parseSearchReplaceBlock", () => {
7+ describe("Complete blocks", () => {
8+ it("should parse a complete basic search/replace block", () => {
9+ const content = `------- SEARCH
10+reset() {
11+this.result = 0;
12+return this;
13+}
14+=======
15+// Resets the calculator result to 0 and returns the instance for method chaining
16+reset() {
17+this.result = 0;
18+return this;
19+}
20++++++++ REPLACE`;
21+
22+ const result = parseSearchReplaceBlock(content);
23+
24+ expect(result.isComplete).toBe(true);
25+ expect(result.searchContent).toBe(`reset() {
26+this.result = 0;
27+return this;
28+}`);
29+ expect(result.replaceContent)
30+ .toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
31+reset() {
32+this.result = 0;
33+return this;
34+}`);
35+ expect(result.error).toBeUndefined();
36+ });
37+
38+ it("should handle different marker lengths", () => {
39+ const content = `------- SEARCH
40+old content
41+=========
42+new content
43++++++++++++ REPLACE`;
44+
45+ const result = parseSearchReplaceBlock(content);
46+
47+ expect(result.isComplete).toBe(true);
48+ expect(result.searchContent).toBe("old content");
49+ expect(result.replaceContent).toBe("new content");
50+ });
51+
52+ it("should handle empty search content", () => {
53+ const content = `------- SEARCH
54+=======
55+new content
56++++++++ REPLACE`;
57+
58+ const result = parseSearchReplaceBlock(content);
59+
60+ expect(result.isComplete).toBe(true);
61+ expect(result.searchContent).toBe("");
62+ expect(result.replaceContent).toBe("new content");
63+ });
64+
65+ it("should handle empty replace content (deletion)", () => {
66+ const content = `------- SEARCH
67+old content to delete
68+=======
69++++++++ REPLACE`;
70+
71+ const result = parseSearchReplaceBlock(content);
72+
73+ expect(result.isComplete).toBe(true);
74+ expect(result.searchContent).toBe("old content to delete");
75+ expect(result.replaceContent).toBe("");
76+ });
77+
78+ it("should handle both empty search and replace content", () => {
79+ const content = `------- SEARCH
80+=======
81++++++++ REPLACE`;
82+
83+ const result = parseSearchReplaceBlock(content);
84+
85+ expect(result.isComplete).toBe(true);
86+ expect(result.searchContent).toBe("");
87+ expect(result.replaceContent).toBe("");
88+ });
89+ });
90+
91+ describe("Incomplete blocks", () => {
92+ it("should handle incomplete search block", () => {
93+ const content = `------- SEARCH
94+some content`;
95+
96+ const result = parseSearchReplaceBlock(content);
97+
98+ expect(result.isComplete).toBe(false);
99+ expect(result.searchContent).toBe("some content");
100+ expect(result.replaceContent).toBe("");
101+ expect(result.error).toBeUndefined();
102+ });
103+
104+ it("should handle incomplete replace block", () => {
105+ const content = `------- SEARCH
106+old content
107+=======
108+new content`;
109+
110+ const result = parseSearchReplaceBlock(content);
111+
112+ expect(result.isComplete).toBe(false);
113+ expect(result.searchContent).toBe("old content");
114+ expect(result.replaceContent).toBe("new content");
115+ expect(result.error).toBeUndefined();
116+ });
117+ });
118+
119+ describe("Error cases", () => {
120+ it("should error on search end without start", () => {
121+ const content = `=======
122+some content
123++++++++ REPLACE`;
124+
125+ const result = parseSearchReplaceBlock(content);
126+
127+ expect(result.isComplete).toBe(false);
128+ expect(result.error).toBe(
129+ "Found search block end marker without matching start marker",
130+ );
131+ });
132+
133+ it("should error on replace end without replace start", () => {
134+ const content = `+++++++ REPLACE`;
135+
136+ const result = parseSearchReplaceBlock(content);
137+
138+ expect(result.isComplete).toBe(false);
139+ expect(result.error).toBe(
140+ "Found replace block end marker without matching replace start marker",
141+ );
142+ });
143+ });
144+
145+ describe("Regex pattern validation", () => {
146+ it("should match various search start patterns", () => {
147+ const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
148+
149+ patterns.forEach((pattern) => {
150+ const content = `${pattern}
151+content
152+=======
153+replacement
154++++++++ REPLACE`;
155+
156+ const result = parseSearchReplaceBlock(content);
157+ expect(result.isComplete).toBe(true);
158+ });
159+ });
160+
161+ it("should match various search end patterns", () => {
162+ const patterns = ["===", "=======", "=============="];
163+
164+ patterns.forEach((pattern) => {
165+ const content = `------- SEARCH
166+content
167+${pattern}
168+replacement
169++++++++ REPLACE`;
170+
171+ const result = parseSearchReplaceBlock(content);
172+ expect(result.isComplete).toBe(true);
173+ });
174+ });
175+
176+ it("should match various replace end patterns", () => {
177+ const patterns = [
178+ "+++ REPLACE",
179+ "+++++++ REPLACE",
180+ "+++++++++++ REPLACE",
181+ ];
182+
183+ patterns.forEach((pattern) => {
184+ const content = `------- SEARCH
185+content
186+=======
187+replacement
188+${pattern}`;
189+
190+ const result = parseSearchReplaceBlock(content);
191+ expect(result.isComplete).toBe(true);
192+ });
193+ });
194+
195+ it("should not match invalid patterns", () => {
196+ const invalidPatterns = [
197+ "-- SEARCH", // Too few dashes
198+ "SEARCH", // No markers
199+ "== SEARCH", // Wrong markers
200+ "=== REPLACE", // Wrong end marker
201+ "++++ SEARCH", // Wrong markers for search
202+ ];
203+
204+ invalidPatterns.forEach((pattern) => {
205+ const content = `${pattern}
206+content`;
207+
208+ const result = parseSearchReplaceBlock(content);
209+ expect(result.isComplete).toBe(false);
210+ expect(result.searchContent).toBe(""); // Should not enter search mode
211+ });
212+ });
213+ });
214+});
215+
216+describe("parseAllSearchReplaceBlocks", () => {
217+ it("should parse multiple complete blocks", () => {
218+ const content = `------- SEARCH
219+old code 1
220+=======
221+new code 1
222++++++++ REPLACE
223+
224+------- SEARCH
225+old code 2
226+=======
227+new code 2
228++++++++ REPLACE`;
229+
230+ const blocks = parseAllSearchReplaceBlocks(content);
231+
232+ expect(blocks).toHaveLength(2);
233+ expect(blocks[0].searchContent).toBe("old code 1");
234+ expect(blocks[0].replaceContent).toBe("new code 1");
235+ expect(blocks[1].searchContent).toBe("old code 2");
236+ expect(blocks[1].replaceContent).toBe("new code 2");
237+ });
238+
239+ it("should handle blocks with different content", () => {
240+ const content = `------- SEARCH
241+function old() {
242+ return 1;
243+}
244+=======
245+function new() {
246+ return 2;
247+}
248++++++++ REPLACE
249+
250+------- SEARCH
251+const x = 'old';
252+=======
253+const x = 'new';
254++++++++ REPLACE`;
255+
256+ const blocks = parseAllSearchReplaceBlocks(content);
257+
258+ expect(blocks).toHaveLength(2);
259+ expect(blocks[0].searchContent).toBe(`function old() {
260+ return 1;
261+}`);
262+ expect(blocks[0].replaceContent).toBe(`function new() {
263+ return 2;
264+}`);
265+ expect(blocks[1].searchContent).toBe(`const x = 'old';`);
266+ expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
267+ });
268+
269+ it("should handle deletion blocks (empty replace content)", () => {
270+ const content = `------- SEARCH
271+code to keep
272+=======
273+modified code
274++++++++ REPLACE
275+
276+------- SEARCH
277+code to delete
278+=======
279++++++++ REPLACE`;
280+
281+ const blocks = parseAllSearchReplaceBlocks(content);
282+
283+ expect(blocks).toHaveLength(2);
284+ expect(blocks[0].searchContent).toBe("code to keep");
285+ expect(blocks[0].replaceContent).toBe("modified code");
286+ expect(blocks[1].searchContent).toBe("code to delete");
287+ expect(blocks[1].replaceContent).toBe(""); // Deletion
288+ });
289+
290+ it("should handle insertion blocks (empty search content)", () => {
291+ const content = `------- SEARCH
292+existing code
293+=======
294+modified existing code
295++++++++ REPLACE
296+
297+------- SEARCH
298+=======
299+new code to insert
300++++++++ REPLACE`;
301+
302+ const blocks = parseAllSearchReplaceBlocks(content);
303+
304+ expect(blocks).toHaveLength(2);
305+ expect(blocks[0].searchContent).toBe("existing code");
306+ expect(blocks[0].replaceContent).toBe("modified existing code");
307+ expect(blocks[1].searchContent).toBe(""); // Insertion
308+ expect(blocks[1].replaceContent).toBe("new code to insert");
309+ });
310+
311+ it("should skip incomplete blocks", () => {
312+ const content = `------- SEARCH
313+incomplete block
314+
315+------- SEARCH
316+complete block
317+=======
318+replacement
319++++++++ REPLACE`;
320+
321+ const blocks = parseAllSearchReplaceBlocks(content);
322+
323+ expect(blocks).toHaveLength(1);
324+ expect(blocks[0].searchContent).toBe("complete block");
325+ expect(blocks[0].replaceContent).toBe("replacement");
326+ });
327+
328+ it("should handle single block", () => {
329+ const content = `------- SEARCH
330+single block
331+=======
332+replacement
333++++++++ REPLACE`;
334+
335+ const blocks = parseAllSearchReplaceBlocks(content);
336+
337+ expect(blocks).toHaveLength(1);
338+ expect(blocks[0].searchContent).toBe("single block");
339+ expect(blocks[0].replaceContent).toBe("replacement");
340+ });
341+
342+ it("should return empty array when no complete blocks found", () => {
343+ const content = `------- SEARCH
344+incomplete
345+=======
346+missing replace marker`;
347+
348+ const blocks = parseAllSearchReplaceBlocks(content);
349+
350+ expect(blocks).toHaveLength(0);
351+ });
352+
353+ it("should handle blocks with extra content between them", () => {
354+ const content = `Some other content here
355+
356+------- SEARCH
357+block 1
358+=======
359+replacement 1
360++++++++ REPLACE
361+
362+More content in between
363+
364+------- SEARCH
365+block 2
366+=======
367+replacement 2
368++++++++ REPLACE
369+
370+Trailing content`;
371+
372+ const blocks = parseAllSearchReplaceBlocks(content);
373+
374+ expect(blocks).toHaveLength(2);
375+ expect(blocks[0].searchContent).toBe("block 1");
376+ expect(blocks[0].replaceContent).toBe("replacement 1");
377+ expect(blocks[1].searchContent).toBe("block 2");
378+ expect(blocks[1].replaceContent).toBe("replacement 2");
379+ });
380+
381+ it("should throw error for malformed blocks", () => {
382+ const content = `------- SEARCH
383+content
384++++++++ REPLACE`; // Missing =======
385+
386+ expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
387+ "Found replace block end marker without matching replace start marker",
388+ );
389+ });
390+});
added core/edit/searchAndReplace/parseSearchReplaceBlock.ts +147 −0
@@ -0,0 +1,147 @@
1+// Search and replace block markers using flexible regex patterns
2+const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
3+const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
4+const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
5+
6+export interface SearchReplaceBlockResult {
7+ /** Whether a complete search/replace block has been parsed */
8+ isComplete: boolean;
9+ /** The content to search for in the file */
10+ searchContent?: string;
11+ /** The content to replace the search content with */
12+ replaceContent?: string;
13+ /** Error message if parsing failed */
14+ error?: string;
15+}
16+
17+/**
18+ * Parses a search and replace block from content.
19+ *
20+ * Expected format:
21+ * ------- SEARCH
22+ * [content to find]
23+ * =======
24+ * [content to replace with]
25+ * +++++++ REPLACE
26+ *
27+ * @param content - The content to parse
28+ * @returns ParseResult with completion status and extracted content
29+ */
30+export function parseSearchReplaceBlock(
31+ content: string,
32+): SearchReplaceBlockResult {
33+ const lines = content.split("\n");
34+
35+ let currentSearchContent = "";
36+ let currentReplaceContent = "";
37+ let inSearch = false;
38+ let inReplace = false;
39+
40+ for (const line of lines) {
41+ if (SEARCH_BLOCK_START_REGEX.test(line)) {
42+ inSearch = true;
43+ inReplace = false;
44+ currentSearchContent = "";
45+ currentReplaceContent = "";
46+ continue;
47+ }
48+
49+ if (SEARCH_BLOCK_END_REGEX.test(line)) {
50+ if (!inSearch) {
51+ return {
52+ isComplete: false,
53+ error: "Found search block end marker without matching start marker",
54+ };
55+ }
56+ inSearch = false;
57+ inReplace = true;
58+ continue;
59+ }
60+
61+ if (REPLACE_BLOCK_END_REGEX.test(line)) {
62+ if (!inReplace) {
63+ return {
64+ isComplete: false,
65+ error:
66+ "Found replace block end marker without matching replace start marker",
67+ };
68+ }
69+
70+ // Complete block found
71+ return {
72+ isComplete: true,
73+ searchContent: currentSearchContent.trim(),
74+ replaceContent: currentReplaceContent.trim(),
75+ };
76+ }
77+
78+ // Accumulate content
79+ if (inSearch) {
80+ currentSearchContent += line + "\n";
81+ } else if (inReplace) {
82+ currentReplaceContent += line + "\n";
83+ }
84+ }
85+
86+ // Block is not yet complete
87+ return {
88+ isComplete: false,
89+ searchContent: currentSearchContent.trim(),
90+ replaceContent: currentReplaceContent.trim(),
91+ };
92+}
93+
94+/**
95+ * Parses all complete search and replace blocks from content.
96+ *
97+ * @param content - The content containing multiple search/replace blocks
98+ * @returns Array of complete search/replace blocks found
99+ * @throws Error if any malformed blocks are encountered
100+ */
101+export function parseAllSearchReplaceBlocks(
102+ content: string,
103+): SearchReplaceBlockResult[] {
104+ const blocks: SearchReplaceBlockResult[] = [];
105+ const lines = content.split("\n");
106+
107+ let currentBlockLines: string[] = [];
108+ let inBlock = false;
109+
110+ for (const line of lines) {
111+ if (SEARCH_BLOCK_START_REGEX.test(line)) {
112+ // Start of new block
113+ if (inBlock && currentBlockLines.length > 0) {
114+ // Process previous incomplete block if any
115+ const blockContent = currentBlockLines.join("\n");
116+ const result = parseSearchReplaceBlock(blockContent);
117+ if (result.isComplete) {
118+ blocks.push(result);
119+ } else if (result.error) {
120+ // Fail fast on any parsing error
121+ throw new Error(result.error);
122+ }
123+ // If incomplete but no error, it's just a partial block - continue processing
124+ }
125+ currentBlockLines = [line];
126+ inBlock = true;
127+ } else if (inBlock) {
128+ currentBlockLines.push(line);
129+
130+ // Check if this line completes the current block
131+ if (REPLACE_BLOCK_END_REGEX.test(line)) {
132+ const blockContent = currentBlockLines.join("\n");
133+ const result = parseSearchReplaceBlock(blockContent);
134+ if (result.isComplete) {
135+ blocks.push(result);
136+ } else if (result.error) {
137+ // Fail fast on any parsing error
138+ throw new Error(result.error);
139+ }
140+ currentBlockLines = [];
141+ inBlock = false;
142+ }
143+ }
144+ }
145+
146+ return blocks;
147+}
modified core/edit/streamDiffLines.ts +9 −16
@@ -20,7 +20,6 @@
2020 import { streamLines } from "../diff/util";
2121 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2222 import { gptEditPrompt } from "../llm/templates/edit";
23-import { StreamAbortManager } from "../util/abortManager";
2423 import { findLast } from "../util/findLast";
2524 import { Telemetry } from "../util/posthog";
2625 import { recursiveStream } from "./recursiveStream";
@@ -56,7 +55,11 @@
5655 }
5756
5857 function modelIsInept(model: string): boolean {
59- return !(model.includes("gpt") || model.includes("claude"));
58+ return !(
59+ model.includes("gpt") ||
60+ model.includes("claude") ||
61+ model.includes("nova")
62+ );
6063 }
6164
6265 export async function* streamDiffLines({
@@ -64,10 +67,9 @@
6467 highlighted,
6568 suffix,
6669 llm,
67- abortControllerId,
70+ abortController,
6871 input,
6972 language,
70- onlyOneInsertion,
7173 overridePrompt,
7274 rulesToInclude,
7375 }: {
@@ -75,15 +77,12 @@
7577 highlighted: string;
7678 suffix: string;
7779 llm: ILLM;
78- abortControllerId: string;
80+ abortController: AbortController;
7981 input: string;
8082 language: string | undefined;
81- onlyOneInsertion: boolean;
8283 overridePrompt: ChatMessage[] | undefined;
8384 rulesToInclude: RuleWithSource[] | undefined;
8485 }): AsyncGenerator<DiffLine> {
85- const abortManager = StreamAbortManager.getInstance();
86- const abortController = abortManager.get(abortControllerId);
8786 void Telemetry.capture(
8887 "inlineEdit",
8988 {
@@ -115,7 +114,7 @@
115114 // If any rules are present this will result in using chat instead of legacy completion
116115 const systemMessage = rulesToInclude
117116 ? getSystemMessageWithRules({
118- rules: rulesToInclude,
117+ availableRules: rulesToInclude,
119118 userMessage:
120119 typeof prompt === "string"
121120 ? ({
@@ -128,7 +127,7 @@
128127 ) as UserChatMessage | ToolResultChatMessage | undefined),
129128 baseSystemMessage: undefined,
130129 contextItems: [],
131- })
130+ }).systemMessage
132131 : undefined;
133132
134133 if (systemMessage) {
@@ -185,13 +184,7 @@
185184 diffLines = addIndentation(diffLines, indentation);
186185 }
187186
188- let seenGreen = false;
189187 for await (const diffLine of diffLines) {
190188 yield diffLine;
191- if (diffLine.type === "new") {
192- seenGreen = true;
193- } else if (onlyOneInsertion && seenGreen && diffLine.type === "same") {
194- break;
195- }
196189 }
197190 }
modified core/index.d.ts +101 −19
@@ -50,6 +50,7 @@
5050 shouldClearIndexes?: boolean;
5151 status:
5252 | "loading"
53+ | "waiting"
5354 | "indexing"
5455 | "done"
5556 | "failed"
@@ -57,6 +58,7 @@
5758 | "disabled"
5859 | "cancelled";
5960 debugInfo?: string;
61+ warnings?: string[];
6062 }
6163
6264 // This is more or less a V2 of IndexingProgressUpdate for docs etc.
@@ -186,6 +188,7 @@
186188 ide: IDE;
187189 selectedCode: RangeInFile[];
188190 fetch: FetchFunction;
191+ isInAgentMode: boolean;
189192 }
190193
191194 export interface LoadSubmenuItemsArgs {
@@ -426,7 +429,7 @@
426429 completion: string;
427430 }
428431
429-export type MessageModes = "chat" | "agent";
432+export type MessageModes = "chat" | "agent" | "plan";
430433
431434 export type ToolStatus =
432435 | "generating"
@@ -443,6 +446,7 @@
443446 status: ToolStatus;
444447 parsedArgs: any;
445448 output?: ContextItem[];
449+ tool?: Tool;
446450 }
447451
448452 interface Reasoning {
@@ -565,6 +569,7 @@
565569 title?: string;
566570 uniqueId?: string;
567571 baseAgentSystemMessage?: string;
572+ basePlanSystemMessage?: string;
568573 baseChatSystemMessage?: string;
569574 autocompleteOptions?: Partial<TabAutocompleteOptions>;
570575 contextLength?: number;
@@ -580,6 +585,7 @@
580585
581586 // continueProperties
582587 apiKeyLocation?: string;
588+ envSecretLocations?: Record<string, string>;
583589 apiBase?: string;
584590 orgScopeId?: string | null;
585591
@@ -608,6 +614,8 @@
608614 // AWS options
609615 profile?: string;
610616 modelArn?: string;
617+ accessKeyId?: string;
618+ secretAccessKey?: string;
611619
612620 // AWS and VertexAI Options
613621 region?: string;
@@ -731,6 +739,8 @@
731739
732740 isTelemetryEnabled(): Promise<boolean>;
733741
742+ isWorkspaceRemote(): Promise<boolean>;
743+
734744 getUniqueId(): Promise<string>;
735745
736746 getTerminalContents(): Promise<string>;
@@ -781,9 +791,9 @@
781791
782792 getPinnedFiles(): Promise<string[]>;
783793
784- getSearchResults(query: string): Promise<string>;
794+ getSearchResults(query: string, maxResults?: number): Promise<string>;
785795
786- getFileResults(pattern: string): Promise<string[]>;
796+ getFileResults(pattern: string, maxResults?: number): Promise<string[]>;
787797
788798 subprocess(command: string, cwd?: string): Promise<[string, string]>;
789799
@@ -833,17 +843,47 @@
833843 config: ContinueConfig;
834844 fetch: FetchFunction;
835845 completionOptions?: LLMFullCompletionOptions;
846+ abortController: AbortController;
836847 }
837848
838-export interface SlashCommand {
849+/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
850+export interface SlashCommandDescription {
839851 name: string;
840852 description: string;
841853 prompt?: string;
842854 params?: { [key: string]: any };
843- promptFile?: string;
855+}
856+
857+export interface SlashCommand extends SlashCommandDescription {
844858 run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
845859 }
846860
861+export interface SlashCommandWithSource extends SlashCommandDescription {
862+ run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
863+ source: SlashCommandSource;
864+ promptFile?: string;
865+ overrideSystemMessage?: string;
866+}
867+
868+export type SlashCommandSource =
869+ | "built-in-legacy"
870+ | "built-in"
871+ | "json-custom-command"
872+ | "config-ts-slash-command"
873+ | "yaml-prompt-block"
874+ | "mcp-prompt"
875+ | "prompt-file-v1"
876+ | "prompt-file-v2"
877+ | "invokable-rule";
878+
879+export interface SlashCommandDescWithSource extends SlashCommandDescription {
880+ isLegacy: boolean; // Maps to if slashcommand.run exists
881+ source: SlashCommandSource;
882+ promptFile?: string;
883+ mcpServerName?: string;
884+ mcpArgs?: MCPPromptArgs;
885+}
886+
847887 // Config
848888
849889 export type StepName =
@@ -944,8 +984,6 @@
944984 params: { [key: string]: any };
945985 }
946986
947-export type SlashCommandDescription = Omit<SlashCommand, "run">;
948-
949987 export interface CustomCommand {
950988 name: string;
951989 prompt: string;
@@ -1006,6 +1044,7 @@
10061044
10071045 export interface ConfigDependentToolParams {
10081046 rules: RuleWithSource[];
1047+ enableExperimentalTools: boolean;
10091048 }
10101049
10111050 export type GetTool = (params: ConfigDependentToolParams) => Tool;
@@ -1048,6 +1087,7 @@
10481087
10491088 apiBase?: string;
10501089 apiKeyLocation?: string;
1090+ envSecretLocations?: Record<string, string>;
10511091 orgScopeId?: string | null;
10521092
10531093 onPremProxyUrl?: string | null;
@@ -1057,6 +1097,7 @@
10571097 template?: TemplateType;
10581098 completionOptions?: BaseCompletionOptions;
10591099 baseAgentSystemMessage?: string;
1100+ basePlanSystemMessage?: string;
10601101 baseChatSystemMessage?: string;
10611102 requestOptions?: RequestOptions;
10621103 promptTemplates?: { [key: string]: string };
@@ -1128,6 +1169,7 @@
11281169 command: string;
11291170 args: string[];
11301171 env?: Record<string, string>;
1172+ cwd?: string;
11311173 requestOptions?: RequestOptions;
11321174 }
11331175
@@ -1169,14 +1211,16 @@
11691211 | "error"
11701212 | "not-connected";
11711213
1214+export type MCPPromptArgs = {
1215+ name: string;
1216+ description?: string;
1217+ required?: boolean;
1218+}[];
1219+
11721220 export interface MCPPrompt {
11731221 name: string;
11741222 description?: string;
1175- arguments?: {
1176- name: string;
1177- description?: string;
1178- required?: boolean;
1179- }[];
1223+ arguments?: MCPPromptArgs;
11801224 }
11811225
11821226 // Leaving here to ideate on
@@ -1225,6 +1269,7 @@
12251269 codeWrap?: boolean;
12261270 showSessionTabs?: boolean;
12271271 autoAcceptEditToolDiffs?: boolean;
1272+ logEditingData?: boolean;
12281273 }
12291274
12301275 export interface ContextMenuConfig {
@@ -1280,7 +1325,7 @@
12801325 }
12811326
12821327 export interface AcceptOrRejectDiffPayload {
1283- filepath: string;
1328+ filepath?: string;
12841329 streamId?: string;
12851330 }
12861331
@@ -1288,6 +1333,14 @@
12881333 filepath: string;
12891334 }
12901335
1336+export interface ApplyToFilePayload {
1337+ streamId: string;
1338+ filepath?: string;
1339+ text: string;
1340+ toolCallId?: string;
1341+ isSearchAndReplace?: boolean;
1342+}
1343+
12911344 export interface RangeInFileWithContents {
12921345 filepath: string;
12931346 range: {
@@ -1297,6 +1350,16 @@
12971350 contents: string;
12981351 }
12991352
1353+export interface RangeInFileWithNextEditInfo {
1354+ filepath: string;
1355+ range: Range;
1356+ fileContents: string;
1357+ editText: string;
1358+ afterCursorPos: Position;
1359+ beforeCursorPos: Position;
1360+ workspaceDir: string;
1361+}
1362+
13001363 export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
13011364
13021365 /**
@@ -1333,6 +1396,7 @@
13331396 modelRoles?: ExperimentalModelRoles;
13341397 defaultContext?: DefaultContextProvider[];
13351398 promptPath?: string;
1399+ enableExperimentalTools?: boolean;
13361400
13371401 /**
13381402 * Quick actions are a way to add custom commands to the Code Lens of
@@ -1357,6 +1421,22 @@
13571421 * If enabled, will add the current file as context.
13581422 */
13591423 useCurrentFileAsContext?: boolean;
1424+
1425+ /**
1426+ * If enabled, will save data on the user's editing processes
1427+ */
1428+ logEditingData?: boolean;
1429+
1430+ /**
1431+ * If enabled, will enable next edit in place of autocomplete
1432+ */
1433+ optInNextEditFeature?: boolean;
1434+
1435+ /**
1436+ * If enabled, @codebase will only use tool calling
1437+ * instead of embeddings, FTS, recently edited files, etc.
1438+ */
1439+ codebaseToolCallingOnly?: boolean;
13601440 }
13611441
13621442 export interface AnalyticsConfig {
@@ -1441,7 +1521,7 @@
14411521 /** Request options that will be applied to all models and context providers */
14421522 requestOptions?: RequestOptions;
14431523 /** The list of slash commands that will be available in the sidebar */
1444- slashCommands?: SlashCommand[];
1524+ slashCommands?: (SlashCommand | SlashCommandWithSource)[];
14451525 /** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
14461526 * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
14471527 */
@@ -1478,7 +1558,7 @@
14781558 // systemMessage?: string;
14791559 completionOptions?: BaseCompletionOptions;
14801560 requestOptions?: RequestOptions;
1481- slashCommands: SlashCommand[];
1561+ slashCommands: SlashCommandWithSource[];
14821562 contextProviders: IContextProvider[];
14831563 disableSessionTitles?: boolean;
14841564 disableIndexing?: boolean;
@@ -1501,7 +1581,7 @@
15011581 // systemMessage?: string;
15021582 completionOptions?: BaseCompletionOptions;
15031583 requestOptions?: RequestOptions;
1504- slashCommands: SlashCommandDescription[];
1584+ slashCommands: SlashCommandDescWithSource[];
15051585 contextProviders: ContextProviderDescription[];
15061586 disableIndexing?: boolean;
15071587 disableSessionTitles?: boolean;
@@ -1564,9 +1644,11 @@
15641644
15651645 export type RuleSource =
15661646 | "default-chat"
1647+ | "default-plan"
15671648 | "default-agent"
1568- | "model-chat-options"
1569- | "model-agent-options"
1649+ | "model-options-chat"
1650+ | "model-options-plan"
1651+ | "model-options-agent"
15701652 | "rules-block"
15711653 | "json-systemMessage"
15721654 | ".continuerules";
@@ -1576,12 +1658,12 @@
15761658 slug?: string;
15771659 source: RuleSource;
15781660 globs?: string | string[];
1661+ regex?: string | string[];
15791662 rule: string;
15801663 description?: string;
15811664 ruleFile?: string;
15821665 alwaysApply?: boolean;
15831666 }
1584-
15851667 export interface CompleteOnboardingPayload {
15861668 mode: OnboardingModes;
15871669 provider?: string;
modified core/indexing/CodeSnippetsIndex.ts +2 −2
@@ -35,7 +35,8 @@
3535
3636 export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
3737 relativeExpectedTime: number = 1;
38- artifactId = "codeSnippets";
38+ static artifactId = "codeSnippets";
39+ artifactId: string = CodeSnippetsCodebaseIndex.artifactId;
3940
4041 constructor(private readonly ide: IDE) {}
4142
@@ -220,7 +221,6 @@
220221 // Compute
221222 for (let i = 0; i < results.compute.length; i++) {
222223 const compute = results.compute[i];
223-
224224 let snippets: SnippetChunk[] = [];
225225 try {
226226 snippets = await this.getSnippetsInFile(
modified core/indexing/CodebaseIndexer.test.ts +1 −9
@@ -124,14 +124,6 @@
124124 return updates;
125125 }
126126
127- async function refreshIndexFiles(files: string[]) {
128- const updates = [];
129- for await (const update of codebaseIndexer.refreshFiles(files)) {
130- updates.push(update);
131- }
132- return updates;
133- }
134-
135127 async function getAllIndexedFiles() {
136128 const files = await testIndex.getIndexedFilesForTags(
137129 await testIde.getTags(testIndex.artifactId),
@@ -197,7 +189,7 @@
197189 test("should successfuly re-index specific files", async () => {
198190 // Could add more specific tests for this but uses similar logic
199191 const before = await getAllIndexedFiles();
200- await refreshIndexFiles(before);
192+ await codebaseIndexer.refreshCodebaseIndexFiles(before);
201193
202194 const after = await getAllIndexedFiles();
203195 expect(after.length).toBe(before.length);
modified core/indexing/CodebaseIndexer.ts +184 −73
@@ -16,7 +16,7 @@
1616 import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
1717 import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
1818 import { LanceDbIndex } from "./LanceDbIndex.js";
19-import { getComputeDeleteAddRemove } from "./refreshIndex.js";
19+import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
2020 import {
2121 CodebaseIndex,
2222 IndexResultType,
@@ -43,11 +43,21 @@
4343 * - To limit memory usage for indexes that perform computations locally, e.g. FTS
4444 * - To make as few requests as possible to the embeddings providers
4545 */
46- filesPerBatch = 500;
46+ filesPerBatch = 200;
4747 private indexingCancellationController: AbortController | undefined;
4848 private codebaseIndexingState: IndexingProgressUpdate;
4949 private readonly pauseToken: PauseToken;
5050
51+ private getUserFriendlyIndexName(artifactId: string): string {
52+ if (artifactId === FullTextSearchCodebaseIndex.artifactId)
53+ return "Full text search";
54+ if (artifactId === CodeSnippetsCodebaseIndex.artifactId)
55+ return "Code snippets";
56+ if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking";
57+ if (artifactId.startsWith("vectordb")) return "Embedding";
58+ return artifactId; // fallback to original
59+ }
60+
5161 // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
5262 // e.g. a `SQLITE_BUSY` error.
5363 errorsRegexesToClearIndexesOn = [
@@ -75,16 +85,10 @@
7585 this.pauseToken = new PauseToken(initialPaused);
7686 }
7787
78- /**
79- * Set the paused state of the indexer
80- */
8188 set paused(value: boolean) {
8289 this.pauseToken.paused = value;
8390 }
8491
85- /**
86- * Get the current paused state of the indexer
87- */
8892 get paused(): boolean {
8993 return this.pauseToken.paused;
9094 }
@@ -235,7 +239,9 @@
235239 }
236240 }
237241
238- async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
242+ private async *refreshFiles(
243+ files: string[],
244+ ): AsyncGenerator<IndexingProgressUpdate> {
239245 let progress = 0;
240246 if (files.length === 0) {
241247 yield {
@@ -318,6 +324,7 @@
318324 status: "loading",
319325 };
320326 const beginTime = Date.now();
327+ let collectedWarnings: string[] = [];
321328
322329 for (const directory of dirs) {
323330 const dirBasename = getUriPathBasename(directory);
@@ -348,45 +355,52 @@
348355 const repoName = await this.ide.getRepoName(directory);
349356 let nextLogThreshold = 0;
350357
351- try {
352- for await (const updateDesc of this.indexFiles(
353- directory,
354- directoryFiles,
355- branch,
356- repoName,
357- )) {
358- // Handle pausing in this loop because it's the only one really taking time
359- if (abortSignal.aborted) {
360- yield {
361- progress: 0,
362- desc: "Indexing cancelled",
363- status: "cancelled",
364- };
365- return;
366- }
367- if (this.pauseToken.paused) {
368- yield* this.yieldUpdateAndPause();
369- }
370- yield updateDesc;
371- if (updateDesc.progress >= nextLogThreshold) {
372- // log progress every 2.5%
373- nextLogThreshold += 0.025;
374- this.logProgress(
375- beginTime,
376- Math.floor(directoryFiles.length * updateDesc.progress),
377- updateDesc.progress,
378- );
379- }
358+ for await (const updateDesc of this.indexFiles(
359+ directory,
360+ directoryFiles,
361+ branch,
362+ repoName,
363+ )) {
364+ // Handle pausing in this loop because it's the only one really taking time
365+ if (abortSignal.aborted) {
366+ yield {
367+ progress: 0,
368+ desc: "Indexing cancelled",
369+ status: "cancelled",
370+ };
371+ return;
372+ }
373+ if (this.pauseToken.paused) {
374+ yield* this.yieldUpdateAndPause();
375+ }
376+
377+ // Collect warnings from indexFiles
378+ if (updateDesc.warnings && updateDesc.warnings.length > 0) {
379+ collectedWarnings = [...updateDesc.warnings];
380+ }
381+
382+ yield updateDesc;
383+ if (updateDesc.progress >= nextLogThreshold) {
384+ // log progress every 2.5%
385+ nextLogThreshold += 0.025;
386+ this.logProgress(
387+ beginTime,
388+ Math.floor(directoryFiles.length * updateDesc.progress),
389+ updateDesc.progress,
390+ );
380391 }
381- } catch (err) {
382- yield this.handleErrorAndGetProgressUpdate(err);
383- return;
384392 }
385393 }
394+
395+ // Final completion message with preserved warnings
386396 yield {
387397 progress: 1,
388- desc: "Indexing Complete",
398+ desc:
399+ collectedWarnings.length > 0
400+ ? `Indexing completed with ${collectedWarnings.length} warning(s)`
401+ : "Indexing Complete",
389402 status: "done",
403+ warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined,
390404 };
391405 this.logProgress(beginTime, 0, 1);
392406 }
@@ -494,6 +508,8 @@
494508 const indexesToBuild = await this.getIndexesToBuild();
495509 let completedIndexCount = 0;
496510 let progress = 0;
511+ const warnings: string[] = [];
512+
497513 for (const codebaseIndex of indexesToBuild) {
498514 const tag: IndexTag = {
499515 directory,
@@ -504,45 +520,101 @@
504520 progress: progress,
505521 desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
506522 status: "indexing",
523+ warnings: warnings.length > 0 ? [...warnings] : undefined,
507524 };
508- const [results, lastUpdated, markComplete] =
509- await getComputeDeleteAddRemove(
510- tag,
511- { ...stats },
512- (filepath) => this.ide.readFile(filepath),
513- repoName,
514- );
515- const totalOps = this.totalIndexOps(results);
516- let completedOps = 0;
517525
518- // Don't update if nothing to update. Some of the indices might do unnecessary setup work
519- if (totalOps > 0) {
520- for (const subResult of this.batchRefreshIndexResults(results)) {
521- for await (const { desc } of codebaseIndex.update(
526+ try {
527+ const [results, lastUpdated, markComplete] =
528+ await getComputeDeleteAddRemove(
522529 tag,
523- subResult,
524- markComplete,
530+ { ...stats },
531+ (filepath) => this.ide.readFile(filepath),
525532 repoName,
526- )) {
527- yield {
528- progress: progress,
529- desc,
530- status: "indexing",
531- };
533+ );
534+ const totalOps = this.totalIndexOps(results);
535+ let completedOps = 0;
536+
537+ // Don't update if nothing to update. Some of the indices might do unnecessary setup work
538+ if (totalOps > 0) {
539+ for (const subResult of this.batchRefreshIndexResults(results)) {
540+ try {
541+ for await (const { desc } of codebaseIndex.update(
542+ tag,
543+ subResult,
544+ markComplete,
545+ repoName,
546+ )) {
547+ yield {
548+ progress,
549+ desc,
550+ status: "indexing",
551+ warnings: warnings.length > 0 ? [...warnings] : undefined,
552+ };
553+ }
554+ completedOps +=
555+ subResult.compute.length +
556+ subResult.del.length +
557+ subResult.addTag.length +
558+ subResult.removeTag.length;
559+ progress =
560+ (completedIndexCount + completedOps / totalOps) *
561+ (1 / indexesToBuild.length);
562+ } catch (err) {
563+ // Collect non-fatal errors as warnings and continue
564+ const warningMsg =
565+ err instanceof Error ? err.message : String(err);
566+ const friendlyName = this.getUserFriendlyIndexName(
567+ codebaseIndex.artifactId,
568+ );
569+ warnings.push(`${friendlyName}: ${warningMsg}`);
570+ console.warn(`${friendlyName}: ${warningMsg}`, err);
571+
572+ // Complete this batch and continue with next
573+ completedOps +=
574+ subResult.compute.length +
575+ subResult.del.length +
576+ subResult.addTag.length +
577+ subResult.removeTag.length;
578+ progress =
579+ (completedIndexCount + completedOps / totalOps) *
580+ (1 / indexesToBuild.length);
581+ }
532582 }
533- completedOps +=
534- subResult.compute.length +
535- subResult.del.length +
536- subResult.addTag.length +
537- subResult.removeTag.length;
538- progress =
539- (completedIndexCount + completedOps / totalOps) *
540- (1 / indexesToBuild.length);
541583 }
584+
585+ await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
586+ completedIndexCount += 1;
587+ } catch (err) {
588+ // Handle errors during planning phase
589+ const cause = getRootCause(err as Error);
590+ if (cause instanceof LLMError) {
591+ // LLM errors are critical, re-throw them
592+ throw cause;
593+ }
594+
595+ // Collect planning errors as warnings and continue to next index
596+ const errorMsg = err instanceof Error ? err.message : String(err);
597+ const friendlyName = this.getUserFriendlyIndexName(
598+ codebaseIndex.artifactId,
599+ );
600+ warnings.push(`${friendlyName}: ${errorMsg}`);
601+ console.warn(
602+ `Warning during ${codebaseIndex.artifactId} planning:`,
603+ err,
604+ );
605+ completedIndexCount += 1;
606+ progress = completedIndexCount * (1 / indexesToBuild.length);
542607 }
608+ }
543609
544- await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
545- completedIndexCount += 1;
610+ // Final update with any collected warnings
611+ if (warnings.length > 0) {
612+ yield {
613+ progress: 1,
614+ desc: `Indexing completed with ${warnings.length} warning(s)`,
615+ status: "done",
616+ warnings: [...warnings],
617+ };
546618 }
547619 }
548620
@@ -571,11 +643,47 @@
571643 );
572644 }
573645
646+ /**
647+ * We want to prevent sqlite concurrent write errors
648+ * when there are 2 indexing happening from different windows.
649+ * We want the other window to wait until the first window's indexing finishes.
650+ * Incase the first window closes before indexing is finished,
651+ * we want to unlock the IndexLock by checking the last timestamp.
652+ */
653+ private async *waitForDBIndex(): AsyncGenerator<IndexingProgressUpdate> {
654+ let foundLock = await IndexLock.isLocked();
655+ while (foundLock?.locked) {
656+ if ((Date.now() - foundLock.timestamp) / 1000 > 10) {
657+ console.log(`${foundLock.dirs} is not being indexed... unlocking`);
658+ await IndexLock.unlock();
659+ break;
660+ }
661+ console.log(`indexing ${foundLock.dirs}`);
662+ yield {
663+ progress: 0,
664+ desc: "",
665+ status: "waiting",
666+ };
667+ await new Promise((resolve) => setTimeout(resolve, 1000));
668+ foundLock = await IndexLock.isLocked();
669+ }
670+ }
671+
574672 public async refreshCodebaseIndex(paths: string[]) {
575673 if (this.indexingCancellationController) {
576674 this.indexingCancellationController.abort();
577675 }
578676 this.indexingCancellationController = new AbortController();
677+ for await (const update of this.waitForDBIndex()) {
678+ this.updateProgress(update);
679+ }
680+
681+ await IndexLock.lock(paths.join(", ")); // acquire the index lock to prevent multiple windows to begin indexing
682+ const indexLockTimestampUpdateInterval = setInterval(
683+ () => void IndexLock.updateTimestamp(),
684+ 5_000,
685+ );
686+
579687 try {
580688 for await (const update of this.refreshDirs(
581689 paths,
@@ -592,6 +700,9 @@
592700 await this.handleIndexingError(e);
593701 }
594702
703+ clearInterval(indexLockTimestampUpdateInterval); // interval will also be cleared when window closes before indexing is finished
704+ await IndexLock.unlock();
705+
595706 // Directly refresh submenu items
596707 if (this.messenger) {
597708 this.messenger.send("refreshSubmenuItems", {
modified core/indexing/FullTextSearchCodebaseIndex.ts +1 −2
@@ -55,7 +55,6 @@
5555
5656 for (let i = 0; i < results.compute.length; i++) {
5757 const item = results.compute[i];
58-
5958 // Insert chunks
6059 const chunks = await db.all(
6160 "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?",
@@ -68,7 +67,7 @@
6867 [item.path, chunk.content],
6968 );
7069 await db.run(
71- `INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
70+ `INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
7271 VALUES (?, ?, ?, ?)
7372 ON CONFLICT(id) DO UPDATE SET
7473 path = excluded.path,
modified core/indexing/LanceDbIndex.ts +23 −6
@@ -97,8 +97,8 @@
9797 contents TEXT NOT NULL
9898 )`);
9999
100- await new Promise((resolve) =>
101- migrate(
100+ await new Promise((resolve) => {
101+ void migrate(
102102 "lancedb_sqlite_artifact_id_column",
103103 async () => {
104104 try {
@@ -118,8 +118,8 @@
118118 }
119119 },
120120 () => resolve(undefined),
121- ),
122- );
121+ );
122+ });
123123 }
124124
125125 private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
@@ -234,6 +234,23 @@
234234 return results;
235235 }
236236
237+ /**
238+ * Due to a bug in indexing, some indexes have vectors
239+ * without the surrounding []. These would fail to parse
240+ * but this allows such existing indexes to function properly
241+ */
242+ private parseVector(vector: string): number[] {
243+ try {
244+ return JSON.parse(vector);
245+ } catch (err) {
246+ try {
247+ return JSON.parse(`[${vector}]`);
248+ } catch (err2) {
249+ throw new Error(`Failed to parse vector: ${vector}`, { cause: err2 });
250+ }
251+ }
252+ }
253+
237254 async *update(
238255 tag: IndexTag,
239256 results: RefreshIndexResults,
@@ -297,10 +314,10 @@
297314 const lanceRows: LanceDbRow[] = [];
298315 for (const item of cachedItems) {
299316 try {
300- const vector = JSON.parse(item.vector);
317+ const vector = this.parseVector(item.vector);
301318 const { uuid, startLine, endLine, contents } = item;
302319
303- cachedItems.push({
320+ lanceRows.push({
304321 path,
305322 uuid,
306323 startLine,
modified core/indexing/README.md +3 −3
@@ -20,10 +20,10 @@
2020
2121 All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used.
2222
23-`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
23+`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
2424 `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
25-`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
26-`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
25+`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex`
26+`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
2727
2828 ## Known problems
2929
modified core/indexing/chunk/chunk.ts +17 −16
@@ -50,24 +50,25 @@
5050 maxChunkSize,
5151 )) {
5252 chunkPromises.push(
53- new Promise(async (resolve) => {
54- if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
55- // console.debug(
56- // `Chunk with more than ${maxChunkSize} tokens constructed: `,
57- // filepath,
58- // countTokens(chunkWithoutId.content),
59- // );
60- return resolve(undefined);
61- }
62- resolve({
63- ...chunkWithoutId,
64- digest,
65- index,
66- filepath,
67- });
53+ new Promise((resolve) => {
54+ void (async () => {
55+ if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
56+ // console.debug(
57+ // `Chunk with more than ${maxChunkSize} tokens constructed: `,
58+ // filepath,
59+ // countTokens(chunkWithoutId.content),
60+ // );
61+ return resolve(undefined);
62+ }
63+ resolve({
64+ ...chunkWithoutId,
65+ digest,
66+ index: index++,
67+ filepath,
68+ });
69+ })();
6870 }),
6971 );
70- index++;
7172 }
7273 for await (const chunk of chunkPromises) {
7374 if (!chunk) {
modified core/indexing/docs/DocsService.ts +90 −22
@@ -107,6 +107,17 @@
107107 );
108108 };
109109
110+const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
111+ config1: SiteIndexingConfig,
112+ config2: SiteIndexingConfig,
113+) => {
114+ return (
115+ config1.startUrl === config2.startUrl &&
116+ config1.maxDepth === config2.maxDepth &&
117+ config1.useLocalCrawling === config2.useLocalCrawling
118+ );
119+};
120+
110121 /*
111122 General process:
112123 - On config update:
@@ -186,7 +197,9 @@
186197 private async init(configHandler: ConfigHandler) {
187198 const result = await configHandler.loadConfig();
188199 await this.handleConfigUpdate(result);
189- configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this));
200+ configHandler.onConfigUpdate(
201+ this.handleConfigUpdate.bind(this) as (arg: any) => void,
202+ );
190203 }
191204
192205 readonly statuses: Map<string, IndexingStatus> = new Map();
@@ -393,6 +406,21 @@
393406 siteIndexingConfig: SiteIndexingConfig,
394407 ): Promise<boolean> {
395408 try {
409+ // Set a initial status when retrieving cache
410+ this.handleStatusUpdate({
411+ type: "docs",
412+ id: startUrl,
413+ embeddingsProviderId: embeddingId,
414+ isReindexing: false,
415+ title: siteIndexingConfig.title,
416+ debugInfo: "Loaded from cache",
417+ icon: siteIndexingConfig.faviconUrl,
418+ url: startUrl,
419+ progress: 0,
420+ description: "Try to retrieve cache",
421+ status: "indexing",
422+ });
423+
396424 const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
397425
398426 if (cacheHit) {
@@ -427,7 +455,8 @@
427455 siteIndexingConfig: SiteIndexingConfig,
428456 forceReindex: boolean = false,
429457 ): Promise<void> {
430- const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
458+ const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
459+ siteIndexingConfig;
431460
432461 // First, if indexing is already in process, don't attempt
433462 // This queue is necessary because indexAndAdd is invoked circularly by config edits
@@ -683,7 +712,9 @@
683712 await this.deleteIndexes(startUrl);
684713 }
685714
686- const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
715+ const favicon =
716+ faviconUrl ||
717+ (await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
687718
688719 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
689720 return;
@@ -716,10 +747,6 @@
716747 void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
717748 }
718749
719- this.messenger?.send("refreshSubmenuItems", {
720- providers: ["docs"],
721- });
722-
723750 removeFromFailedGlobalContext(siteIndexingConfig);
724751 } catch (e) {
725752 console.error(
@@ -764,14 +791,22 @@
764791 const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
765792
766793 // Try to get a favicon for the site
767- const favicon = await fetchFavicon(new URL(startUrl));
794+ const favicon =
795+ this.statuses.get(startUrl)?.icon ||
796+ (await fetchFavicon(new URL(startUrl)));
797+
798+ // Always try to make the title match what users set in the config
799+ const title =
800+ this.statuses.get(startUrl)?.title ||
801+ siteEmbeddings.title ||
802+ new URL(startUrl).hostname;
768803
769804 // Add the cached embeddings to our database
770805 await this.add({
771806 favicon,
772807 siteIndexingConfig: {
773808 startUrl,
774- title: siteEmbeddings.title || new URL(startUrl).hostname,
809+ title,
775810 },
776811 chunks: siteEmbeddings.chunks,
777812 embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
@@ -908,6 +943,10 @@
908943 );
909944
910945 if (cacheHit) {
946+ // If cache hit, refresh the submenu items for docs
947+ this.messenger?.send("refreshSubmenuItems", {
948+ providers: ["docs"],
949+ });
911950 // If cache hit, retry the search once
912951 return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
913952 }
@@ -979,20 +1018,13 @@
9791018 // Otherwise sync the index based on config changes
9801019 const oldConfigDocs = oldConfig?.docs || [];
9811020 const newConfigDocs = newConfig.docs || [];
982- const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
9831021
9841022 // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
9851023 const currentlyIndexedDocs = await this.listMetadata();
9861024 const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
9871025
988- // Anything found in sqlite but not in new config should be deleted
989- const deletedDocs = currentlyIndexedDocs.filter(
990- (doc) => !newConfigStartUrls.includes(doc.startUrl),
991- );
992-
9931026 // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
994- // TODO if only favicon and title change, only update, don't embed
995- // Otherwise anything found in new config that isn't in sqlite should be added/indexed
1027+ // Anything found in new config that isn't in sqlite should be added/indexed
9961028 const addedDocs: SiteIndexingConfig[] = [];
9971029 const changedDocs: SiteIndexingConfig[] = [];
9981030 for (const doc of newConfigDocs) {
@@ -1003,12 +1035,26 @@
10031035 (d) => d.startUrl === doc.startUrl,
10041036 );
10051037
1038+ // TODO: Changes to the docs config made while Continue isn't running won't be caught
10061039 if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
1007- changedDocs.push(doc);
1040+ // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
1041+ if (
1042+ siteIndexingConfigsAreEqualExceptTitleAndFavicon(
1043+ oldConfigDoc,
1044+ doc,
1045+ )
1046+ ) {
1047+ await this.updateMetadataInSqlite(doc);
1048+ } else {
1049+ changedDocs.push(doc);
1050+ }
10081051 } else {
10091052 if (forceReindex) {
10101053 changedDocs.push(doc);
10111054 } else {
1055+ // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
1056+ // We only update title and faviconUrl here
1057+ await this.updateMetadataInSqlite(doc);
10121058 // if get's here, not changed, no update needed, mark as complete
10131059 this.handleStatusUpdate({
10141060 type: "docs",
@@ -1036,14 +1082,14 @@
10361082 ...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
10371083 ...addedDocs.map((doc) => this.indexAndAdd(doc)),
10381084 ]);
1039-
1040- for (const doc of deletedDocs) {
1041- await this.deleteIndexes(doc.startUrl);
1042- }
10431085 } catch (e) {
10441086 console.error("Error syncing docs index on config update", e);
10451087 } finally {
10461088 this.isSyncing = false;
1089+ // Refresh the submenu items for docs
1090+ this.messenger?.send("refreshSubmenuItems", {
1091+ providers: ["docs"],
1092+ });
10471093 }
10481094 }
10491095
@@ -1190,6 +1236,27 @@
11901236 );
11911237 }
11921238
1239+ private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
1240+ const { startUrl, title, faviconUrl } = siteIndexingConfig;
1241+ const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
1242+ if (!this.config.selectedModelByRole.embed) {
1243+ console.warn(
1244+ `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1245+ );
1246+ return;
1247+ }
1248+
1249+ const db = await this.getOrCreateSqliteDb();
1250+
1251+ await db.run(
1252+ `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
1253+ title,
1254+ favicon,
1255+ startUrl,
1256+ this.config.selectedModelByRole.embed.embeddingId,
1257+ );
1258+ }
1259+
11931260 private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
11941261 // Handles the case where a user has manually added the doc to config.json
11951262 // so it already exists in the file
@@ -1294,5 +1361,6 @@
12941361 this.messenger?.send("refreshSubmenuItems", {
12951362 providers: ["docs"],
12961363 });
1364+ this.statuses.delete(startUrl);
12971365 }
12981366 }
modified core/indexing/docs/migrations.ts +4 −4
@@ -6,8 +6,8 @@
66 import DocsService, { SqliteDocsRow } from "./DocsService.js";
77
88 export async function runLanceMigrations(table: Table) {
9- await new Promise((resolve) =>
10- migrate(
9+ await new Promise((resolve) => {
10+ void migrate(
1111 "rename_baseurl_column_for_lance_docs",
1212 async () => {
1313 try {
@@ -21,8 +21,8 @@
2121 }
2222 },
2323 () => resolve(undefined),
24- ),
25- );
24+ );
25+ });
2626 }
2727
2828 export async function runSqliteMigrations(db: Database) {
modified core/indexing/refreshIndex.ts +54 −0
@@ -45,6 +45,16 @@
4545 artifactId STRING NOT NULL
4646 )`,
4747 );
48+
49+ await db.exec(
50+ `CREATE TABLE IF NOT EXISTS indexing_lock (
51+ id INTEGER PRIMARY KEY AUTOINCREMENT,
52+ locked BOOLEAN NOT NULL,
53+ timestamp INTEGER NOT NULL,
54+ dirs STRING NOT NULL
55+ )`,
56+ );
57+
4858 // Delete duplicate rows from tag_catalog
4959 await db.exec(`
5060 DELETE FROM tag_catalog
@@ -532,3 +542,47 @@
532542 export function truncateSqliteLikePattern(input: string, safety: number = 100) {
533543 return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
534544 }
545+
546+export class IndexLock {
547+ private static getLockTableName() {
548+ return "indexing_lock";
549+ }
550+
551+ static async isLocked(): Promise<
552+ { locked: boolean; dirs: string; timestamp: number } | undefined | undefined
553+ > {
554+ const db = await SqliteDb.get();
555+ const row = (await db.get(
556+ `SELECT locked, dirs, timestamp FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
557+ true,
558+ )) as { locked: boolean; dirs: string; timestamp: number } | undefined;
559+ return row;
560+ }
561+
562+ static async lock(dirs: string) {
563+ const db = await SqliteDb.get();
564+ await db.run(
565+ `INSERT INTO ${IndexLock.getLockTableName()} (locked, timestamp, dirs) VALUES (?, ?, ?)`,
566+ true,
567+ Date.now(),
568+ dirs,
569+ );
570+ }
571+
572+ static async updateTimestamp() {
573+ const db = await SqliteDb.get();
574+ await db.run(
575+ `UPDATE ${IndexLock.getLockTableName()} SET timestamp = ? where locked = ?`,
576+ Date.now(),
577+ true,
578+ );
579+ }
580+
581+ static async unlock() {
582+ const db = await SqliteDb.get();
583+ await db.run(
584+ `DELETE FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
585+ true,
586+ );
587+ }
588+}
modified core/jest.config.js +1 −3
@@ -29,7 +29,5 @@
2929 globalSetup: "<rootDir>/test/jest.global-setup.ts",
3030 setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.js"],
3131 maxWorkers: 1, // equivalent to CLI --runInBand
32- modulePathIgnorePatterns: [
33- "<rootDir>/config/yaml/LocalPlatformClient.test.ts",
34- ],
32+ testMatch: ["**/*.test.ts"],
3533 };
modified core/llm/autodetect.ts +14 −1
@@ -46,12 +46,14 @@
4646 const PROVIDER_HANDLES_TEMPLATING: string[] = [
4747 "lmstudio",
4848 "openai",
49+ "nvidia",
4950 "ollama",
5051 "together",
5152 "novita",
5253 "msty",
5354 "anthropic",
5455 "bedrock",
56+ "cohere",
5557 "sagemaker",
5658 "continue-proxy",
5759 "mistral",
@@ -65,6 +67,7 @@
6567 const PROVIDER_SUPPORTS_IMAGES: string[] = [
6668 "openai",
6769 "ollama",
70+ "cohere",
6871 "gemini",
6972 "msty",
7073 "anthropic",
@@ -89,6 +92,8 @@
8992 "gpt-4o-mini",
9093 "gpt-4-vision",
9194 "claude-3",
95+ "c4ai-aya-vision-8b",
96+ "c4ai-aya-vision-32b",
9297 "gemini-ultra",
9398 "gemini-1.5-pro",
9499 "gemini-1.5-flash",
@@ -140,6 +145,7 @@
140145 const PARALLEL_PROVIDERS: string[] = [
141146 "anthropic",
142147 "bedrock",
148+ "cohere",
143149 "sagemaker",
144150 "deepinfra",
145151 "gemini",
@@ -176,12 +182,14 @@
176182 if (
177183 lower.includes("gpt") ||
178184 lower.includes("command") ||
185+ lower.includes("aya") ||
179186 lower.includes("chat-bison") ||
180187 lower.includes("pplx") ||
181188 lower.includes("gemini") ||
182189 lower.includes("grok") ||
183190 lower.includes("moonshot") ||
184- lower.includes("mercury")
191+ lower.includes("mercury") ||
192+ /^o\d/.test(lower)
185193 ) {
186194 return undefined;
187195 }
@@ -230,6 +238,11 @@
230238 return "none";
231239 }
232240
241+ // Nova Pro requests always sent through Converse API, so formatting not necessary
242+ if (lower.includes("nova")) {
243+ return "none";
244+ }
245+
233246 if (lower.includes("codestral")) {
234247 return "none";
235248 }
added core/llm/autodetect.vitest.ts +203 −0
@@ -0,0 +1,203 @@
1+import { expect, test } from "vitest";
2+import { autodetectTemplateType } from "./autodetect";
3+
4+test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => {
5+ expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
6+ expect(autodetectTemplateType("CodeLlama-70B")).toBe("codellama-70b");
7+ expect(autodetectTemplateType("codellama-70b-instruct")).toBe(
8+ "codellama-70b",
9+ );
10+ expect(autodetectTemplateType("CodeLlama-70B-Python")).toBe("codellama-70b");
11+});
12+
13+test("autodetectTemplateType returns undefined for models that don't need templates", () => {
14+ expect(autodetectTemplateType("gpt-4")).toBe(undefined);
15+ expect(autodetectTemplateType("gpt-3.5-turbo")).toBe(undefined);
16+ expect(autodetectTemplateType("GPT-4")).toBe(undefined);
17+ expect(autodetectTemplateType("command-r")).toBe(undefined);
18+ expect(autodetectTemplateType("aya-23")).toBe(undefined);
19+ expect(autodetectTemplateType("chat-bison")).toBe(undefined);
20+ expect(autodetectTemplateType("pplx-70b")).toBe(undefined);
21+ expect(autodetectTemplateType("gemini-pro")).toBe(undefined);
22+ expect(autodetectTemplateType("grok-beta")).toBe(undefined);
23+ expect(autodetectTemplateType("moonshot-v1")).toBe(undefined);
24+ expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
25+ expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
26+ expect(autodetectTemplateType("o3-mini")).toBe(undefined);
27+ expect(autodetectTemplateType("o4")).toBe(undefined);
28+ expect(autodetectTemplateType("claude-sonnet-4-20250514")).toBe("none");
29+ expect(autodetectTemplateType("claude-3-7-sonnet-latest")).toBe("none");
30+});
31+
32+test("autodetectTemplateType returns 'llama3' for Llama 3 models", () => {
33+ expect(autodetectTemplateType("llama3")).toBe("llama3");
34+ expect(autodetectTemplateType("llama-3")).toBe("llama3");
35+ expect(autodetectTemplateType("Llama3-8B")).toBe("llama3");
36+ expect(autodetectTemplateType("llama-3:70b")).toBe("llama3");
37+});
38+
39+test("autodetectTemplateType returns 'llava' for LLaVA models", () => {
40+ expect(autodetectTemplateType("llava")).toBe("llava");
41+ expect(autodetectTemplateType("LLaVA")).toBe("llava");
42+ expect(autodetectTemplateType("llava-1.5")).toBe("llava");
43+ expect(autodetectTemplateType("llava-v1.6")).toBe("llava");
44+});
45+
46+test("autodetectTemplateType returns 'zephyr' for TinyLlama models", () => {
47+ expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
48+ expect(autodetectTemplateType("TinyLlama")).toBe("zephyr");
49+ expect(autodetectTemplateType("tinyllama-1.1b")).toBe("zephyr");
50+});
51+
52+test("autodetectTemplateType returns 'xwin-coder' for XWin models", () => {
53+ expect(autodetectTemplateType("xwin")).toBe("xwin-coder");
54+ expect(autodetectTemplateType("XWin")).toBe("xwin-coder");
55+ expect(autodetectTemplateType("xwin-coder")).toBe("xwin-coder");
56+});
57+
58+test("autodetectTemplateType returns 'chatml' for Dolphin models", () => {
59+ expect(autodetectTemplateType("dolphin")).toBe("chatml");
60+ expect(autodetectTemplateType("Dolphin")).toBe("chatml");
61+ expect(autodetectTemplateType("dolphin-2.1")).toBe("chatml");
62+});
63+
64+test("autodetectTemplateType returns 'gemma' for Gemma models", () => {
65+ expect(autodetectTemplateType("gemma")).toBe("gemma");
66+ expect(autodetectTemplateType("Gemma")).toBe("gemma");
67+ expect(autodetectTemplateType("gemma-7b")).toBe("gemma");
68+});
69+
70+test("autodetectTemplateType returns 'phi2' for Phi-2 models", () => {
71+ expect(autodetectTemplateType("phi2")).toBe("phi2");
72+ expect(autodetectTemplateType("Phi2")).toBe("phi2");
73+ expect(autodetectTemplateType("microsoft-phi2")).toBe("phi2");
74+});
75+
76+test("autodetectTemplateType returns 'phind' for Phind models", () => {
77+ expect(autodetectTemplateType("phind")).toBe("phind");
78+ expect(autodetectTemplateType("Phind")).toBe("phind");
79+ expect(autodetectTemplateType("phind-codellama")).toBe("phind");
80+});
81+
82+test("autodetectTemplateType returns 'llama2' for general Llama models", () => {
83+ expect(autodetectTemplateType("llama")).toBe("llama2");
84+ expect(autodetectTemplateType("Llama")).toBe("llama2");
85+ expect(autodetectTemplateType("llama2")).toBe("llama2");
86+ expect(autodetectTemplateType("llama-2")).toBe("llama2");
87+ expect(autodetectTemplateType("codellama")).toBe("llama2");
88+});
89+
90+test("autodetectTemplateType returns 'zephyr' for Zephyr models", () => {
91+ expect(autodetectTemplateType("zephyr")).toBe("zephyr");
92+ expect(autodetectTemplateType("Zephyr")).toBe("zephyr");
93+ expect(autodetectTemplateType("zephyr-7b")).toBe("zephyr");
94+});
95+
96+test("autodetectTemplateType returns 'none' for Claude models", () => {
97+ expect(autodetectTemplateType("claude")).toBe("none");
98+ expect(autodetectTemplateType("Claude")).toBe("none");
99+ expect(autodetectTemplateType("claude-3")).toBe("none");
100+ expect(autodetectTemplateType("claude-3-opus")).toBe("none");
101+});
102+
103+test("autodetectTemplateType returns 'none' for Codestral models", () => {
104+ expect(autodetectTemplateType("codestral")).toBe("none");
105+ expect(autodetectTemplateType("Codestral")).toBe("none");
106+ expect(autodetectTemplateType("codestral-22b")).toBe("none");
107+});
108+
109+test("autodetectTemplateType returns 'none' for Nova models", () => {
110+ expect(autodetectTemplateType("nova")).toBe("none");
111+ expect(autodetectTemplateType("Nova")).toBe("none");
112+ expect(autodetectTemplateType("nova-pro")).toBe("none");
113+ expect(autodetectTemplateType("nova-lite")).toBe("none");
114+ expect(autodetectTemplateType("nova-micro")).toBe("none");
115+ expect(autodetectTemplateType("nova-premier")).toBe("none");
116+ expect(autodetectTemplateType("amazon-nova-pro")).toBe("none");
117+ expect(autodetectTemplateType("amazon-nova-lite")).toBe("none");
118+ expect(autodetectTemplateType("amazon-nova-micro")).toBe("none");
119+ expect(autodetectTemplateType("amazon-nova-premier")).toBe("none");
120+});
121+
122+test("autodetectTemplateType returns 'alpaca' for Alpaca and Wizard models", () => {
123+ expect(autodetectTemplateType("alpaca")).toBe("alpaca");
124+ expect(autodetectTemplateType("Alpaca")).toBe("alpaca");
125+ expect(autodetectTemplateType("wizard")).toBe("alpaca");
126+ expect(autodetectTemplateType("Wizard")).toBe("alpaca");
127+ expect(autodetectTemplateType("wizardlm")).toBe("alpaca");
128+});
129+
130+test("autodetectTemplateType returns 'llama2' for Mistral and Mixtral models", () => {
131+ expect(autodetectTemplateType("mistral")).toBe("llama2");
132+ expect(autodetectTemplateType("Mistral")).toBe("llama2");
133+ expect(autodetectTemplateType("mixtral")).toBe("llama2");
134+ expect(autodetectTemplateType("Mixtral")).toBe("llama2");
135+ expect(autodetectTemplateType("mistral-7b")).toBe("llama2");
136+});
137+
138+test("autodetectTemplateType returns 'deepseek' for DeepSeek models", () => {
139+ expect(autodetectTemplateType("deepseek")).toBe("deepseek");
140+ expect(autodetectTemplateType("DeepSeek")).toBe("deepseek");
141+ expect(autodetectTemplateType("deepseek-coder")).toBe("deepseek");
142+});
143+
144+test("autodetectTemplateType returns 'openchat' for Ninja and OpenChat models", () => {
145+ expect(autodetectTemplateType("ninja")).toBe("openchat");
146+ expect(autodetectTemplateType("Ninja")).toBe("openchat");
147+ expect(autodetectTemplateType("openchat")).toBe("openchat");
148+ expect(autodetectTemplateType("OpenChat")).toBe("openchat");
149+});
150+
151+test("autodetectTemplateType returns 'neural-chat' for Neural Chat models", () => {
152+ expect(autodetectTemplateType("neural-chat")).toBe("neural-chat");
153+ expect(autodetectTemplateType("Neural-Chat")).toBe("neural-chat");
154+ expect(autodetectTemplateType("intel-neural-chat")).toBe("neural-chat");
155+});
156+
157+test("autodetectTemplateType returns 'granite' for Granite models", () => {
158+ expect(autodetectTemplateType("granite")).toBe("granite");
159+ expect(autodetectTemplateType("granite2:8b")).toBe("granite");
160+ expect(autodetectTemplateType("Granite")).toBe("granite");
161+ expect(autodetectTemplateType("granite-code")).toBe("granite");
162+});
163+
164+test("autodetectTemplateType returns chatml for other models", () => {
165+ expect(autodetectTemplateType("unknown-model")).toBe("chatml");
166+ expect(autodetectTemplateType("random-ai")).toBe("chatml");
167+ expect(autodetectTemplateType("")).toBe("chatml");
168+});
169+
170+test("autodetectTemplateType handles case sensitivity correctly", () => {
171+ expect(autodetectTemplateType("LLAMA3")).toBe("llama3");
172+ expect(autodetectTemplateType("gpt-4")).toBe(undefined);
173+ expect(autodetectTemplateType("GPT-4")).toBe(undefined);
174+ expect(autodetectTemplateType("CLAUDE")).toBe("none");
175+});
176+
177+test("autodetectTemplateType follows correct precedence order", () => {
178+ // CodeLlama 70B should be detected before general llama
179+ expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
180+
181+ // Llama3 should be detected before general llama
182+ expect(autodetectTemplateType("llama3")).toBe("llama3");
183+
184+ // General llama should be detected after specific cases
185+ expect(autodetectTemplateType("llama2")).toBe("llama2");
186+
187+ // TinyLlama should be detected as zephyr, not llama
188+ expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
189+});
190+
191+test("autodetectTemplateType handles edge cases with special characters", () => {
192+ expect(autodetectTemplateType("llama-3-8b-instruct")).toBe("llama3");
193+ expect(autodetectTemplateType("gpt-4-turbo-preview")).toBe(undefined);
194+ expect(autodetectTemplateType("claude-3-opus-20240229")).toBe("none");
195+ expect(autodetectTemplateType("mistral-7b-instruct-v0.1")).toBe("llama2");
196+});
197+
198+test("autodetectTemplateType handles models with mixed keywords", () => {
199+ // Should match the first applicable pattern
200+ expect(autodetectTemplateType("llama3-chat")).toBe("llama3"); // llama3 comes before general patterns
201+ expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined
202+ expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2
203+});
modified core/llm/constants.ts +2 −1
@@ -1,5 +1,5 @@
11 const DEFAULT_MAX_TOKENS = 4096;
2-const DEFAULT_CONTEXT_LENGTH = 8192;
2+const DEFAULT_CONTEXT_LENGTH = 32_768;
33 const DEFAULT_TEMPERATURE = 0.5;
44
55 const DEFAULT_ARGS = {
@@ -15,6 +15,7 @@
1515 export enum LLMConfigurationStatuses {
1616 VALID = "valid",
1717 MISSING_API_KEY = "missing-api-key",
18+ MISSING_ENV_SECRET = "missing-env-secret",
1819 }
1920
2021 export {
deleted core/llm/constructMessages.ts +0 −181
@@ -1,181 +0,0 @@
1-import {
2- ChatHistoryItem,
3- ChatMessage,
4- ContextItemWithId,
5- RuleWithSource,
6- TextMessagePart,
7- ToolResultChatMessage,
8- UserChatMessage,
9-} from "../";
10-import { findLast } from "../util/findLast";
11-import { normalizeToMessageParts } from "../util/messageContent";
12-import { isUserOrToolMsg } from "./messages";
13-import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
14-
15-export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
16- "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
17-
18-export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
19- "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
20-
21-const EDIT_MESSAGE = `\
22- Always include the language and file name in the info string when you write code blocks.
23- If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
24-
25- When addressing code modification requests, present a concise code snippet that
26- emphasizes only the necessary changes and uses abbreviated placeholders for
27- unmodified sections. For example:
28-
29- \`\`\`language /path/to/file
30- // ... existing code ...
31-
32- {{ modified code here }}
33-
34- // ... existing code ...
35-
36- {{ another modification }}
37-
38- // ... rest of code ...
39- \`\`\`
40-
41- In existing files, you should always restate the function or class that the snippet belongs to:
42-
43- \`\`\`language /path/to/file
44- // ... existing code ...
45-
46- function exampleFunction() {
47- // ... existing code ...
48-
49- {{ modified code here }}
50-
51- // ... rest of function ...
52- }
53-
54- // ... rest of code ...
55- \`\`\`
56-
57- Since users have access to their complete file, they prefer reading only the
58- relevant modifications. It's perfectly acceptable to omit unmodified portions
59- at the beginning, middle, or end of files using these "lazy" comments. Only
60- provide the complete file when explicitly requested. Include a concise explanation
61- of changes unless the user specifically asks for code only.
62-`;
63-
64-export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
65-<important_rules>
66- You are in chat mode.
67-
68- If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
69- If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
70-
71-${EDIT_MESSAGE}
72-</important_rules>`;
73-
74-export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
75-<important_rules>
76- You are in agent mode.
77-
78-${EDIT_MESSAGE}
79-</important_rules>`;
80-
81-/**
82- * Helper function to get the context items for a user message
83- */
84-function getUserContextItems(
85- userMsg: UserChatMessage | ToolResultChatMessage | undefined,
86- history: ChatHistoryItem[],
87-): ContextItemWithId[] {
88- if (!userMsg) return [];
89-
90- // Find the history item that contains the userMsg
91- const historyItem = history.find((item) => {
92- // Check if the message ID matches
93- if ("id" in userMsg && "id" in item.message) {
94- return (item.message as any).id === (userMsg as any).id;
95- }
96- // Fallback to content comparison
97- return (
98- item.message.content === userMsg.content &&
99- item.message.role === userMsg.role
100- );
101- });
102-
103- return historyItem?.contextItems || [];
104-}
105-
106-export function constructMessages(
107- messageMode: string,
108- history: ChatHistoryItem[],
109- baseChatOrAgentSystemMessage: string | undefined,
110- rules: RuleWithSource[],
111-): ChatMessage[] {
112- const filteredHistory = history.filter(
113- (item) => item.message.role !== "system",
114- );
115- const msgs: ChatMessage[] = [];
116-
117- for (let i = 0; i < filteredHistory.length; i++) {
118- const historyItem = filteredHistory[i];
119-
120- if (messageMode === "chat") {
121- const toolMessage: ToolResultChatMessage =
122- historyItem.message as ToolResultChatMessage;
123- if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
124- // remove all tool calls from the history
125- continue;
126- }
127- }
128-
129- if (historyItem.message.role === "user") {
130- // Gather context items for user messages
131- let content = normalizeToMessageParts(historyItem.message);
132-
133- const ctxItems = historyItem.contextItems
134- .map((ctxItem) => {
135- return {
136- type: "text",
137- text: `${ctxItem.content}\n`,
138- } as TextMessagePart;
139- })
140- .filter((part) => !!part.text.trim());
141-
142- content = [...ctxItems, ...content];
143- msgs.push({
144- ...historyItem.message,
145- content,
146- });
147- } else {
148- msgs.push(historyItem.message);
149- }
150- }
151-
152- const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
153- | UserChatMessage
154- | ToolResultChatMessage
155- | undefined;
156-
157- // Get context items for the last user message
158- const lastUserContextItems = getUserContextItems(
159- lastUserMsg,
160- filteredHistory,
161- );
162- const systemMessage = getSystemMessageWithRules({
163- baseSystemMessage: baseChatOrAgentSystemMessage,
164- rules,
165- userMessage: lastUserMsg,
166- contextItems: lastUserContextItems,
167- });
168-
169- if (systemMessage.trim()) {
170- msgs.unshift({
171- role: "system",
172- content: systemMessage,
173- });
174- }
175-
176- // Remove the "id" from all of the messages
177- return msgs.map((msg) => {
178- const { id, ...rest } = msg as any;
179- return rest;
180- });
181-}
modified core/llm/countTokens.ts +4 −1
@@ -60,7 +60,10 @@
6060
6161 const modelType = autodetectTemplateType(modelName);
6262 if (!modelType || modelType === "none") {
63- return gptAsyncEncoder;
63+ // Right now there is a problem packaging js-tiktoken in workers. Until then falling back
64+ // Cannot find package 'js-tiktoken' imported from /Users/nate/gh/continuedev/continue/extensions/vscode/out/tiktokenWorkerPool.mjs
65+ // return gptAsyncEncoder;
66+ return llamaAsyncEncoder;
6467 }
6568 return llamaAsyncEncoder;
6669 }
added core/llm/defaultSystemMessages.ts +79 −0
@@ -0,0 +1,79 @@
1+export const DEFAULT_SYSTEM_MESSAGES_URL =
2+ "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
3+
4+export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
5+ Always include the language and file name in the info string when you write code blocks.
6+ If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
7+`;
8+
9+export const EDIT_CODE_INSTRUCTIONS = `\
10+ When addressing code modification requests, present a concise code snippet that
11+ emphasizes only the necessary changes and uses abbreviated placeholders for
12+ unmodified sections. For example:
13+
14+ \`\`\`language /path/to/file
15+ // ... existing code ...
16+
17+ {{ modified code here }}
18+
19+ // ... existing code ...
20+
21+ {{ another modification }}
22+
23+ // ... rest of code ...
24+ \`\`\`
25+
26+ In existing files, you should always restate the function or class that the snippet belongs to:
27+
28+ \`\`\`language /path/to/file
29+ // ... existing code ...
30+
31+ function exampleFunction() {
32+ // ... existing code ...
33+
34+ {{ modified code here }}
35+
36+ // ... rest of function ...
37+ }
38+
39+ // ... rest of code ...
40+ \`\`\`
41+
42+ Since users have access to their complete file, they prefer reading only the
43+ relevant modifications. It's perfectly acceptable to omit unmodified portions
44+ at the beginning, middle, or end of files using these "lazy" comments. Only
45+ provide the complete file when explicitly requested. Include a concise explanation
46+ of changes unless the user specifically asks for code only.
47+`;
48+
49+export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
50+<important_rules>
51+ You are in chat mode.
52+
53+ If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
54+ If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
55+
56+${CODEBLOCK_FORMATTING_INSTRUCTIONS}
57+${EDIT_CODE_INSTRUCTIONS}
58+</important_rules>`;
59+
60+export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
61+<important_rules>
62+ You are in agent mode.
63+
64+${CODEBLOCK_FORMATTING_INSTRUCTIONS}
65+</important_rules>`;
66+
67+// The note about read-only tools is for MCP servers
68+// For now, all MCP tools are included so model can decide if they are read-only
69+export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\
70+<important_rules>
71+ You are in plan mode, in which you help the user understand and construct a plan.
72+ Only use read-only tools. Do not use any tools that would write to non-temporary files.
73+ If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates.
74+
75+${CODEBLOCK_FORMATTING_INSTRUCTIONS}
76+${EDIT_CODE_INSTRUCTIONS}
77+
78+ In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
79+</important_rules>`;
modified core/llm/index.test.ts +31 −0
@@ -1,6 +1,10 @@
11 import { ChatMessage, LLMOptions } from "..";
22
3+import { allModelProviders } from "@continuedev/llm-info";
4+import { LlmInfo } from "@continuedev/llm-info/dist/types";
35 import { BaseLLM } from ".";
6+import { DEFAULT_CONTEXT_LENGTH } from "./constants";
7+import { LLMClasses } from "./llms";
48 import { LLMLogger } from "./logger";
59
610 class DummyLLM extends BaseLLM {
@@ -140,4 +144,31 @@
140144 describe("*streamChat", () => {
141145 // TODO: Implement tests for *streamChat method
142146 });
147+
148+ describe("default context length", () => {
149+ allModelProviders.map((modelProvider) => {
150+ const LLMClass = LLMClasses.find(
151+ (llm) => llm.providerName === modelProvider.id,
152+ );
153+ if (!LLMClass) {
154+ throw new Error(`did not find LLM provider for ${modelProvider.id}`);
155+ }
156+ const testContextLength = (llmInfo: LlmInfo) => () => {
157+ const llm = new LLMClass({ model: llmInfo.model });
158+ if (llmInfo.contextLength) {
159+ expect(llm.contextLength).toEqual(llmInfo.contextLength);
160+ } else {
161+ expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH);
162+ }
163+ };
164+ describe(`${modelProvider.id}`, () => {
165+ modelProvider.models.forEach((llmInfo) => {
166+ test(
167+ `should have correct context length for ${llmInfo.model}`,
168+ testContextLength(llmInfo),
169+ );
170+ });
171+ });
172+ });
173+ });
143174 });
modified core/llm/index.ts +95 −64
@@ -141,6 +141,7 @@
141141
142142 title?: string;
143143 baseChatSystemMessage?: string;
144+ basePlanSystemMessage?: string;
144145 baseAgentSystemMessage?: string;
145146 contextLength: number;
146147 maxStopWords?: number | undefined;
@@ -155,6 +156,7 @@
155156
156157 // continueProperties
157158 apiKeyLocation?: string;
159+ envSecretLocations?: Record<string, string>;
158160 apiBase?: string;
159161 orgScopeId?: string | null;
160162
@@ -172,6 +174,8 @@
172174 accountId?: string;
173175 aiGatewaySlug?: string;
174176 profile?: string | undefined;
177+ accessKeyId?: string;
178+ secretAccessKey?: string;
175179
176180 // For IBM watsonx
177181 deploymentId?: string;
@@ -209,6 +213,7 @@
209213 this.title = options.title;
210214 this.uniqueId = options.uniqueId ?? "None";
211215 this.baseAgentSystemMessage = options.baseAgentSystemMessage;
216+ this.basePlanSystemMessage = options.basePlanSystemMessage;
212217 this.baseChatSystemMessage = options.baseChatSystemMessage;
213218 this.contextLength =
214219 options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
@@ -246,6 +251,7 @@
246251
247252 // continueProperties
248253 this.apiKeyLocation = options.apiKeyLocation;
254+ this.envSecretLocations = options.envSecretLocations;
249255 this.orgScopeId = options.orgScopeId;
250256 this.apiBase = options.apiBase;
251257
@@ -270,6 +276,8 @@
270276 this.region = options.region;
271277 this.projectId = options.projectId;
272278 this.profile = options.profile;
279+ this.accessKeyId = options.accessKeyId;
280+ this.secretAccessKey = options.secretAccessKey;
273281
274282 this.openaiAdapter = this.createOpenAiAdapter();
275283
@@ -292,6 +300,7 @@
292300 apiKey: this.apiKey ?? "",
293301 apiBase: this.apiBase,
294302 requestOptions: this.requestOptions,
303+ env: this._llmOptions.env,
295304 });
296305 }
297306
@@ -383,6 +392,50 @@
383392 }
384393 }
385394
395+ private async parseError(resp: any): Promise<Error> {
396+ let text = await resp.text();
397+
398+ if (resp.status === 404 && !resp.url.includes("/v1")) {
399+ const parsedError = JSON.parse(text);
400+ const errorMessageRaw = parsedError?.error ?? parsedError?.message;
401+ const error =
402+ typeof errorMessageRaw === "string"
403+ ? errorMessageRaw.replace(/"/g, "'")
404+ : undefined;
405+ let model = error?.match(/model '(.*)' not found/)?.[1];
406+ if (model && resp.url.match("127.0.0.1:11434")) {
407+ text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
408+ return new LLMError(text, this); // No need to add HTTP status details
409+ } else if (text.includes("/api/chat")) {
410+ text =
411+ "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
412+ } else {
413+ text =
414+ "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
415+ }
416+ } else if (resp.status === 404 && resp.url.includes("api.openai.com")) {
417+ text =
418+ "You may need to add pre-paid credits before using the OpenAI API.";
419+ } else if (
420+ resp.status === 401 &&
421+ (resp.url.includes("api.mistral.ai") ||
422+ resp.url.includes("codestral.mistral.ai"))
423+ ) {
424+ if (resp.url.includes("codestral.mistral.ai")) {
425+ return new Error(
426+ "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
427+ );
428+ } else {
429+ return new Error(
430+ "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
431+ );
432+ }
433+ }
434+ return new Error(
435+ `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
436+ );
437+ }
438+
386439 fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
387440 // Custom Node.js fetch
388441 const customFetch = async (input: URL | RequestInfo, init: any) => {
@@ -398,44 +451,9 @@
398451 if (resp.status === 499) {
399452 return resp; // client side cancellation
400453 }
401- let text = await resp.text();
402- if (resp.status === 404 && !resp.url.includes("/v1")) {
403- const error = JSON.parse(text)?.error?.replace(/"/g, "'");
404- let model = error?.match(/model '(.*)' not found/)?.[1];
405- if (model && resp.url.match("127.0.0.1:11434")) {
406- text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
407- throw new LLMError(text, this); // No need to add HTTP status details
408- } else if (text.includes("/api/chat")) {
409- text =
410- "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
411- } else {
412- text =
413- "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
414- }
415- } else if (
416- resp.status === 404 &&
417- resp.url.includes("api.openai.com")
418- ) {
419- text =
420- "You may need to add pre-paid credits before using the OpenAI API.";
421- } else if (
422- resp.status === 401 &&
423- (resp.url.includes("api.mistral.ai") ||
424- resp.url.includes("codestral.mistral.ai"))
425- ) {
426- if (resp.url.includes("codestral.mistral.ai")) {
427- throw new Error(
428- "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
429- );
430- } else {
431- throw new Error(
432- "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
433- );
434- }
435- }
436- throw new Error(
437- `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
438- );
454+
455+ const error = await this.parseError(resp);
456+ throw error;
439457 }
440458
441459 return resp;
@@ -491,28 +509,32 @@
491509 const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
492510 let formatted = "";
493511 for (const msg of msgsCopy) {
494- let contentToShow = "";
495- if (msg.role === "tool") {
496- contentToShow = msg.content;
497- } else if (msg.role === "assistant" && msg.toolCalls) {
498- contentToShow = msg.toolCalls
499- ?.map(
500- (toolCall) =>
501- `${toolCall.function?.name}(${toolCall.function?.arguments})`,
502- )
503- .join("\n");
504- } else if ("content" in msg) {
505- if (Array.isArray(msg.content)) {
506- msg.content = renderChatMessage(msg);
507- }
508- contentToShow = msg.content;
509- }
510-
511- formatted += `<${msg.role}>\n${contentToShow}\n\n`;
512+ formatted += this._formatChatMessage(msg);
512513 }
513514 return formatted;
514515 }
515516
517+ private _formatChatMessage(msg: ChatMessage): string {
518+ let contentToShow = "";
519+ if (msg.role === "tool") {
520+ contentToShow = msg.content;
521+ } else if (msg.role === "assistant" && msg.toolCalls) {
522+ contentToShow = msg.toolCalls
523+ ?.map(
524+ (toolCall) =>
525+ `${toolCall.function?.name}(${toolCall.function?.arguments})`,
526+ )
527+ .join("\n");
528+ } else if ("content" in msg) {
529+ if (Array.isArray(msg.content)) {
530+ msg.content = renderChatMessage(msg);
531+ }
532+ contentToShow = msg.content;
533+ }
534+
535+ return `<${msg.role}>\n${contentToShow}\n\n`;
536+ }
537+
516538 protected async *_streamFim(
517539 prefix: string,
518540 suffix: string,
@@ -568,11 +590,12 @@
568590 const result = fromChatCompletionChunk(chunk);
569591 if (result) {
570592 const content = renderChatMessage(result);
593+ const formattedContent = this._formatChatMessage(result);
571594 interaction?.logItem({
572595 kind: "chunk",
573- chunk: content,
596+ chunk: formattedContent,
574597 });
575- completion += content;
598+ completion += formattedContent;
576599 yield content;
577600 }
578601 }
@@ -931,7 +954,7 @@
931954 );
932955 const msg = fromChatResponse(response);
933956 yield msg;
934- completion = renderChatMessage(msg);
957+ completion = this._formatChatMessage(msg);
935958 } else {
936959 // Stream true
937960 const stream = this.openaiAdapter.chatCompletionStream(
@@ -944,7 +967,7 @@
944967 for await (const chunk of stream) {
945968 const result = fromChatCompletionChunk(chunk);
946969 if (result) {
947- completion += result.content;
970+ completion += this._formatChatMessage(result);
948971 interaction?.logItem({
949972 kind: "message",
950973 message: result,
@@ -960,7 +983,7 @@
960983 completionOptions,
961984 )) {
962985 if (chunk.role === "assistant") {
963- completion += chunk.content;
986+ completion += this._formatChatMessage(chunk);
964987 } else if (chunk.role === "thinking") {
965988 thinking += chunk.content;
966989 }
@@ -1068,9 +1091,17 @@
10681091 documents: chunks.map((chunk) => chunk.content),
10691092 });
10701093
1071- // Put them in the order they were given
1072- const sortedResults = results.data.sort((a, b) => a.index - b.index);
1073- return sortedResults.map((result) => result.relevance_score);
1094+ // Standard OpenAI format
1095+ if (results.data && Array.isArray(results.data)) {
1096+ return results.data
1097+ .sort((a, b) => a.index - b.index)
1098+ .map((result) => result.relevance_score);
1099+ }
1100+
1101+ throw new Error(
1102+ `Unexpected rerank response format from ${this.providerName}. ` +
1103+ `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`,
1104+ );
10741105 }
10751106
10761107 throw new Error(
modified core/llm/llm.test.ts +7 −21
@@ -161,12 +161,7 @@
161161 group: "Hello",
162162 },
163163 ],
164- toolChoice: {
165- type: "function",
166- function: {
167- name: "say_hello",
168- },
169- },
164+ toolChoice: { type: "function", function: { name: "say_hello" } },
170165 },
171166 )) {
172167 const typedChunk = chunk as AssistantChatMessage;
@@ -211,10 +206,7 @@
211206 model: "claude-3-5-sonnet-latest",
212207 apiKey: process.env.ANTHROPIC_API_KEY,
213208 }),
214- {
215- skip: false,
216- testToolCall: true,
217- },
209+ { skip: false, testToolCall: true },
218210 );
219211 testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), {
220212 skip: false,
@@ -240,12 +232,7 @@
240232 apiKey: process.env.MISTRAL_API_KEY,
241233 model: "codestral-latest",
242234 }),
243- {
244- testFim: true,
245- skip: false,
246- testToolCall: true,
247- timeout: 60000,
248- },
235+ { testFim: true, skip: false, testToolCall: true, timeout: 60000 },
249236 );
250237 testLLM(
251238 new Azure({
@@ -260,11 +247,10 @@
260247 );
261248 testLLM(
262249 new Azure({
263- apiKey: process.env.AZURE_FOUNDRY_API_KEY,
264- model: "codestral-latest",
265- apiBase:
266- "https://codestral-2501-continue-testing.eastus.models.ai.azure.com",
267- apiType: "azure-foundry",
250+ apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY,
251+ model: "Codestral-2501",
252+ apiBase: "https://continue-foundry-resource.services.ai.azure.com",
253+ env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" },
268254 }),
269255 { testFim: false, skip: false, timeout: 20000 },
270256 );
modified core/llm/llms/Anthropic.ts +0 −1
@@ -8,7 +8,6 @@
88 static providerName = "anthropic";
99 static defaultOptions: Partial<LLMOptions> = {
1010 model: "claude-3-5-sonnet-latest",
11- contextLength: 200_000,
1211 completionOptions: {
1312 model: "claude-3-5-sonnet-latest",
1413 maxTokens: 8192,
modified core/llm/llms/Bedrock.test.ts +248 −80
@@ -1,12 +1,10 @@
1-import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
2-import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
3-import Bedrock from "./Bedrock.js";
41 import {
52 ChatMessage,
63 Chunk,
74 CompletionOptions,
85 UserChatMessage,
96 } from "../../index.js";
7+import Bedrock from "./Bedrock.js";
108
119 // Mock AWS SDK
1210 jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@@ -317,96 +315,266 @@
317315 });
318316 });
319317
320- it("should convert text messages correctly", () => {
321- const message: ChatMessage = {
322- role: "user",
323- content: "Hello",
324- } as UserChatMessage;
325- const converted = bedrock["_convertMessage"](message);
326- expect(converted).toEqual({
327- role: "user",
328- content: [{ text: "Hello" }],
329- });
318+ it("should convert simple user and assistant messages correctly", () => {
319+ const messages: ChatMessage[] = [
320+ { role: "user", content: "Hello" } as UserChatMessage,
321+ { role: "assistant", content: "Hi there" },
322+ ];
323+
324+ const availableTools = new Set<string>();
325+ const converted = bedrock["_convertMessages"](messages, availableTools);
326+
327+ expect(converted).toEqual([
328+ { role: "user", content: [{ text: "Hello" }] },
329+ { role: "assistant", content: [{ text: "Hi there" }] },
330+ ]);
330331 });
331332
332- it("should convert tool responses correctly", () => {
333- const message: ChatMessage = {
334- role: "tool",
335- content: "Tool result",
336- toolCallId: "tool-1",
337- };
338- const converted = bedrock["_convertMessage"](message);
339- expect(converted).toEqual({
340- role: "user",
341- content: [
342- {
343- toolResult: {
344- toolUseId: "tool-1",
345- content: [{ text: "Tool result" }],
333+ it("should handle tool responses correctly", () => {
334+ const messages: ChatMessage[] = [
335+ { role: "user", content: "Use a tool" } as UserChatMessage,
336+ {
337+ role: "assistant",
338+ content: "",
339+ toolCalls: [
340+ {
341+ id: "tool-1",
342+ type: "function",
343+ function: {
344+ name: "test_tool",
345+ arguments: '{"arg":"value"}',
346+ },
346347 },
347- },
348- ],
349- });
348+ ],
349+ },
350+ {
351+ role: "tool",
352+ content: "Tool result",
353+ toolCallId: "tool-1",
354+ },
355+ ];
356+
357+ const availableTools = new Set(["test_tool"]);
358+ const converted = bedrock["_convertMessages"](messages, availableTools);
359+
360+ expect(converted).toEqual([
361+ { role: "user", content: [{ text: "Use a tool" }] },
362+ {
363+ role: "assistant",
364+ content: [
365+ {
366+ toolUse: {
367+ toolUseId: "tool-1",
368+ name: "test_tool",
369+ input: { arg: "value" },
370+ },
371+ },
372+ ],
373+ },
374+ {
375+ role: "user",
376+ content: [
377+ {
378+ toolResult: {
379+ toolUseId: "tool-1",
380+ content: [{ text: "Tool result" }],
381+ },
382+ },
383+ ],
384+ },
385+ ]);
350386 });
351387
352- it("should convert tool calls correctly", () => {
353- const message: ChatMessage = {
354- role: "assistant",
355- content: "",
356- toolCalls: [
357- {
358- id: "tool-1",
359- type: "function" as const,
360- function: {
361- name: "test_tool",
362- arguments: '{"arg":"value"}',
388+ it("should handle tool calls with unavailable tools as text", () => {
389+ const messages: ChatMessage[] = [
390+ { role: "user", content: "Use a tool" } as UserChatMessage,
391+ {
392+ role: "assistant",
393+ content: "",
394+ toolCalls: [
395+ {
396+ id: "tool-1",
397+ type: "function",
398+ function: {
399+ name: "unavailable_tool",
400+ arguments: '{"arg":"value"}',
401+ },
363402 },
364- },
365- ],
366- };
367- const converted = bedrock["_convertMessage"](message);
368- expect(converted).toEqual({
369- role: "assistant",
370- content: [
371- {
372- toolUse: {
373- toolUseId: "tool-1",
374- name: "test_tool",
375- input: { arg: "value" },
403+ ],
404+ },
405+ ];
406+
407+ // Empty set means no tools are available
408+ const availableTools = new Set<string>();
409+ const converted = bedrock["_convertMessages"](messages, availableTools);
410+
411+ expect(converted).toEqual([
412+ { role: "user", content: [{ text: "Use a tool" }] },
413+ {
414+ role: "assistant",
415+ content: [
416+ {
417+ text: expect.stringContaining("Assistant tool call:"),
376418 },
377- },
378- ],
379- });
419+ ],
420+ },
421+ ]);
380422 });
381423
382- it("should handle multimodal content correctly", () => {
383- const message: ChatMessage = {
384- role: "user",
385- content: [
386- { type: "text", text: "Look at this image:" },
387- {
388- type: "imageUrl",
389- imageUrl: {
390- url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
424+ it("should handle thinking messages correctly", () => {
425+ const messages: ChatMessage[] = [
426+ { role: "user", content: "Think about this" } as UserChatMessage,
427+ { role: "thinking", content: "I am thinking about the solution" },
428+ { role: "assistant", content: "Here's my answer" },
429+ ];
430+
431+ const availableTools = new Set<string>();
432+ const converted = bedrock["_convertMessages"](messages, availableTools);
433+
434+ expect(converted).toEqual([
435+ { role: "user", content: [{ text: "Think about this" }] },
436+ {
437+ role: "assistant",
438+ content: [
439+ {
440+ reasoningContent: {
441+ reasoningText: {
442+ text: "I am thinking about the solution",
443+ signature: undefined,
444+ },
445+ },
391446 },
392- },
393- ],
394- } as UserChatMessage;
395- const converted = bedrock["_convertMessage"](message);
396- expect(converted).toEqual({
397- role: "user",
398- content: [
399- { text: "Look at this image:" },
400- {
401- image: {
402- format: "jpeg",
403- source: {
404- bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
447+ { text: "Here's my answer" },
448+ ],
449+ },
450+ ]);
451+ });
452+
453+ it("should handle redacted thinking messages", () => {
454+ const messages: ChatMessage[] = [
455+ { role: "user", content: "Think about this" } as UserChatMessage,
456+ {
457+ role: "thinking",
458+ content: "",
459+ redactedThinking: "redacted-content-bytes",
460+ },
461+ { role: "assistant", content: "Here's my answer" },
462+ ];
463+
464+ const availableTools = new Set<string>();
465+ const converted = bedrock["_convertMessages"](messages, availableTools);
466+
467+ expect(converted).toEqual([
468+ { role: "user", content: [{ text: "Think about this" }] },
469+ {
470+ role: "assistant",
471+ content: [
472+ {
473+ reasoningContent: {
474+ redactedContent: expect.any(Uint8Array),
405475 },
406476 },
407- },
408- ],
477+ { text: "Here's my answer" },
478+ ],
479+ },
480+ ]);
481+
482+ // Check that the Uint8Array contains the expected bytes
483+ const redactedContent =
484+ converted[1].content?.[0].reasoningContent?.redactedContent;
485+ expect(redactedContent).toBeInstanceOf(Uint8Array);
486+ expect(Buffer.from(redactedContent!).toString()).toBe(
487+ "redacted-content-bytes",
488+ );
489+ });
490+
491+ it("should convert multimodal content correctly", () => {
492+ const messages: ChatMessage[] = [
493+ {
494+ role: "user",
495+ content: [
496+ { type: "text", text: "Look at this image:" },
497+ {
498+ type: "imageUrl",
499+ imageUrl: {
500+ url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
501+ },
502+ },
503+ ],
504+ } as UserChatMessage,
505+ ];
506+
507+ const availableTools = new Set<string>();
508+ const converted = bedrock["_convertMessages"](messages, availableTools);
509+
510+ expect(converted).toEqual([
511+ {
512+ role: "user",
513+ content: [
514+ { text: "Look at this image:" },
515+ {
516+ image: {
517+ format: "jpeg",
518+ source: {
519+ bytes: expect.any(Uint8Array),
520+ },
521+ },
522+ },
523+ ],
524+ },
525+ ]);
526+
527+ // Check that the image bytes were processed correctly
528+ const imageBytes = converted[0].content?.[1].image?.source?.bytes;
529+ expect(imageBytes).toBeInstanceOf(Uint8Array);
530+ expect(Buffer.from(imageBytes!).toString("base64")).toBe(
531+ "/9j/4AAQSkZJRg==",
532+ );
533+ });
534+
535+ it("should add cache points for prompt caching when needed", () => {
536+ // Create a test instance with caching behavior enabled
537+ const bedrockWithCaching = new TestBedrock({
538+ apiKey: "test-key",
539+ model: "anthropic.claude-3-sonnet-20240229-v1:0",
540+ region: "us-east-1",
409541 });
542+
543+ // Set caching behavior
544+ bedrockWithCaching.cacheBehavior = {
545+ cacheConversation: true,
546+ cacheSystemMessage: true,
547+ };
548+
549+ const messages: ChatMessage[] = [
550+ { role: "system", content: "You are a helpful assistant" },
551+ { role: "user", content: "First message" } as UserChatMessage,
552+ { role: "assistant", content: "First response" },
553+ { role: "user", content: "Second message" } as UserChatMessage,
554+ ];
555+
556+ const availableTools = new Set<string>();
557+ const converted = bedrockWithCaching["_convertMessages"](
558+ messages,
559+ availableTools,
560+ );
561+
562+ // The last two user messages should have cache points
563+ // But we're not testing the system message here since it's handled separately
564+ expect(converted.length).toBe(3);
565+ expect(converted[0].role).toBe("user");
566+ expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
567+ true,
568+ );
569+ expect(converted[1].role).toBe("assistant");
570+ expect(converted[2].role).toBe("user");
571+ expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
572+ true,
573+ );
574+
575+ // Verify that text content includes a cache ID suffix
576+ const userMessageText = converted[0].content?.[0].text;
577+ expect(userMessageText).toMatch(/First message.+/);
410578 });
411579 });
412580 });
modified core/llm/llms/Bedrock.ts +247 −168
@@ -1,8 +1,10 @@
11 import {
22 BedrockRuntimeClient,
33 ContentBlock,
4+ ConversationRole,
45 ConverseStreamCommand,
56 ConverseStreamCommandOutput,
7+ ImageFormat,
68 InvokeModelCommand,
79 Message,
810 ToolConfiguration,
@@ -14,6 +16,7 @@
1416 Chunk,
1517 CompletionOptions,
1618 LLMOptions,
19+ MessageContent,
1720 } from "../../index.js";
1821 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
1922 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
@@ -48,7 +51,6 @@
4851 static defaultOptions: Partial<LLMOptions> = {
4952 region: "us-east-1",
5053 model: "anthropic.claude-3-sonnet-20240229-v1:0",
51- contextLength: 200_000,
5254 profile: "bedrock",
5355 };
5456
@@ -69,11 +71,7 @@
6971 if (!options.apiBase) {
7072 this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
7173 }
72- if (options.profile) {
73- this.profile = options.profile;
74- } else {
75- this.profile = "bedrock";
76- }
74+
7775 this.requestOptions = {
7876 region: options.region,
7977 headers: {},
@@ -290,8 +288,8 @@
290288 const systemMessage = stripImages(
291289 messages.find((m) => m.role === "system")?.content ?? "",
292290 );
293- const convertedMessages = this._convertMessages(messages);
294291
292+ // Prompt and system message caching settings
295293 const shouldCacheSystemMessage =
296294 (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
297295 this.completionOptions.promptCaching;
@@ -299,9 +297,7 @@
299297 shouldCacheSystemMessage ||
300298 this.cacheBehavior?.cacheConversation ||
301299 this.completionOptions.promptCaching;
302- const shouldCacheToolsConfig = this.completionOptions.promptCaching;
303300
304- // Add header for prompt caching
305301 if (enablePromptCaching) {
306302 this.requestOptions.headers = {
307303 ...this.requestOptions.headers,
@@ -309,30 +305,37 @@
309305 };
310306 }
311307
308+ // First get tools
312309 const supportsTools =
313310 (this.capabilities?.tools ||
314311 PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
315312 false;
316313
317- let toolConfig =
318- supportsTools && options.tools
319- ? ({
320- tools: options.tools.map((tool) => ({
321- toolSpec: {
322- name: tool.function.name,
323- description: tool.function.description,
324- inputSchema: {
325- json: tool.function.parameters,
326- },
327- },
328- })),
329- } as ToolConfiguration)
330- : undefined;
331-
332- if (toolConfig?.tools && shouldCacheToolsConfig) {
333- toolConfig.tools.push({ cachePoint: { type: "default" } });
314+ let toolConfig: undefined | ToolConfiguration = undefined;
315+ const availableTools = new Set<string>();
316+ if (supportsTools && options.tools && options.tools.length > 0) {
317+ toolConfig = {
318+ tools: options.tools.map((tool) => ({
319+ toolSpec: {
320+ name: tool.function.name,
321+ description: tool.function.description,
322+ inputSchema: {
323+ json: tool.function.parameters,
324+ },
325+ },
326+ })),
327+ } as ToolConfiguration;
328+ const shouldCacheToolsConfig = this.completionOptions.promptCaching;
329+ if (shouldCacheToolsConfig) {
330+ toolConfig.tools!.push({ cachePoint: { type: "default" } });
331+ }
332+ options.tools.forEach((tool) => {
333+ availableTools.add(tool.function.name);
334+ });
334335 }
335336
337+ const convertedMessages = this._convertMessages(messages, availableTools);
338+
336339 return {
337340 modelId: options.model,
338341 system: systemMessage
@@ -369,185 +372,261 @@
369372 };
370373 }
371374
372- private _convertMessage(
373- message: ChatMessage,
374- addCaching: boolean = false,
375- ): Message | null {
376- // Handle system messages explicitly
377- if (message.role === "system") {
378- return null;
379- }
375+ /*
376+ Converts the messages to the format expected by the Bedrock API.
377+
378+ */
379+ private _convertMessages(
380+ messages: ChatMessage[],
381+ availableTools: Set<string>,
382+ ): Message[] {
383+ let currentRole: "user" | "assistant" = "user";
384+ let currentBlocks: ContentBlock[] = [];
385+
386+ const converted: Message[] = [];
387+ const pushCurrentMessage = () => {
388+ if (currentBlocks.length === 0 && converted.length > 1) {
389+ throw new Error(
390+ `Bedrock: no content in ${currentRole} message before conversational turn change`,
391+ );
392+ }
393+ if (currentBlocks.length > 0) {
394+ converted.push({
395+ role: currentRole,
396+ content: currentBlocks,
397+ });
398+ }
399+ currentBlocks = [];
400+ };
380401
381- const cachePoint = addCaching
382- ? { cachePoint: { type: "default" } }
383- : undefined;
402+ const nonSystemMessages = messages.filter((m) => m.role !== "system");
403+ const hasAddedToolCallIds = new Set<string>();
384404
385- // Tool response handling
386- if (message.role === "tool") {
387- return {
388- role: "user",
389- content: [
390- {
391- toolResult: {
392- toolUseId: message.toolCallId,
393- content: [
394- {
395- text: message.content || "",
405+ for (let idx = 0; idx < nonSystemMessages.length; idx++) {
406+ const message = nonSystemMessages[idx];
407+
408+ if (message.role === "user" || message.role === "tool") {
409+ // Detect conversational turn change
410+ if (currentRole !== ConversationRole.USER) {
411+ pushCurrentMessage();
412+ currentRole = ConversationRole.USER;
413+ }
414+
415+ // USER messages:
416+ // Non-empty user message content is converted to "text" and "image" blocks
417+ // If ANY user message part is cached, we add a single cache point block when we push the message
418+ if (message.role === "user") {
419+ const trimmedContent =
420+ typeof message.content === "string"
421+ ? message.content.trim()
422+ : message.content;
423+ if (trimmedContent) {
424+ currentBlocks.push(
425+ ...this._convertMessageContentToBlocks(trimmedContent),
426+ );
427+ }
428+ }
429+ // TOOL messages:
430+ // Tool messages are represented by "toolResult" blocks
431+ // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
432+ // If it doesn't, we convert it to a text block
433+ else if (message.role === "tool") {
434+ const trimmedContent = message.content.trim() || "No tool output";
435+ if (hasAddedToolCallIds.has(message.toolCallId)) {
436+ currentBlocks.push({
437+ toolResult: {
438+ toolUseId: message.toolCallId,
439+ content: [
440+ {
441+ text: trimmedContent,
442+ },
443+ ],
444+ },
445+ });
446+ } else {
447+ currentBlocks.push({
448+ text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
449+ });
450+ }
451+ }
452+ } else if (message.role === "assistant" || message.role === "thinking") {
453+ // Detect conversational turn change
454+ if (currentRole !== ConversationRole.ASSISTANT) {
455+ pushCurrentMessage();
456+ currentRole = ConversationRole.ASSISTANT;
457+ }
458+
459+ // ASSISTANT messages:
460+ // Non-empty assistant message content is converted to "text" and "image" blocks
461+ if (message.role === "assistant") {
462+ const trimmedContent =
463+ typeof message.content === "string"
464+ ? message.content.trim()
465+ : message.content;
466+ if (trimmedContent) {
467+ currentBlocks.push(
468+ ...this._convertMessageContentToBlocks(trimmedContent),
469+ );
470+ }
471+ // TOOL CALLS:
472+ // Tool calls are represented by "toolUse" blocks
473+ // Each tool call must have an id and a function name
474+ // The function name must match one of the available tools
475+ // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
476+ if (message.toolCalls) {
477+ for (const toolCall of message.toolCalls) {
478+ if (toolCall.id && toolCall.function?.name) {
479+ if (availableTools.has(toolCall.function.name)) {
480+ currentBlocks.push({
481+ toolUse: {
482+ toolUseId: toolCall.id,
483+ name: toolCall.function.name,
484+ input: safeParseToolCallArgs(toolCall),
485+ },
486+ });
487+ hasAddedToolCallIds.add(toolCall.id);
488+ } else {
489+ const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
490+ currentBlocks.push({
491+ text: toolCallText,
492+ });
493+ }
494+ } else {
495+ console.warn(
496+ `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
497+ );
498+ continue;
499+ }
500+ }
501+ }
502+ } else if (message.role === "thinking") {
503+ // THINKING:
504+ // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
505+ if (message.redactedThinking) {
506+ const block: ContentBlock.ReasoningContentMember = {
507+ reasoningContent: {
508+ redactedContent: new Uint8Array(
509+ Buffer.from(message.redactedThinking),
510+ ),
511+ },
512+ };
513+ currentBlocks.push(block);
514+ } else {
515+ const block: ContentBlock.ReasoningContentMember = {
516+ reasoningContent: {
517+ reasoningText: {
518+ text: (message.content as string) || "",
519+ signature: message.signature,
396520 },
397- ],
398- },
399- },
400- ],
401- };
521+ },
522+ };
523+ currentBlocks.push(block);
524+ }
525+ }
526+ }
402527 }
403-
404- // Tool calls handling
405- if (message.role === "assistant" && message.toolCalls) {
406- return {
407- role: "assistant",
408- content: message.toolCalls.map((toolCall) => ({
409- toolUse: {
410- toolUseId: toolCall.id,
411- name: toolCall.function?.name,
412- input: safeParseToolCallArgs(toolCall),
413- },
414- })),
415- };
528+ if (currentBlocks.length > 0) {
529+ pushCurrentMessage();
416530 }
417531
418- if (message.role === "thinking") {
419- if (message.redactedThinking) {
420- const content: ContentBlock.ReasoningContentMember = {
421- reasoningContent: {
422- redactedContent: new Uint8Array(
423- Buffer.from(message.redactedThinking),
424- ),
425- },
426- };
427- return {
428- role: "assistant",
429- content: [content],
430- };
431- } else {
432- const content: ContentBlock.ReasoningContentMember = {
433- reasoningContent: {
434- reasoningText: {
435- text: (message.content as string) || "",
436- signature: message.signature,
437- },
438- },
439- };
440- return {
441- role: "assistant",
442- content: [content],
443- };
444- }
532+ // If caching is enabled, we add cache_control parameter to the last two user messages
533+ // The second-to-last because it retrieves potentially already cached contents,
534+ // The last one because we want it cached for later retrieval.
535+ // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
536+ if (this.cacheBehavior?.cacheConversation) {
537+ this._addCachingToLastTwoUserMessages(converted);
445538 }
446539
447- // Standard text message
448- if (typeof message.content === "string") {
449- if (addCaching) {
450- message.content += getSecureID();
540+ return converted;
541+ }
542+
543+ private _addCachingToLastTwoUserMessages(converted: Message[]) {
544+ let numCached = 0;
545+ for (let i = converted.length - 1; i >= 0; i--) {
546+ const message = converted[i];
547+ if (message.role === "user") {
548+ message.content?.forEach((block) => {
549+ if (block.text) {
550+ block.text += getSecureID();
551+ }
552+ });
553+ message.content?.push({ cachePoint: { type: "default" } });
554+ numCached++;
451555 }
452- const content: any[] = [{ text: message.content }];
453- if (addCaching) {
454- content.push({ cachePoint: { type: "default" } });
556+ if (numCached === 2) {
557+ break;
455558 }
456- return {
457- role: message.role,
458- content,
459- };
460559 }
560+ }
461561
462- // Improved multimodal content handling
463- if (Array.isArray(message.content)) {
464- const content: any[] = [];
465-
466- // Process all parts first
467- message.content.forEach((part) => {
562+ // Converts Continue message content (string/parts) to Bedrock ContentBlock format.
563+ // Unsupported/problematic image formats are skipped with a warning.
564+ private _convertMessageContentToBlocks(
565+ content: MessageContent,
566+ ): ContentBlock[] {
567+ const blocks: ContentBlock[] = [];
568+ if (typeof content === "string") {
569+ blocks.push({ text: content });
570+ } else {
571+ for (const part of content) {
468572 if (part.type === "text") {
469- if (addCaching) {
470- part.text += getSecureID();
471- }
472- content.push({ text: part.text });
573+ blocks.push({ text: part.text });
473574 } else if (part.type === "imageUrl" && part.imageUrl) {
474575 try {
475576 const [mimeType, base64Data] = part.imageUrl.url.split(",");
476577 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
477- content.push({
478- image: {
479- format,
480- source: {
481- bytes: Buffer.from(base64Data, "base64"),
578+ if (
579+ format === ImageFormat.JPEG ||
580+ format === ImageFormat.PNG ||
581+ format === ImageFormat.WEBP ||
582+ format === ImageFormat.GIF
583+ ) {
584+ blocks.push({
585+ image: {
586+ format,
587+ source: {
588+ bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
589+ },
482590 },
483- },
484- });
591+ });
592+ } else {
593+ console.warn(
594+ `Bedrock: skipping unsupported image part format: ${format}`,
595+ part,
596+ );
597+ }
485598 } catch (error) {
486- console.warn(`Failed to process image: ${error}`);
599+ console.warn("Bedrock: failed to process image part", error, part);
487600 }
488601 }
489- });
490-
491- // Add cache point as a separate block at the end if needed
492- if (addCaching && content.length > 0) {
493- content.push({ cachePoint: { type: "default" } });
494602 }
495-
496- return {
497- role: message.role,
498- content,
499- } as Message;
500603 }
501- return null;
502- }
503-
504- private _convertMessages(messages: ChatMessage[]): any[] {
505- const filteredmessages = messages.filter(
506- (m) => m.role !== "system" && !!m.content,
507- );
508- const lastTwoUserMsgIndices = filteredmessages
509- .map((msg, index) => (msg.role === "user" ? index : -1))
510- .filter((index) => index !== -1)
511- .slice(-2);
512-
513- const converted = filteredmessages
514- .map((message, filteredMsgIdx) => {
515- // Add cache_control parameter to the last two user messages
516- // The second-to-last because it retrieves potentially already cached contents,
517- // The last one because we want it cached for later retrieval.
518- // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
519- const addCaching =
520- this.cacheBehavior?.cacheConversation &&
521- lastTwoUserMsgIndices.includes(filteredMsgIdx);
522-
523- try {
524- return this._convertMessage(message, addCaching);
525- } catch (error) {
526- console.error(`Failed to convert message: ${error}`);
527- return null;
528- }
529- })
530- .filter(Boolean);
531-
532- return converted;
604+ return blocks;
533605 }
534606
535607 private async _getCredentials() {
608+ if (this.accessKeyId && this.secretAccessKey) {
609+ return {
610+ accessKeyId: this.accessKeyId,
611+ secretAccessKey: this.secretAccessKey,
612+ };
613+ }
614+ const profile = this.profile ?? "bedrock";
536615 try {
537616 return await fromNodeProviderChain({
538- profile: this.profile,
617+ profile: profile,
539618 ignoreCache: true,
540619 })();
541620 } catch (e) {
542621 console.warn(
543- `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
622+ `AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
544623 );
545- return await fromNodeProviderChain()();
546624 }
625+ return await fromNodeProviderChain()();
547626 }
548627
549628 // EMBED //
550- async embed(chunks: string[]): Promise<number[][]> {
629+ async _embed(chunks: string[]): Promise<number[][]> {
551630 const credentials = await this._getCredentials();
552631 const client = new BedrockRuntimeClient({
553632 region: this.region,
modified core/llm/llms/Cohere.ts +173 −20
@@ -1,9 +1,10 @@
1-import { streamJSON } from "@continuedev/fetch";
1+import { streamSse } from "@continuedev/fetch";
22 import {
33 ChatMessage,
44 Chunk,
55 CompletionOptions,
66 LLMOptions,
7+ MessageContent,
78 } from "../../index.js";
89 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
910 import { BaseLLM } from "../index.js";
@@ -11,21 +12,89 @@
1112 class Cohere extends BaseLLM {
1213 static providerName = "cohere";
1314 static defaultOptions: Partial<LLMOptions> = {
14- apiBase: "https://api.cohere.ai/v1",
15+ apiBase: "https://api.cohere.ai/v2",
1516 maxEmbeddingBatchSize: 96,
1617 };
1718 static maxStopSequences = 5;
1819
1920 private _convertMessages(msgs: ChatMessage[]): any[] {
2021 const messages = [];
22+ let lastToolPlan: MessageContent | undefined;
2123 for (const m of msgs) {
22- if (m.role === "system" || !m.content) {
24+ if (!m.content) {
2325 continue;
2426 }
25- messages.push({
26- role: m.role === "assistant" ? "chatbot" : m.role,
27- message: m.content,
28- });
27+ switch (m.role) {
28+ case "user":
29+ if (typeof m.content === "string") {
30+ messages.push({
31+ role: m.role,
32+ content: m.content,
33+ });
34+ break;
35+ }
36+
37+ messages.push({
38+ role: m.role,
39+ content: m.content.map((part) => {
40+ if (part.type === "imageUrl") {
41+ return {
42+ type: "image_url",
43+ image_url: { url: part.imageUrl.url },
44+ };
45+ }
46+ return part;
47+ }),
48+ });
49+ break;
50+ case "thinking":
51+ lastToolPlan = m.content;
52+ break;
53+ case "assistant":
54+ if (m.toolCalls) {
55+ if (!lastToolPlan) {
56+ throw new Error("No tool plan found");
57+ }
58+ messages.push({
59+ role: m.role,
60+ tool_calls: m.toolCalls.map((toolCall) => ({
61+ id: toolCall.id,
62+ type: "function",
63+ function: {
64+ name: toolCall.function?.name,
65+ arguments: toolCall.function?.arguments,
66+ },
67+ })),
68+ // Ideally the tool plan would be in this message, but it is
69+ // split in another, usually the previous, this one's content is
70+ // a space.
71+ // tool_plan: m.content,
72+ tool_plan: lastToolPlan,
73+ });
74+ lastToolPlan = undefined;
75+ break;
76+ }
77+ messages.push({
78+ role: m.role,
79+ content: m.content,
80+ });
81+ break;
82+ case "system":
83+ messages.push({
84+ role: m.role,
85+ content: stripImages(m.content),
86+ });
87+ break;
88+ case "tool":
89+ messages.push({
90+ role: m.role,
91+ content: m.content,
92+ tool_call_id: m.toolCallId,
93+ });
94+ break;
95+ default:
96+ break;
97+ }
2998 }
3099 return messages;
31100 }
@@ -41,7 +110,14 @@
41110 stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences),
42111 frequency_penalty: options.frequencyPenalty,
43112 presence_penalty: options.presencePenalty,
44- raw_prompting: options.raw,
113+ tools: options.tools?.map((tool) => ({
114+ type: "function",
115+ function: {
116+ name: tool.function.name,
117+ parameters: tool.function.parameters,
118+ description: tool.function.description,
119+ },
120+ })),
45121 };
46122 }
47123
@@ -67,19 +143,12 @@
67143 ...this.requestOptions?.headers,
68144 };
69145
70- let preamble: string | undefined = undefined;
71- const systemMessage = messages.find((m) => m.role === "system")?.content;
72- if (systemMessage) {
73- preamble = stripImages(systemMessage);
74- }
75146 const resp = await this.fetch(new URL("chat", this.apiBase), {
76147 method: "POST",
77148 headers,
78149 body: JSON.stringify({
79150 ...this._convertArgs(options),
80- message: messages.pop()?.content,
81- chat_history: this._convertMessages(messages),
82- preamble,
151+ messages: this._convertMessages(messages),
83152 }),
84153 signal,
85154 });
@@ -90,13 +159,97 @@
90159
91160 if (options.stream === false) {
92161 const data = await resp.json();
93- yield { role: "assistant", content: data.text };
162+ if (data.message.tool_calls) {
163+ yield {
164+ // Use the "thinking" role for `tool_plan`, since there is no such
165+ // role in the Cohere API at the moment and it is a "a
166+ // chain-of-thought style reflection".
167+ role: "thinking",
168+ content: data.message.tool_plan,
169+ };
170+ yield {
171+ role: "assistant",
172+ content: "",
173+ toolCalls: data.message.tool_calls.map((toolCall: any) => ({
174+ id: toolCall.id,
175+ type: "function",
176+ function: {
177+ name: toolCall.function?.name,
178+ arguments: toolCall.function?.arguments,
179+ },
180+ })),
181+ };
182+ return;
183+ }
184+ yield { role: "assistant", content: data.message.content[0].text };
94185 return;
95186 }
96187
97- for await (const value of streamJSON(resp)) {
98- if (value.event_type === "text-generation") {
99- yield { role: "assistant", content: value.text };
188+ let lastToolUseId: string | undefined;
189+ let lastToolUseName: string | undefined;
190+ for await (const value of streamSse(resp)) {
191+ // https://docs.cohere.com/v2/docs/streaming#stream-events
192+ switch (value.type) {
193+ // https://docs.cohere.com/v2/docs/streaming#content-delta
194+ case "content-delta":
195+ yield {
196+ role: "assistant",
197+ content: value.delta.message.content.text,
198+ };
199+ break;
200+ // https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan
201+ case "tool-plan-delta":
202+ // Use the "thinking" role for `tool_plan`, since there is no such
203+ // role in the Cohere API at the moment and it is a "a
204+ // chain-of-thought style reflection".
205+ yield {
206+ role: "thinking",
207+ content: value.delta.message.tool_plan,
208+ };
209+ break;
210+ case "tool-call-start":
211+ lastToolUseId = value.delta.message.tool_calls.id;
212+ lastToolUseName = value.delta.message.tool_calls.function.name;
213+ yield {
214+ role: "assistant",
215+ content: "",
216+ toolCalls: [
217+ {
218+ id: lastToolUseId,
219+ type: "function",
220+ function: {
221+ name: lastToolUseName,
222+ arguments: value.delta.message.tool_calls.function.arguments,
223+ },
224+ },
225+ ],
226+ };
227+ break;
228+ case "tool-call-delta":
229+ if (!lastToolUseId || !lastToolUseName) {
230+ throw new Error("No tool use found");
231+ }
232+ yield {
233+ role: "assistant",
234+ content: "",
235+ toolCalls: [
236+ {
237+ id: lastToolUseId,
238+ type: "function",
239+ function: {
240+ name: lastToolUseName,
241+ arguments: value.delta.message.tool_calls.function.arguments,
242+ },
243+ },
244+ ],
245+ };
246+ break;
247+ case "tool-call-end":
248+ lastToolUseId = undefined;
249+ lastToolUseName = undefined;
250+ break;
251+ default:
252+ break;
100253 }
101254 }
102255 }
modified core/llm/llms/HuggingFaceTEI.ts +1 −10
@@ -25,16 +25,7 @@
2525 });
2626 }
2727
28- async embed(chunks: string[]) {
29- const batchedChunks = this.getBatchedChunks(chunks);
30-
31- const results = await Promise.all(
32- batchedChunks.map((batch) => this.doEmbedRequest(batch)),
33- );
34- return results.flat();
35- }
36-
37- async doEmbedRequest(batch: string[]): Promise<number[][]> {
28+ async _embed(batch: string[]): Promise<number[][]> {
3829 const headers: Record<string, string> = {
3930 "Content-Type": "application/json",
4031 };
added core/llm/llms/LlamaStack.ts +57 −0
@@ -0,0 +1,57 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { CompletionOptions, LLMOptions } from "../../index.js";
3+import { osModelsEditPrompt } from "../templates/edit.js";
4+
5+import OpenAI from "./OpenAI.js";
6+
7+class LlamaStack extends OpenAI {
8+ static providerName = "llamastack";
9+ static defaultOptions: Partial<LLMOptions> = {
10+ apiBase: "http://localhost:8321/v1/openai/v1/",
11+ model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
12+ promptTemplates: {
13+ edit: osModelsEditPrompt,
14+ },
15+ useLegacyCompletionsEndpoint: false,
16+ };
17+ maxStopWords: number | undefined = 16;
18+
19+ supportsFim(): boolean {
20+ return true;
21+ }
22+
23+ async *_streamFim(
24+ prefix: string,
25+ suffix: string,
26+ signal: AbortSignal,
27+ options: CompletionOptions,
28+ ): AsyncGenerator<string> {
29+ const endpoint = new URL("completions", this.apiBase);
30+ const resp = await this.fetch(endpoint, {
31+ method: "POST",
32+ body: JSON.stringify({
33+ model: options.model,
34+ prompt: prefix,
35+ suffix,
36+ max_tokens: options.maxTokens,
37+ temperature: options.temperature,
38+ top_p: options.topP,
39+ frequency_penalty: options.frequencyPenalty,
40+ presence_penalty: options.presencePenalty,
41+ stop: options.stop,
42+ stream: true,
43+ }),
44+ headers: {
45+ "Content-Type": "application/json",
46+ Accept: "application/json",
47+ Authorization: `Bearer ${this.apiKey}`,
48+ },
49+ signal,
50+ });
51+ for await (const chunk of streamSse(resp)) {
52+ yield chunk.choices[0].text;
53+ }
54+ }
55+}
56+
57+export default LlamaStack;
modified core/llm/llms/Ollama.ts +0 −1
@@ -405,7 +405,6 @@
405405 parameters: tool.function.parameters,
406406 },
407407 }));
408- chatOptions.stream = false; // Cannot set stream = true for tools calls
409408 }
410409 const headers: Record<string, string> = {
411410 "Content-Type": "application/json",
modified core/llm/llms/SageMaker.ts +1 −1
@@ -141,7 +141,7 @@
141141 }
142142 }
143143
144- async embed(chunks: string[]) {
144+ async _embed(chunks: string[]) {
145145 const credentials = await this._getCredentials();
146146 const client = new SageMakerRuntimeClient({
147147 region: this.region,
modified core/llm/llms/Test.ts +10 −1
@@ -2,6 +2,7 @@
22 import { BaseLLM } from "../index.js";
33
44 const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
5+const NEXT_EDIT_COMPLETION: string = "<|editable_region_start|>\nHELLO\n";
56
67 class TestLLM extends BaseLLM {
78 static providerName = "test";
@@ -24,7 +25,15 @@
2425 signal: AbortSignal,
2526 options: CompletionOptions,
2627 ): AsyncGenerator<string> {
27- yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
28+ if (
29+ prompt === "NEXT_EDIT" ||
30+ prompt ===
31+ "<|im_start|>user\nNEXT_EDIT<|im_end|>\n<|im_start|>assistant\n"
32+ ) {
33+ yield NEXT_EDIT_COMPLETION;
34+ } else {
35+ yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
36+ }
2837 }
2938
3039 protected async *_streamChat(
modified core/llm/llms/VertexAI.ts +149 −27
@@ -1,4 +1,4 @@
1-import { GoogleAuth } from "google-auth-library";
1+import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
22
33 import { streamResponse, streamSse } from "@continuedev/fetch";
44 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
@@ -14,30 +14,40 @@
1414 declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
1515 declare anthropicInstance: Anthropic;
1616 declare geminiInstance: Gemini;
17+ static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
1718
1819 static defaultOptions: Partial<LLMOptions> | undefined = {
1920 maxEmbeddingBatchSize: 250,
2021 region: "us-central1",
2122 };
2223
23- private clientPromise = new GoogleAuth({
24- scopes: "https://www.googleapis.com/auth/cloud-platform",
25- })
26- .getClient()
27- .catch((e) => {
28- console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
29- });
24+ private clientPromise: Promise<AuthClient | void>;
3025
31- private static getDefaultApiBaseFrom(options: LLMOptions) {
32- const { region, projectId } = options;
33- if (!region || !projectId) {
34- throw new Error(
35- "region and projectId must be defined if apiBase is not provided",
36- );
37- }
38- return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
39- }
26+ /*
27+ Vertex Supports 3 different URL formats
28+ 1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent
29+ 2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent
30+ 3. Express mode: e.g. https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:streamGenerateContent?key={API_KEY} // see https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview
31+
32+ Authentication can be done using the following
33+ 2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region
34+ 1. API Key (express mode), region and projectId will be ignored
4035
36+ In all cases we have defined apiBase to be up to everything including the location.
37+ Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/
38+ Express api base: https://aiplatform.googleapis.com/v1/
39+ TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet
40+
41+ Note that VertexAI uses the term "service endpoint" and "model", like:
42+ {service-endpoint}/v1/{model}:streamGenerateContent
43+ So "model" includes the project, location, publisher, etc
44+
45+ Express mode has limited support
46+ and CRITICALLY is only available to NEW users who had NOT used cloud services before.
47+ However it is pretty common as gemini becomes more popular.
48+ Only Gemini models are supported for now
49+ https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models
50+ */
4151 constructor(_options: LLMOptions) {
4252 if (_options.region !== "us-central1") {
4353 // Any region outside of us-central1 has a max batch size of 5.
@@ -47,7 +57,7 @@
4757 );
4858 }
4959 super(_options);
50- this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
60+
5161 this.vertexProvider =
5262 _options.model.includes("mistral") ||
5363 _options.model.includes("codestral") ||
@@ -58,24 +68,130 @@
5868 : _options.model.includes("gemini")
5969 ? "gemini"
6070 : "unknown";
71+
72+ // Set client authentication promise
73+ const { apiKey, region, projectId, env } = _options;
74+ const keyFile = env?.keyFile;
75+ const keyJson = env?.keyJson;
76+
77+ // Acceptable authentication methods:
78+ // apiKey only
79+ // region and projectId AND (keyFile OR keyJson OR nothing)
80+
81+ if (apiKey) {
82+ // Consider warning here instead of throwing error
83+ if (region || projectId || keyFile || keyJson) {
84+ throw new Error(
85+ "Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson",
86+ );
87+ // console.warn(
88+ // "Region, projectId, and key path/file are ignored when apiKey is set. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview",
89+ // );
90+ }
91+ if (this.vertexProvider !== "gemini") {
92+ throw new Error(
93+ "VertexAI: only gemini models are supported in express (apiKey) mode. See https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models",
94+ );
95+ }
96+ } else {
97+ if (!region && !projectId) {
98+ throw new Error(
99+ "region and projectId are required for VertexAI (when not using express/apiKey mode)",
100+ );
101+ }
102+ if (keyFile && keyJson) {
103+ throw new Error(
104+ "VertexAI credentials can be configured with either keyFile or keyJson but not both",
105+ );
106+ }
107+ }
108+
109+ if (keyJson) {
110+ // Loading keys from manually set JSON
111+ if (typeof keyJson !== "string") {
112+ throw new Error("VertexAI: keyJson must be a JSON string");
113+ }
114+ try {
115+ const parsed = JSON.parse(keyJson);
116+ if (!parsed?.private_key) {
117+ throw new Error("VertexAI: keyJson must contain a valid private key");
118+ }
119+ parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
120+ const jsonClient = auth.fromJSON(parsed);
121+ if (jsonClient instanceof JWT) {
122+ jsonClient.scopes = [VertexAI.AUTH_SCOPES];
123+ } else {
124+ throw new Error("VertexAI: keyJson must be a valid JWT");
125+ }
126+ this.clientPromise = Promise.resolve(jsonClient);
127+ } catch (e) {
128+ throw new Error("VertexAI: Failed to parse keyJson");
129+ }
130+ } else if (keyFile) {
131+ // Loading keys from manually set file path
132+ if (typeof keyFile !== "string") {
133+ throw new Error("VertexAI: keyFile must be a string");
134+ }
135+ this.clientPromise = new GoogleAuth({
136+ scopes: VertexAI.AUTH_SCOPES,
137+ keyFile,
138+ })
139+ .getClient()
140+ .catch((e) => {
141+ console.warn(
142+ `Failed to load credentials for Vertex AI: ${e.message}`,
143+ );
144+ });
145+ } else {
146+ // Loading keys from local credentials or environment variable
147+ this.clientPromise = new GoogleAuth({
148+ scopes: VertexAI.AUTH_SCOPES,
149+ })
150+ .getClient()
151+ .catch((e) => {
152+ console.warn(
153+ `Failed to load credentials for Vertex AI: ${e.message}`,
154+ );
155+ });
156+ }
157+
158+ // Set api base
159+ if (!this.apiBase) {
160+ if (apiKey) {
161+ // Express mode
162+ this.apiBase = `https://aiplatform.googleapis.com/v1/`;
163+ } else {
164+ this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
165+ }
166+ }
167+
168+ // Uses instances of other LLMs since underlying functionality is the same
61169 this.anthropicInstance = new Anthropic(_options);
62170 this.geminiInstance = new Gemini(_options);
63171 }
64172
65- async fetch(url: RequestInfo | URL, init?: RequestInit) {
66- const client = await this.clientPromise;
67- const result = await client?.getAccessToken();
68- if (!result?.token) {
69- throw new Error(
70- "Could not get an access token. Set up your Google Application Default Credentials.",
71- );
173+ async fetch(url: URL, init?: RequestInit) {
174+ const headers: Record<string, string> = {
175+ "Content-Type": "application/json",
176+ };
177+ if (this.apiKey) {
178+ url.searchParams.set("key", this.apiKey);
179+ } else {
180+ const client = await this.clientPromise;
181+ const result = await client?.getAccessToken();
182+ if (!result?.token) {
183+ throw new Error(
184+ "Could not get an access token. Set up your Google Application Default Credentials.",
185+ );
186+ }
187+ headers.Authorization = `Bearer ${result.token}`;
72188 }
189+
73190 return await super.fetch(url, {
74191 ...init,
75192 headers: {
76- "Content-Type": "application/json",
77- Authorization: `Bearer ${result.token}`,
78193 ...init?.headers,
194+ ...headers,
79195 },
80196 });
81197 }
@@ -85,6 +201,10 @@
85201 const convertedArgs = this.anthropicInstance.convertArgs(options);
86202
87203 // Remove the `model` property and add `anthropic_version`
204+ // For claude 4 models
205+ // anthropic_version is a required parameter and must be set to "vertex-2024-10-22".
206+
207+ // const
88208 const { model, ...finalOptions } = convertedArgs;
89209 return {
90210 ...finalOptions,
@@ -104,6 +224,8 @@
104224 this.cacheBehavior?.cacheSystemMessage && systemMessage
105225 );
106226
227+ // <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
228+
107229 const apiURL = new URL(
108230 `publishers/anthropic/models/${options.model}:streamRawPredict`,
109231 this.apiBase,
modified core/llm/llms/Vllm.ts +41 −1
@@ -1,7 +1,25 @@
1-import { LLMOptions } from "../../index.js";
1+import { Chunk, LLMOptions } from "../../index.js";
22
33 import OpenAI from "./OpenAI.js";
44
5+// vLLM-specific rerank response types
6+interface VllmRerankItem {
7+ index: number;
8+ document: {
9+ text: string;
10+ };
11+ relevance_score: number;
12+}
13+
14+interface VllmRerankResponse {
15+ id: string;
16+ model: string;
17+ usage: {
18+ total_tokens: number;
19+ };
20+ results: VllmRerankItem[];
21+}
22+
523 class Vllm extends OpenAI {
624 static providerName = "vllm";
725 constructor(options: LLMOptions) {
@@ -16,6 +34,28 @@
1634 return false;
1735 }
1836
37+ async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
38+ if (this.useOpenAIAdapterFor.includes("rerank") && this.openaiAdapter) {
39+ const results = (await this.openaiAdapter.rerank({
40+ model: this.model,
41+ query,
42+ documents: chunks.map((chunk) => chunk.content),
43+ })) as unknown as VllmRerankResponse;
44+
45+ // vLLM uses 'results' array instead of 'data'
46+ if (results.results && Array.isArray(results.results)) {
47+ const sortedResults = results.results.sort((a, b) => a.index - b.index);
48+ return sortedResults.map((result) => result.index);
49+ }
50+
51+ throw new Error(
52+ `vLLM rerank response missing 'results' array. Got: ${JSON.stringify(Object.keys(results))}`,
53+ );
54+ }
55+
56+ throw new Error("vLLM rerank requires OpenAI adapter");
57+ }
58+
1959 private _setupCompletionOptions() {
2060 this.fetch(this._getEndpoint("models"), {
2161 method: "GET",
modified core/llm/llms/WatsonX.ts +69 −29
@@ -1,9 +1,12 @@
11 import { streamResponse, streamSse } from "@continuedev/fetch";
22 import {
3+ AssistantChatMessage,
34 ChatMessage,
45 Chunk,
56 CompletionOptions,
67 LLMOptions,
8+ ToolCallDelta,
9+ ToolResultChatMessage,
710 } from "../../index.js";
811 import { BaseLLM } from "../index.js";
912 import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
@@ -89,30 +92,24 @@
8992 static providerName = "watsonx";
9093
9194 protected _convertMessage(message: ChatMessage) {
92- if (typeof message.content === "string") {
93- return message;
94- }
95-
96- if (message.role === "tool") {
97- return null;
95+ let message_ = message as any;
96+ if (message_.role === "tool") {
97+ message_.tool_call_id = (message as ToolResultChatMessage).toolCallId;
98+ delete message_.toolCallId;
99+ } else if (message.role === "assistant" && !!message.toolCalls) {
100+ message_.tool_calls = message.toolCalls.map((t) => ({
101+ ...t,
102+ type: "function",
103+ }));
104+ delete message_.toolCalls;
105+ delete message_.content;
106+ } else if (
107+ message_.role === "user" &&
108+ typeof message_.content === "string"
109+ ) {
110+ message_.content = [{ type: "text", text: message_.content }];
98111 }
99-
100- const parts = message.content.map((part) => {
101- if (part.type === "imageUrl") {
102- return {
103- type: "image_url",
104- image_url: { ...part.imageUrl, detail: "low" },
105- };
106- }
107- return {
108- type: "text",
109- text: part.text,
110- };
111- });
112- return {
113- ...message,
114- content: parts,
115- };
112+ return message_;
116113 }
117114
118115 protected _convertArgs(options: any, messages: ChatMessage[]) {
@@ -257,11 +254,11 @@
257254 const headers = this._getHeaders();
258255
259256 const payload: any = {
260- messages: messages,
257+ messages: messages.map(this._convertMessage).filter(Boolean),
261258 max_tokens: options.maxTokens ?? 1024,
262259 stop: stopSequences,
263- frequency_penalty: options.frequencyPenalty || 1,
264- presence_penalty: options.presencePenalty || 1,
260+ frequency_penalty: options.frequencyPenalty ?? 0,
261+ presence_penalty: options.presencePenalty ?? 0,
265262 };
266263
267264 if (!this.deploymentId) {
@@ -291,10 +288,53 @@
291288 signal,
292289 });
293290
291+ let toolName;
292+ let toolCallId = null;
293+ let accumulatedArgs = "";
294+
294295 for await (const value of streamSse(response)) {
295- const chunk = fromChatCompletionChunk(value);
296- if (chunk) {
297- yield chunk;
296+ const message = fromChatCompletionChunk(value);
297+ if (!!message) {
298+ if (
299+ (message as AssistantChatMessage)?.toolCalls &&
300+ (message as AssistantChatMessage).toolCalls?.length !== 0
301+ ) {
302+ let chunk = message as AssistantChatMessage;
303+ if (!!chunk.toolCalls?.[0]?.id) {
304+ toolCallId = chunk.toolCalls?.[0]?.id;
305+ }
306+ if (!!chunk.toolCalls?.[0]?.function?.name) {
307+ accumulatedArgs = "";
308+ toolName = chunk.toolCalls[0].function.name;
309+ continue;
310+ }
311+ if (!!toolName) {
312+ if (value?.choices?.[0]?.finish_reason === "tool_calls") {
313+ // If final assistant message has "tool_calls" as finish_reason
314+ let args: string | undefined;
315+ try {
316+ accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments;
317+ // Check if accumulated argument chunks are parsable
318+ args = JSON.stringify(JSON.parse(accumulatedArgs));
319+ } catch (e) {
320+ // Otherwise use arguments from final assistant tool call message
321+ args = chunk.toolCalls?.[0]?.function?.arguments;
322+ }
323+ const toolCall = {
324+ function: { name: toolName, arguments: args },
325+ id: toolCallId,
326+ };
327+ chunk.toolCalls = [toolCall as ToolCallDelta];
328+ } else {
329+ if (!!chunk.toolCalls?.[0]?.function?.arguments)
330+ accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments;
331+ continue;
332+ }
333+ }
334+ yield chunk;
335+ } else {
336+ yield message;
337+ }
298338 }
299339 }
300340 }
modified core/llm/llms/index.ts +13 −8
@@ -1,3 +1,4 @@
1+import Handlebars from "handlebars";
12 import {
23 BaseCompletionOptions,
34 IdeSettings,
@@ -6,10 +7,8 @@
67 JSONModelDescription,
78 LLMOptions,
89 } from "../..";
9-import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
10-import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
10+import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
1111 import { BaseLLM } from "../index";
12-
1312 import Anthropic from "./Anthropic";
1413 import Asksage from "./Asksage";
1514 import Azure from "./Azure";
@@ -33,6 +32,7 @@
3332 import Kindo from "./Kindo";
3433 import LlamaCpp from "./LlamaCpp";
3534 import Llamafile from "./Llamafile";
35+import LlamaStack from "./LlamaStack";
3636 import LMStudio from "./LMStudio";
3737 import Mistral from "./Mistral";
3838 import MockLLM from "./Mock";
@@ -62,7 +62,6 @@
6262 import Voyage from "./Voyage";
6363 import WatsonX from "./WatsonX";
6464 import xAI from "./xAI";
65-
6665 export const LLMClasses = [
6766 Anthropic,
6867 Cohere,
@@ -116,11 +115,13 @@
116115 Relace,
117116 Inception,
118117 Voyage,
118+ LlamaStack,
119119 ];
120120
121121 export async function llmFromDescription(
122122 desc: JSONModelDescription,
123123 readFile: (filepath: string) => Promise<string>,
124+ getUriFromPath: (path: string) => Promise<string | undefined>,
124125 uniqueId: string,
125126 ideSettings: IdeSettings,
126127 llmLogger: ILLMLogger,
@@ -139,12 +140,15 @@
139140
140141 let baseChatSystemMessage: string | undefined = undefined;
141142 if (desc.systemMessage !== undefined) {
142- baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
143- baseChatSystemMessage += "\n\n";
144- baseChatSystemMessage += await renderTemplatedString(
143+ // baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
144+ // baseChatSystemMessage += "\n\n";
145+ baseChatSystemMessage = await renderTemplatedString(
146+ Handlebars,
145147 desc.systemMessage,
146- readFile,
147148 {},
149+ [],
150+ readFile,
151+ getUriFromPath,
148152 );
149153 }
150154
@@ -158,6 +162,7 @@
158162 cls.defaultOptions?.completionOptions?.maxTokens,
159163 },
160164 baseChatSystemMessage,
165+ basePlanSystemMessage: baseChatSystemMessage,
161166 baseAgentSystemMessage: baseChatSystemMessage,
162167 logger: llmLogger,
163168 uniqueId,
modified core/llm/llms/stubs/ContinueProxy.ts +17 −4
@@ -40,6 +40,7 @@
4040 this.apiType = undefined;
4141 this.actualApiBase = options.apiBase;
4242 this.apiKeyLocation = options.apiKeyLocation;
43+ this.envSecretLocations = options.envSecretLocations;
4344 this.orgScopeId = options.orgScopeId;
4445 this.onPremProxyUrl = options.onPremProxyUrl;
4546 if (this.onPremProxyUrl) {
@@ -60,6 +61,7 @@
6061 protected extraBodyProperties(): Record<string, any> {
6162 const continueProperties: ContinueProperties = {
6263 apiKeyLocation: this.apiKeyLocation,
64+ envSecretLocations: this.envSecretLocations,
6365 apiBase: this.actualApiBase,
6466 orgScopeId: this.orgScopeId ?? null,
6567 env: this.configEnv,
@@ -70,13 +72,24 @@
7072 }
7173
7274 getConfigurationStatus() {
73- if (!this.apiKeyLocation) {
75+ if (!this.apiKeyLocation && !this.envSecretLocations) {
7476 return LLMConfigurationStatuses.VALID;
7577 }
7678
77- const secretLocation = decodeSecretLocation(this.apiKeyLocation);
78- if (secretLocation.secretType === SecretType.NotFound) {
79- return LLMConfigurationStatuses.MISSING_API_KEY;
79+ if (this.apiKeyLocation) {
80+ const secretLocation = decodeSecretLocation(this.apiKeyLocation);
81+ if (secretLocation.secretType === SecretType.NotFound) {
82+ return LLMConfigurationStatuses.MISSING_API_KEY;
83+ }
84+ }
85+
86+ if (this.envSecretLocations) {
87+ for (const secretLocation of Object.values(this.envSecretLocations)) {
88+ const decoded = decodeSecretLocation(secretLocation);
89+ if (decoded.secretType === SecretType.NotFound) {
90+ return LLMConfigurationStatuses.MISSING_ENV_SECRET;
91+ }
92+ }
8093 }
8194
8295 return LLMConfigurationStatuses.VALID;
added core/llm/rules/alwaysApply.vitest.ts +186 −0
@@ -0,0 +1,186 @@
1+import { describe, expect, it } from "vitest";
2+import {
3+ ContextItemId,
4+ ContextItemWithId,
5+ RuleWithSource,
6+ UserChatMessage,
7+} from "../..";
8+import { getApplicableRules } from "./getSystemMessageWithRules";
9+
10+describe("alwaysApply Behavior", () => {
11+ // Common test fixtures
12+ const testFile = "src/app.ts";
13+ const matchingFile = "src/components/Button.tsx";
14+ const nonMatchingFile = "src/utils/helper.js"; // Not matching *.tsx glob
15+
16+ // File context items
17+ const matchingFileContext: ContextItemWithId = {
18+ id: { providerTitle: "file", itemId: "match1" } as ContextItemId,
19+ uri: { type: "file", value: matchingFile },
20+ content: "export const Button = () => {...}",
21+ name: "Button.tsx",
22+ description: "Component file",
23+ };
24+
25+ const nonMatchingFileContext: ContextItemWithId = {
26+ id: { providerTitle: "file", itemId: "nonmatch1" } as ContextItemId,
27+ uri: { type: "file", value: nonMatchingFile },
28+ content: "export const helper = () => {...}",
29+ name: "helper.js",
30+ description: "Helper file",
31+ };
32+
33+ // Message with no file references
34+ const messageWithoutFile: UserChatMessage = {
35+ role: "user",
36+ content: "Can you help me understand how this works?",
37+ };
38+
39+ it("alwaysApply: true - Always include the rule, regardless of file context", () => {
40+ // Rule with alwaysApply: true
41+ const alwaysApplyRule: RuleWithSource = {
42+ name: "Always Apply Rule",
43+ rule: "This rule should always be applied",
44+ alwaysApply: true,
45+ globs: "**/*.tsx", // Should be ignored since alwaysApply is true
46+ source: "rules-block",
47+ ruleFile: ".continue/rules.md",
48+ };
49+
50+ // Test with no file context
51+ let applicableRules = getApplicableRules(
52+ messageWithoutFile,
53+ [alwaysApplyRule],
54+ [],
55+ );
56+ expect(applicableRules).toHaveLength(1);
57+ expect(applicableRules[0].name).toBe("Always Apply Rule");
58+
59+ // Test with matching file
60+ applicableRules = getApplicableRules(
61+ undefined,
62+ [alwaysApplyRule],
63+ [matchingFileContext],
64+ );
65+ expect(applicableRules).toHaveLength(1);
66+ expect(applicableRules[0].name).toBe("Always Apply Rule");
67+
68+ // Test with non-matching file
69+ applicableRules = getApplicableRules(
70+ undefined,
71+ [alwaysApplyRule],
72+ [nonMatchingFileContext],
73+ );
74+ expect(applicableRules).toHaveLength(1);
75+ expect(applicableRules[0].name).toBe("Always Apply Rule");
76+ });
77+
78+ it("alwaysApply: false - Only include if globs exist AND match file context", () => {
79+ // Rule with alwaysApply: false and globs
80+ const conditionalRule: RuleWithSource = {
81+ name: "Conditional Rule",
82+ rule: "Apply only to matching files",
83+ alwaysApply: false,
84+ globs: "**/*.tsx",
85+ source: "rules-block",
86+ ruleFile: ".continue/rules.md",
87+ };
88+
89+ // Rule with alwaysApply: false and no globs
90+ const neverApplyRule: RuleWithSource = {
91+ name: "Never Apply Rule",
92+ rule: "This rule should never apply",
93+ alwaysApply: false,
94+ // No globs
95+ source: "rules-block",
96+ ruleFile: ".continue/rules.md",
97+ };
98+
99+ // Test with no file context
100+ let applicableRules = getApplicableRules(
101+ messageWithoutFile,
102+ [conditionalRule, neverApplyRule],
103+ [],
104+ );
105+ expect(applicableRules).toHaveLength(0); // No rules should apply
106+
107+ // Test with matching file
108+ applicableRules = getApplicableRules(
109+ undefined,
110+ [conditionalRule, neverApplyRule],
111+ [matchingFileContext],
112+ );
113+ expect(applicableRules).toHaveLength(1);
114+ expect(applicableRules[0].name).toBe("Conditional Rule");
115+ expect(applicableRules.map((r) => r.name)).not.toContain(
116+ "Never Apply Rule",
117+ );
118+
119+ // Test with non-matching file
120+ applicableRules = getApplicableRules(
121+ undefined,
122+ [conditionalRule, neverApplyRule],
123+ [nonMatchingFileContext],
124+ );
125+ expect(applicableRules).toHaveLength(0); // No rules should apply
126+ });
127+
128+ it("alwaysApply: undefined - Default behavior: include if no globs exist OR globs exist and match", () => {
129+ // Rule with undefined alwaysApply and no globs (should behave like a global rule)
130+ const defaultNoGlobsRule: RuleWithSource = {
131+ name: "Default No Globs Rule",
132+ rule: "Default rule with no globs",
133+ source: "rules-block",
134+ ruleFile: ".continue/rules.md",
135+ // No alwaysApply, no globs
136+ };
137+
138+ // Rule with undefined alwaysApply and globs
139+ const defaultWithGlobsRule: RuleWithSource = {
140+ name: "Default With Globs Rule",
141+ rule: "Default rule with globs",
142+ globs: "**/*.tsx",
143+ source: "rules-block",
144+ ruleFile: ".continue/rules.md",
145+ // No alwaysApply, with globs
146+ };
147+
148+ // Test with no file context
149+ let applicableRules = getApplicableRules(
150+ messageWithoutFile,
151+ [defaultNoGlobsRule, defaultWithGlobsRule],
152+ [],
153+ );
154+ expect(applicableRules).toHaveLength(1);
155+ expect(applicableRules[0].name).toBe("Default No Globs Rule");
156+ expect(applicableRules.map((r) => r.name)).not.toContain(
157+ "Default With Globs Rule",
158+ );
159+
160+ // Test with matching file
161+ applicableRules = getApplicableRules(
162+ undefined,
163+ [defaultNoGlobsRule, defaultWithGlobsRule],
164+ [matchingFileContext],
165+ );
166+ expect(applicableRules).toHaveLength(2);
167+ expect(applicableRules.map((r) => r.name)).toContain(
168+ "Default No Globs Rule",
169+ );
170+ expect(applicableRules.map((r) => r.name)).toContain(
171+ "Default With Globs Rule",
172+ );
173+
174+ // Test with non-matching file
175+ applicableRules = getApplicableRules(
176+ undefined,
177+ [defaultNoGlobsRule, defaultWithGlobsRule],
178+ [nonMatchingFileContext],
179+ );
180+ expect(applicableRules).toHaveLength(1);
181+ expect(applicableRules[0].name).toBe("Default No Globs Rule");
182+ expect(applicableRules.map((r) => r.name)).not.toContain(
183+ "Default With Globs Rule",
184+ );
185+ });
186+});
modified core/llm/rules/alwaysApplyRules.vitest.ts +35 −0
@@ -6,6 +6,7 @@
66 UserChatMessage,
77 } from "../..";
88 import { getApplicableRules } from "./getSystemMessageWithRules";
9+import { RulePolicies } from "./types";
910
1011 describe("Rule application with alwaysApply", () => {
1112 // Create an always-apply rule
@@ -136,4 +137,38 @@
136137 expect(applicableRules).toHaveLength(1);
137138 expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
138139 });
140+
141+ it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => {
142+ // Rule with alwaysApply: true
143+ const globalRule: RuleWithSource = {
144+ name: "Global Rule",
145+ rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
146+ alwaysApply: true,
147+ source: "rules-block",
148+ ruleFile: "src/some/path.md",
149+ };
150+
151+ // Message with no code blocks or file references
152+ const simpleMessage: UserChatMessage = {
153+ role: "user",
154+ content: "Can you help me with something?",
155+ };
156+
157+ // Create a rule policy that blocks the rule
158+ const rulePolicies: RulePolicies = {
159+ "Global Rule": "off",
160+ };
161+
162+ // The rule should NOT be applied due to the "off" policy,
163+ // even though it has alwaysApply: true and there are no file paths
164+ const applicableRules = getApplicableRules(
165+ simpleMessage,
166+ [globalRule],
167+ [],
168+ rulePolicies,
169+ );
170+
171+ expect(applicableRules).toHaveLength(0);
172+ expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule");
173+ });
139174 });
modified core/llm/rules/getSystemMessageWithRules.ts +171 −63
@@ -7,7 +7,9 @@
77 } from "../..";
88 import { renderChatMessage } from "../../util/messageContent";
99 import { getCleanUriPath } from "../../util/uri";
10+import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
1011 import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
12+import { RulePolicies } from "./types";
1113
1214 /**
1315 * Checks if a path matches any of the provided globs
@@ -51,6 +53,47 @@
5153 return false;
5254 };
5355
56+/**
57+ * Checks if file content matches any of the provided regex regex
58+ *
59+ * @param fileContent - The content of the file to check
60+ * @param regex - A single regex pattern string or array of regex pattern strings
61+ * @returns true if the content matches any pattern (or if no regex is provided), false otherwise
62+ */
63+const contentMatchesRegex = (
64+ fileContent: string,
65+ regex: string | string[],
66+): boolean => {
67+ // Handle single string pattern
68+ if (typeof regex === "string") {
69+ try {
70+ const expression = new RegExp(regex);
71+ return expression.test(fileContent);
72+ } catch (e) {
73+ console.error(`Invalid regex pattern: ${regex}`, e);
74+ return false;
75+ }
76+ }
77+
78+ // Handle array of regex
79+ if (Array.isArray(regex)) {
80+ if (regex.length === 0) return true;
81+
82+ // Content must match at least one pattern
83+ return regex.some((pattern) => {
84+ try {
85+ const regex = new RegExp(pattern);
86+ return regex.test(fileContent);
87+ } catch (e) {
88+ console.error(`Invalid regex pattern: ${pattern}`, e);
89+ return false;
90+ }
91+ });
92+ }
93+
94+ return false;
95+};
96+
5497 /**
5598 * Determines if a file path is within a specific directory or its subdirectories
5699 *
@@ -102,31 +145,81 @@
102145 return true;
103146 }
104147
105- // Root-level rules with no globs are implicitly global
106- if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
148+ // Root-level rules with no globs or regex are implicitly global
149+ if (
150+ isRootLevelRule(rule) &&
151+ !rule.globs &&
152+ !rule.regex &&
153+ rule.alwaysApply !== false
154+ ) {
107155 return true;
108156 }
109157
110158 return false;
111159 };
112160
161+const checkGlobsAndRegex = ({
162+ rule,
163+ filePaths,
164+ fileContents,
165+}: {
166+ rule: RuleWithSource;
167+ filePaths: string[];
168+ fileContents: Record<string, string>;
169+}) => {
170+ const matchingFiles = rule.globs
171+ ? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
172+ : filePaths;
173+
174+ // If no files match the globs, don't apply the rule
175+ if (matchingFiles.length === 0) {
176+ return false;
177+ }
178+
179+ // Now check for pattern matches in file contents if regex are specified
180+ if (rule.regex) {
181+ // Check if any of the matching files also match the content regex
182+ return matchingFiles.some((filePath) => {
183+ const content = fileContents[filePath];
184+ // If we don't have the content, we can't check regex
185+ if (!content) return false;
186+ return contentMatchesRegex(content, rule.regex!);
187+ });
188+ }
189+
190+ // If we have no regex or if we couldn't check regex (no content),
191+ // just go with the glob matches
192+ return matchingFiles.length > 0;
193+};
194+
113195 /**
114- * Determines if a rule should be applied based on its alwaysApply property and file path matching
196+ * Determines if a rule should be applied based on its properties and file matching
115197 *
116198 * @param rule - The rule to check
117199 * @param filePaths - Array of file paths to check against the rule's globs
200+ * @param fileContents - Map of file paths to their contents for pattern matching
201+ * @param rulePolicies - Optional policies that can override normal rule behavior
118202 * @returns true if the rule should be applied, false otherwise
119203 */
120204 export const shouldApplyRule = (
121205 rule: RuleWithSource,
122206 filePaths: string[],
207+ rulePolicies: RulePolicies = {},
208+ fileContents: Record<string, string> = {},
123209 ): boolean => {
210+ const policy = rulePolicies[rule.name || ""];
211+
212+ // Never apply if policy is "off"
213+ if (policy === "off") {
214+ return false;
215+ }
216+
124217 // If it's a global rule, always apply it regardless of file paths
125218 if (isGlobalRule(rule)) {
126219 return true;
127220 }
128221
129- // If there are no file paths to check:
222+ // If there are no file paths to check and we've made it here:
130223 // - We've already handled global rules above
131224 // - Don't apply other rules since we have no files to match against
132225 if (filePaths.length === 0) {
@@ -148,40 +241,27 @@
148241 isFileInDirectory(filePath, ruleDirPath),
149242 );
150243
151- // If no files are in this directory, don't apply the rule
152- if (filesInRuleDirectory.length === 0) {
153- return false;
154- }
155-
156- // If we have globs, check if any files in this directory match them
157- if (rule.globs) {
158- return filesInRuleDirectory.some((filePath) =>
159- matchesGlobs(filePath, rule.globs),
160- );
161- }
162-
163- // No globs but files are in this directory, so apply the rule
164- return true;
165- }
166-
167- // For root-level rules:
168-
169- // If alwaysApply is explicitly false, only apply if there are globs AND they match
170- if (rule.alwaysApply === false) {
171- if (!rule.globs) {
172- return false;
173- }
174- return filePaths.some((path) => matchesGlobs(path, rule.globs));
244+ return checkGlobsAndRegex({
245+ filePaths: filesInRuleDirectory,
246+ fileContents,
247+ rule,
248+ });
175249 }
176250
177- // Default behavior for root rules with globs:
178- // - Only apply if they match the globs
179- if (rule.globs) {
180- return filePaths.some((path) => matchesGlobs(path, rule.globs));
251+ // If alwaysApply is explicitly false, we need to check globs and/or regex
252+ if (
253+ rule.alwaysApply === false &&
254+ rule.globs === undefined &&
255+ rule.regex === undefined
256+ ) {
257+ return false;
181258 }
182259
183- // This point should not be reached as we've handled all cases above
184- return false;
260+ return checkGlobsAndRegex({
261+ filePaths,
262+ fileContents,
263+ rule,
264+ });
185265 };
186266
187267 /**
@@ -196,11 +276,9 @@
196276 userMessage: UserChatMessage | ToolResultChatMessage | undefined,
197277 rules: RuleWithSource[],
198278 contextItems: ContextItemWithId[],
279+ rulePolicies: RulePolicies = {},
199280 ): RuleWithSource[] => {
200- // First, extract any global rules that should always apply
201- const globalRules = rules.filter((rule) => isGlobalRule(rule));
202-
203- // Get file paths from message and context for regular rule matching
281+ // Get file paths from message and context for rule matching
204282 const filePathsFromMessage = userMessage
205283 ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
206284 : [];
@@ -213,46 +291,76 @@
213291 // Combine file paths from both sources
214292 const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
215293
216- // If we have no file paths, just return the global rules
217- if (allFilePaths.length === 0) {
218- return globalRules;
294+ // Create a map of file paths to their contents for pattern matching
295+ const fileContents: Record<string, string> = {};
296+
297+ // Extract contents from context items with file URIs
298+ contextItems.forEach((item) => {
299+ if (item.uri?.type === "file" && item.uri?.value) {
300+ fileContents[item.uri.value] = item.content;
301+ }
302+ });
303+
304+ // Extract contents from code blocks in the message for paths that don't have content yet
305+ if (userMessage) {
306+ const messageContent = renderChatMessage(userMessage);
307+ filePathsFromMessage.forEach((path) => {
308+ // Only extract content if we don't already have it from context items
309+ if (!fileContents[path]) {
310+ const blockContent = extractContentFromCodeBlock(messageContent, path);
311+ if (blockContent) {
312+ fileContents[path] = blockContent;
313+ }
314+ }
315+ });
219316 }
220317
221- // Get rules that match file paths
222- const matchingRules = rules
223- .filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them
224- .filter((rule) => shouldApplyRule(rule, allFilePaths));
318+ // Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
319+ // and path matching in a consistent way
320+ const applicableRules = rules.filter((rule) =>
321+ shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
322+ );
225323
226- // Combine global rules with matching rules, ensuring no duplicates
227- return [...globalRules, ...matchingRules];
324+ return applicableRules;
228325 };
229326
230-/**
231- * Creates a system message string with applicable rules appended
232- *
233- * @param baseSystemMessage - The base system message to start with
234- * @param userMessage - The user message to check for file paths
235- * @param rules - The list of rules to filter
236- * @param contextItems - Context items to check for file paths
237- * @returns System message with applicable rules appended
238- */
327+export function getRuleId(rule: RuleWithSource): string {
328+ return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
329+}
330+
239331 export const getSystemMessageWithRules = ({
240332 baseSystemMessage,
241333 userMessage,
242- rules,
334+ availableRules,
243335 contextItems,
336+ rulePolicies = {},
244337 }: {
245338 baseSystemMessage?: string;
246339 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
247- rules: RuleWithSource[];
340+ availableRules: RuleWithSource[];
248341 contextItems: ContextItemWithId[];
249-}) => {
250- const applicableRules = getApplicableRules(userMessage, rules, contextItems);
342+ rulePolicies?: RulePolicies;
343+}): {
344+ systemMessage: string;
345+ appliedRules: RuleWithSource[];
346+} => {
347+ const appliedRules = getApplicableRules(
348+ userMessage,
349+ availableRules,
350+ contextItems,
351+ rulePolicies,
352+ );
251353 let systemMessage = baseSystemMessage ?? "";
252354
253- for (const rule of applicableRules) {
254- systemMessage += `\n\n${rule.rule}`;
355+ for (const rule of appliedRules) {
356+ if (systemMessage) {
357+ systemMessage += "\n\n";
358+ }
359+ systemMessage += rule.rule;
255360 }
256361
257- return systemMessage;
362+ return {
363+ systemMessage,
364+ appliedRules,
365+ };
258366 };
modified core/llm/rules/getSystemMessageWithRules.vitest.ts +347 −2
@@ -1,6 +1,15 @@
11 import { describe, expect, it } from "vitest";
2-import { RuleWithSource } from "../..";
3-import { shouldApplyRule } from "./getSystemMessageWithRules";
2+import {
3+ ContextItemId,
4+ ContextItemWithId,
5+ RuleWithSource,
6+ UserChatMessage,
7+} from "../..";
8+import {
9+ getApplicableRules,
10+ shouldApplyRule,
11+} from "./getSystemMessageWithRules";
12+import { RulePolicies } from "./types";
413
514 describe("Rule colocation glob matching", () => {
615 // This test file demonstrates the expected behavior after our fix
@@ -132,3 +141,339 @@
132141 );
133142 });
134143 });
144+
145+describe("Rule policies", () => {
146+ const componentRule: RuleWithSource = {
147+ name: "Components Rule",
148+ rule: "Use functional components with hooks",
149+ source: "rules-block",
150+ ruleFile: "src/components/rules.md",
151+ };
152+
153+ const testFiles = ["src/components/Button.tsx"];
154+ const nonMatchingFiles = ["src/utils/helpers.ts"];
155+
156+ it("should never apply rules with 'off' policy regardless of file paths", () => {
157+ const rulePolicies: RulePolicies = {
158+ "Components Rule": "off",
159+ };
160+
161+ // Should not apply even to matching files
162+ expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false);
163+
164+ // Rule with alwaysApply: true should still be overridden by 'off' policy
165+ const alwaysApplyRule: RuleWithSource = {
166+ name: "Always Apply Rule",
167+ rule: "This rule would normally always apply",
168+ alwaysApply: true,
169+ source: "rules-block",
170+ ruleFile: "src/components/rules.md",
171+ };
172+
173+ const offPolicies: RulePolicies = {
174+ "Always Apply Rule": "off",
175+ };
176+
177+ expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe(
178+ false,
179+ );
180+ });
181+
182+ it("should apply 'on' policy rules based on normal matching logic", () => {
183+ const rulePolicies: RulePolicies = {
184+ "Components Rule": "on",
185+ };
186+
187+ // Should apply to matching files
188+ expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
189+
190+ // Should not apply to non-matching files
191+ expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
192+ false,
193+ );
194+ });
195+
196+ it("should use default behavior when no policy is specified", () => {
197+ // Empty policies object should use default behavior
198+ const rulePolicies: RulePolicies = {};
199+
200+ // Should apply to matching files
201+ expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
202+
203+ // Should not apply to non-matching files
204+ expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
205+ false,
206+ );
207+ });
208+
209+ it("should handle policy interaction with global rules", () => {
210+ // Root level rule which would normally apply globally
211+ const rootRule: RuleWithSource = {
212+ name: "Root Rule",
213+ rule: "Follow project standards",
214+ source: "rules-block",
215+ ruleFile: ".continue/rules.md",
216+ };
217+
218+ // Off policy should override even global rules
219+ const offPolicies: RulePolicies = {
220+ "Root Rule": "off",
221+ };
222+
223+ expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false);
224+
225+ // On policy should maintain global rule behavior
226+ const onPolicies: RulePolicies = {
227+ "Root Rule": "on",
228+ };
229+
230+ expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true);
231+ });
232+
233+ it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => {
234+ // Create rule with multiple matching criteria
235+ const complexRule: RuleWithSource = {
236+ name: "Complex Rule",
237+ rule: "This rule has complex matching logic",
238+ alwaysApply: true,
239+ globs: "**/*.ts",
240+ source: "rules-block",
241+ ruleFile: "src/utils/rules.md",
242+ };
243+
244+ // Off policy should win over everything
245+ const offPolicies: RulePolicies = {
246+ "Complex Rule": "off",
247+ };
248+
249+ // Even with matching files and alwaysApply: true, off policy wins
250+ expect(
251+ shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies),
252+ ).toBe(false);
253+ });
254+});
255+
256+describe("Content pattern matching", () => {
257+ it("should apply rules when file content matches pattern", () => {
258+ // Rule with pattern to match React component files
259+ const reactComponentRule: RuleWithSource = {
260+ name: "React Component Rule",
261+ rule: "Follow React component standards",
262+ regex: "export (function|const) \\w+.*\\(",
263+ source: "rules-block",
264+ ruleFile: "src/components/rules.md",
265+ };
266+
267+ // File that matches the pattern
268+ const filePath = "src/components/Button.tsx";
269+ const fileContents = {
270+ [filePath]:
271+ "export function Button() { return <button>Click me</button> }",
272+ };
273+
274+ expect(
275+ shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
276+ ).toBe(true);
277+
278+ // File that doesn't match the pattern
279+ const nonMatchingContents = {
280+ [filePath]:
281+ "import React from 'react'; // Just an import, not a component",
282+ };
283+
284+ expect(
285+ shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
286+ ).toBe(false);
287+ });
288+
289+ it("should support multiple regex regex as an array", () => {
290+ // Rule with multiple regex
291+ const multiPatternRule: RuleWithSource = {
292+ name: "Multi-Pattern Rule",
293+ rule: "Apply to functions or classes",
294+ regex: ["function\\s+\\w+", "class\\s+\\w+"],
295+ source: "rules-block",
296+ ruleFile: "src/utils/rules.md",
297+ };
298+
299+ const filePath = "src/utils/helper.ts";
300+
301+ // Content with function - should match
302+ const functionContent = {
303+ [filePath]: "function formatDate(date) { return date.toISOString(); }",
304+ };
305+ expect(
306+ shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
307+ ).toBe(true);
308+
309+ // Content with class - should match
310+ const classContent = {
311+ [filePath]:
312+ "class DateFormatter { format(date) { return date.toISOString(); } }",
313+ };
314+ expect(
315+ shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
316+ ).toBe(true);
317+
318+ // Content with neither - should not match
319+ const nonMatchingContent = {
320+ [filePath]: "const PI = 3.14159;",
321+ };
322+ expect(
323+ shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
324+ ).toBe(false);
325+ });
326+
327+ it("should apply rules based on both globs and regex when both are specified", () => {
328+ // Rule with both glob and pattern restrictions
329+ const typescriptClassRule: RuleWithSource = {
330+ name: "TypeScript Class Rule",
331+ rule: "Follow class standards in TypeScript",
332+ globs: "**/*.ts",
333+ regex: "class\\s+\\w+",
334+ source: "rules-block",
335+ ruleFile: "src/models/rules.md",
336+ };
337+
338+ const tsFilePath = "src/models/User.ts";
339+ const jsFilePath = "src/models/Product.js";
340+
341+ // TypeScript file with class - should match
342+ const tsClassContent = {
343+ [tsFilePath]: "export class User { constructor(public name: string) {} }",
344+ };
345+ expect(
346+ shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
347+ ).toBe(true);
348+
349+ // TypeScript file without class - should not match
350+ const tsNonClassContent = {
351+ [tsFilePath]: "export const createUser = (name: string) => ({ name });",
352+ };
353+ expect(
354+ shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
355+ ).toBe(false);
356+
357+ // JavaScript file with class - should not match due to glob
358+ const jsClassContent = {
359+ [jsFilePath]:
360+ "export class Product { constructor(name) { this.name = name; } }",
361+ };
362+ expect(
363+ shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
364+ ).toBe(false);
365+ });
366+
367+ it("should extract file content from messages for pattern matching", () => {
368+ // Rule with pattern
369+ const arrowFunctionRule: RuleWithSource = {
370+ name: "Arrow Function Rule",
371+ rule: "Use arrow functions for better this binding",
372+ regex: "const\\s+\\w+\\s*=\\s*\\(",
373+ source: "rules-block",
374+ ruleFile: "src/utils/rules.md",
375+ };
376+
377+ // Message with code block containing a matching pattern
378+ const messageWithArrowFn: UserChatMessage = {
379+ role: "user",
380+ content:
381+ "Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
382+ };
383+
384+ // Create context item to match the file in the message
385+ const contextItem: ContextItemWithId = {
386+ id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
387+ uri: { type: "file", value: "src/utils/formatter.ts" },
388+ content: "const format = (date) => {\n return date.toISOString();\n};",
389+ name: "formatter.ts",
390+ description: "Utility formatter",
391+ };
392+
393+ // Should match the pattern
394+ const applicableRules = getApplicableRules(
395+ messageWithArrowFn,
396+ [arrowFunctionRule],
397+ [contextItem],
398+ );
399+
400+ expect(applicableRules).toHaveLength(1);
401+ expect(applicableRules[0].name).toBe("Arrow Function Rule");
402+
403+ // Message with code block that doesn't match the pattern
404+ const messageWithoutArrowFn: UserChatMessage = {
405+ role: "user",
406+ content:
407+ "Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
408+ };
409+
410+ // Context item with non-matching content
411+ const nonMatchingContextItem: ContextItemWithId = {
412+ id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
413+ uri: { type: "file", value: "src/utils/formatter.ts" },
414+ content: "function format(date) {\n return date.toISOString();\n}",
415+ name: "formatter.ts",
416+ description: "Utility formatter",
417+ };
418+
419+ // Should not match the pattern
420+ const nonApplicableRules = getApplicableRules(
421+ messageWithoutArrowFn,
422+ [arrowFunctionRule],
423+ [nonMatchingContextItem],
424+ );
425+
426+ expect(nonApplicableRules).toHaveLength(0);
427+ });
428+
429+ it("should handle invalid regex regex gracefully", () => {
430+ // Rule with invalid regex pattern
431+ const invalidRegexRule: RuleWithSource = {
432+ name: "Invalid Regex Rule",
433+ rule: "This rule has an invalid regex pattern",
434+ regex: "([unclosed parenthesis",
435+ source: "rules-block",
436+ ruleFile: "src/utils/rules.md",
437+ };
438+
439+ const filePath = "src/utils/helper.ts";
440+ const fileContents = {
441+ [filePath]: "function helper() { return true; }",
442+ };
443+
444+ // Should not throw an error but gracefully not apply the rule
445+ expect(
446+ shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
447+ ).toBe(false);
448+ });
449+
450+ it("should respect directory restrictions for pattern rules", () => {
451+ // Rule with pattern in a nested directory
452+ const nestedPatternRule: RuleWithSource = {
453+ name: "Nested Pattern Rule",
454+ rule: "Apply only to model files with interfaces",
455+ regex: "interface\\s+\\w+",
456+ source: "rules-block",
457+ ruleFile: "src/models/rules.md",
458+ };
459+
460+ // File in the correct directory with matching content
461+ const modelFilePath = "src/models/User.ts";
462+ const modelContents = {
463+ [modelFilePath]: "export interface User { id: string; name: string; }",
464+ };
465+ expect(
466+ shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
467+ ).toBe(true);
468+
469+ // File outside the directory with matching content - should not match
470+ const utilFilePath = "src/utils/types.ts";
471+ const utilContents = {
472+ [utilFilePath]:
473+ "export interface Config { apiUrl: string; timeout: number; }",
474+ };
475+ expect(
476+ shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
477+ ).toBe(false);
478+ });
479+});
added core/llm/rules/types.ts +2 −0
@@ -0,0 +1,2 @@
1+export type RulePolicy = "on" | "off";
2+export type RulePolicies = { [ruleName: string]: RulePolicy };
deleted core/llm/stream.ts +0 −114
@@ -1,114 +0,0 @@
1-export async function* toAsyncIterable(
2- nodeReadable: NodeJS.ReadableStream,
3-): AsyncGenerator<Uint8Array> {
4- for await (const chunk of nodeReadable) {
5- // @ts-ignore
6- yield chunk as Uint8Array;
7- }
8-}
9-
10-export async function* streamResponse(
11- response: Response,
12-): AsyncGenerator<string> {
13- if (response.status !== 200) {
14- throw new Error(await response.text());
15- }
16-
17- if (!response.body) {
18- throw new Error("No response body returned.");
19- }
20-
21- // Get the major version of Node.js
22- const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
23-
24- if (nodeMajorVersion >= 20) {
25- // Use the new API for Node 20 and above
26- const stream = (ReadableStream as any).from(response.body);
27- for await (const chunk of stream.pipeThrough(
28- new TextDecoderStream("utf-8"),
29- )) {
30- yield chunk;
31- }
32- } else {
33- // Fallback for Node versions below 20
34- // Streaming with this method doesn't work as version 20+ does
35- const decoder = new TextDecoder("utf-8");
36- const nodeStream = response.body as unknown as NodeJS.ReadableStream;
37- for await (const chunk of toAsyncIterable(nodeStream)) {
38- yield decoder.decode(chunk, { stream: true });
39- }
40- }
41-}
42-
43-function parseDataLine(line: string): any {
44- const json = line.startsWith("data: ")
45- ? line.slice("data: ".length)
46- : line.slice("data:".length);
47-
48- try {
49- const data = JSON.parse(json);
50- if (data.error) {
51- throw new Error(`Error streaming response: ${data.error}`);
52- }
53-
54- return data;
55- } catch (e) {
56- throw new Error(`Malformed JSON sent from server: ${json}`);
57- }
58-}
59-
60-function parseSseLine(line: string): { done: boolean; data: any } {
61- if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
62- return { done: true, data: undefined };
63- }
64- if (line.startsWith("data:")) {
65- return { done: false, data: parseDataLine(line) };
66- }
67- if (line.startsWith(": ping")) {
68- return { done: true, data: undefined };
69- }
70- return { done: false, data: undefined };
71-}
72-
73-export async function* streamSse(response: Response): AsyncGenerator<any> {
74- let buffer = "";
75- for await (const value of streamResponse(response)) {
76- buffer += value;
77-
78- let position: number;
79- while ((position = buffer.indexOf("\n")) >= 0) {
80- const line = buffer.slice(0, position);
81- buffer = buffer.slice(position + 1);
82-
83- const { done, data } = parseSseLine(line);
84- if (done) {
85- break;
86- }
87- if (data) {
88- yield data;
89- }
90- }
91- }
92-
93- if (buffer.length > 0) {
94- const { done, data } = parseSseLine(buffer);
95- if (!done && data) {
96- yield data;
97- }
98- }
99-}
100-
101-export async function* streamJSON(response: Response): AsyncGenerator<any> {
102- let buffer = "";
103- for await (const value of streamResponse(response)) {
104- buffer += value;
105-
106- let position;
107- while ((position = buffer.indexOf("\n")) >= 0) {
108- const line = buffer.slice(0, position);
109- const data = JSON.parse(line);
110- yield data;
111- buffer = buffer.slice(position + 1);
112- }
113- }
114-}
modified core/llm/streamChat.ts +7 −0
@@ -59,6 +59,12 @@
5959 },
6060 true,
6161 );
62+ if (!slashCommand.run) {
63+ console.error(
64+ `Slash command ${command.name} (${command.source}) has no run function`,
65+ );
66+ throw new Error(`Slash command not found`);
67+ }
6268
6369 const gen = slashCommand.run({
6470 input,
@@ -85,6 +91,7 @@
8591 config.requestOptions,
8692 ),
8793 completionOptions,
94+ abortController,
8895 });
8996 let next = await gen.next();
9097 while (!next.done) {
modified core/llm/toolSupport.test.ts +14 −0
@@ -109,6 +109,19 @@
109109 });
110110 });
111111
112+ describe("cohere", () => {
113+ const supportsFn = PROVIDER_TOOL_SUPPORT["cohere"];
114+
115+ it("should return true for Command models", () => {
116+ expect(supportsFn("command-r")).toBe(true);
117+ expect(supportsFn("command-a")).toBe(true);
118+ });
119+
120+ it("should return false for other models", () => {
121+ expect(supportsFn("c4ai-aya-expanse-32b")).toBe(false);
122+ });
123+ });
124+
112125 describe("gemini", () => {
113126 const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"];
114127
@@ -221,6 +234,7 @@
221234 expect(supportsFn("qwen2")).toBe(true);
222235 expect(supportsFn("mixtral-8x7b")).toBe(true);
223236 expect(supportsFn("command-r")).toBe(true);
237+ expect(supportsFn("command-a")).toBe(true);
224238 expect(supportsFn("smollm2")).toBe(true);
225239 expect(supportsFn("hermes3")).toBe(true);
226240 expect(supportsFn("athene-v2")).toBe(true);
modified core/llm/toolSupport.ts +22 −7
@@ -19,9 +19,11 @@
1919 "claude-3-7",
2020 "claude-3.7",
2121 "claude-sonnet-4",
22+ "claude-4-sonnet",
2223 "gpt-4",
2324 "o3",
2425 "gemini",
26+ "claude-opus-4",
2527 ].some((part) => model.toLowerCase().startsWith(part));
2628 },
2729 anthropic: (model) => {
@@ -32,6 +34,8 @@
3234 "claude-3-7",
3335 "claude-3.7",
3436 "claude-sonnet-4",
37+ "claude-4-sonnet",
38+ "claude-opus-4",
3539 ].some((part) => model.toLowerCase().startsWith(part))
3640 ) {
3741 return true;
@@ -71,6 +75,9 @@
7175
7276 return false;
7377 },
78+ cohere: (model) => {
79+ return model.toLowerCase().startsWith("command");
80+ },
7481 gemini: (model) => {
7582 // All gemini models support function calling
7683 return model.toLowerCase().includes("gemini");
@@ -83,15 +90,19 @@
8390 );
8491 },
8592 bedrock: (model) => {
86- // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
8793 if (
88- model.toLowerCase().includes("sonnet") &&
8994 [
90- "claude-3-5",
91- "claude-3.5",
92- "claude-3-7",
93- "claude-3.7",
95+ "claude-3-5-sonnet",
96+ "claude-3.5-sonnet",
97+ "claude-3-7-sonnet",
98+ "claude-3.7-sonnet",
9499 "claude-sonnet-4",
100+ "claude-4-sonnet",
101+ "claude-opus-4",
102+ "nova-lite",
103+ "nova-pro",
104+ "nova-micro",
105+ "nova-premier",
95106 ].some((part) => model.toLowerCase().includes(part))
96107 ) {
97108 return true;
@@ -144,6 +155,7 @@
144155 "qwen3",
145156 "mixtral",
146157 "command-r",
158+ "command-a",
147159 "smollm2",
148160 "hermes3",
149161 "athene-v2",
@@ -175,7 +187,9 @@
175187 return false;
176188 },
177189 deepseek: (model) => {
178- if (model !== "deepseek-reasoner") {
190+ // https://api-docs.deepseek.com/quick_start/pricing
191+ // https://api-docs.deepseek.com/guides/function_calling
192+ if (model === "deepseek-reasoner" || model === "deepseek-chat") {
179193 return true;
180194 }
181195
@@ -226,6 +240,7 @@
226240 "qwen/qwen3",
227241 "qwen/qwen-",
228242 "cohere/command-r",
243+ "cohere/command-a",
229244 "ai21/jamba-1.6",
230245 "mistralai/mistral",
231246 "mistralai/ministral",
added core/llm/utils/extractContentFromCodeBlocks.test.ts +94 −0
@@ -0,0 +1,94 @@
1+import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
2+
3+describe("extractContentFromCodeBlock", () => {
4+ it("should extract content from code block with language and filepath", () => {
5+ const content = "```typescript src/main.ts\nconst x = 1;\n```";
6+ expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
7+ "const x = 1;",
8+ );
9+ });
10+
11+ it("should extract content from code block with filepath only (no language)", () => {
12+ const content = "```test.js\nclass Calculator { }\n```";
13+ expect(extractContentFromCodeBlock(content, "test.js")).toBe(
14+ "class Calculator { }",
15+ );
16+ });
17+
18+ it("should extract content from code block with line ranges", () => {
19+ const content = "```js test.js (19-25)\nfunction test() {}\n```";
20+ expect(extractContentFromCodeBlock(content, "test.js")).toBe(
21+ "function test() {}",
22+ );
23+ });
24+
25+ it("should handle multiple code blocks and find the right one", () => {
26+ const content =
27+ "```typescript src/main.ts\nconst x = 1;\n```\n" +
28+ "```test.js\nclass Calculator { }\n```\n" +
29+ "```js utils.js (19-25)\nfunction test() {}\n```";
30+
31+ expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
32+ "const x = 1;",
33+ );
34+ expect(extractContentFromCodeBlock(content, "test.js")).toBe(
35+ "class Calculator { }",
36+ );
37+ expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
38+ "function test() {}",
39+ );
40+ });
41+
42+ it("should handle paths with special regex characters", () => {
43+ const content =
44+ "```typescript src/special+chars.ts[123]\nconst special = true;\n```";
45+ expect(
46+ extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
47+ ).toBe("const special = true;");
48+ });
49+
50+ it("should handle multiline content", () => {
51+ const content =
52+ "```typescript src/multi-line.ts\n" +
53+ "function example() {\n" +
54+ " const x = 1;\n" +
55+ " return x + 2;\n" +
56+ "}\n" +
57+ "```";
58+
59+ const expected =
60+ "function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
61+
62+ expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
63+ expected,
64+ );
65+ });
66+
67+ it("should return undefined when path doesn't exist in any code block", () => {
68+ const content = "```typescript src/main.ts\nconst x = 1;\n```";
69+ expect(
70+ extractContentFromCodeBlock(content, "nonexistent.ts"),
71+ ).toBeUndefined();
72+ });
73+
74+ it("should extract content when the path has directory structure", () => {
75+ const content =
76+ "```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
77+ expect(
78+ extractContentFromCodeBlock(content, "src/components/Button.jsx"),
79+ ).toBe("const Button = () => <button>Click me</button>;");
80+ });
81+
82+ it("should match exact paths only", () => {
83+ const content =
84+ "```typescript src/utils.ts\nconst util = {};\n```\n" +
85+ "```typescript src/utils/index.ts\nconst index = {};\n```";
86+
87+ expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
88+ "const util = {};",
89+ );
90+ expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
91+ "const index = {};",
92+ );
93+ });
94+});
added core/llm/utils/extractContentFromCodeBlocks.ts +33 −0
@@ -0,0 +1,33 @@
1+/**
2+ * Extracts content from code blocks with given path
3+ * @param content The full message content
4+ * @param path The file path to look for
5+ * @returns The content of the code block if found, undefined otherwise
6+ */
7+export function extractContentFromCodeBlock(
8+ content: string,
9+ path: string,
10+): string | undefined {
11+ // Escape special characters in the path for regex
12+ const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13+
14+ // Match the code block with this path
15+ // This regex looks for:
16+ // 1. Code block start with the path (```[language] path)
17+ // 2. The content until the closing ```
18+ // The path can be:
19+ // - With language: ```typescript src/main.ts
20+ // - Without language: ```src/main.ts
21+ // - With line ranges: ```js src/main.ts (1-10)
22+ const regex = new RegExp(
23+ `\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
24+ "m",
25+ );
26+
27+ const match = content.match(regex);
28+ if (match && match[1]) {
29+ return match[1];
30+ }
31+
32+ return undefined;
33+}
added core/nextEdit/NextEditLoggingService.ts +139 −0
@@ -0,0 +1,139 @@
1+import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
2+
3+import { DataLogger } from "../data/log";
4+import { Telemetry } from "../util/posthog";
5+import { NextEditOutcome } from "./types";
6+
7+export class NextEditLoggingService {
8+ private static instance: NextEditLoggingService;
9+
10+ // Key is completionId
11+ private _abortControllers = new Map<string, AbortController>();
12+ private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
13+ private _outcomes = new Map<string, NextEditOutcome>();
14+ _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
15+ undefined;
16+
17+ private constructor() {}
18+
19+ public static getInstance(): NextEditLoggingService {
20+ if (!NextEditLoggingService.instance) {
21+ NextEditLoggingService.instance = new NextEditLoggingService();
22+ }
23+ return NextEditLoggingService.instance;
24+ }
25+
26+ public createAbortController(completionId: string): AbortController {
27+ const abortController = new AbortController();
28+ this._abortControllers.set(completionId, abortController);
29+ return abortController;
30+ }
31+
32+ public deleteAbortController(completionId: string) {
33+ this._abortControllers.delete(completionId);
34+ }
35+
36+ public cancel() {
37+ this._abortControllers.forEach((abortController, id) => {
38+ abortController.abort();
39+ });
40+ this._abortControllers.clear();
41+ }
42+
43+ public accept(completionId: string): NextEditOutcome | undefined {
44+ if (this._logRejectionTimeouts.has(completionId)) {
45+ clearTimeout(this._logRejectionTimeouts.get(completionId));
46+ this._logRejectionTimeouts.delete(completionId);
47+ }
48+ if (this._outcomes.has(completionId)) {
49+ const outcome = this._outcomes.get(completionId)!;
50+ outcome.accepted = true;
51+ this.logNextEditOutcome(outcome);
52+ this._outcomes.delete(completionId);
53+ return outcome;
54+ }
55+ }
56+
57+ public reject(completionId: string): NextEditOutcome | undefined {
58+ if (this._logRejectionTimeouts.has(completionId)) {
59+ clearTimeout(this._logRejectionTimeouts.get(completionId));
60+ this._logRejectionTimeouts.delete(completionId);
61+ }
62+
63+ if (this._outcomes.has(completionId)) {
64+ const outcome = this._outcomes.get(completionId)!;
65+ outcome.accepted = false;
66+ this.logNextEditOutcome(outcome);
67+ this._outcomes.delete(completionId);
68+ return outcome;
69+ }
70+ }
71+
72+ public cancelRejectionTimeout(completionId: string) {
73+ if (this._logRejectionTimeouts.has(completionId)) {
74+ clearTimeout(this._logRejectionTimeouts.get(completionId)!);
75+ this._logRejectionTimeouts.delete(completionId);
76+ }
77+ if (this._outcomes.has(completionId)) {
78+ this._outcomes.delete(completionId);
79+ }
80+ }
81+
82+ public cancelRejectionTimeoutButKeepCompletionId(completionId: string) {
83+ if (this._logRejectionTimeouts.has(completionId)) {
84+ clearTimeout(this._logRejectionTimeouts.get(completionId)!);
85+ }
86+ }
87+
88+ public markDisplayed(completionId: string, outcome: NextEditOutcome) {
89+ const logRejectionTimeout = setTimeout(() => {
90+ // Wait 10 seconds, then assume it wasn't accepted
91+ outcome.accepted = false;
92+ this.logNextEditOutcome(outcome);
93+ this._logRejectionTimeouts.delete(completionId);
94+ }, COUNT_COMPLETION_REJECTED_AFTER);
95+ this._outcomes.set(completionId, outcome);
96+ this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
97+
98+ // If the previously displayed completion is still waiting for rejection,
99+ // and this one is a continuation of that (the outcome.completion is the same modulo prefix)
100+ // then we should cancel the rejection timeout
101+ const previous = this._lastDisplayedCompletion;
102+ const now = Date.now();
103+ if (previous && this._logRejectionTimeouts.has(previous.id)) {
104+ const previousOutcome = this._outcomes.get(previous.id);
105+ const c1 = previousOutcome?.completion.split("\n")[0] ?? "";
106+ const c2 = outcome.completion.split("\n")[0];
107+ if (
108+ previousOutcome &&
109+ (c1.endsWith(c2) ||
110+ c2.endsWith(c1) ||
111+ c1.startsWith(c2) ||
112+ c2.startsWith(c1))
113+ ) {
114+ this.cancelRejectionTimeout(previous.id);
115+ } else if (now - previous.displayedAt < 500) {
116+ // If a completion isn't shown for more than
117+ this.cancelRejectionTimeout(previous.id);
118+ }
119+ }
120+
121+ this._lastDisplayedCompletion = {
122+ id: completionId,
123+ displayedAt: now,
124+ };
125+ }
126+
127+ private logNextEditOutcome(outcome: NextEditOutcome) {
128+ void DataLogger.getInstance().logDevData({
129+ name: "nextEditOutcome",
130+ data: outcome,
131+ // data: {
132+ // ...outcome, // TODO: this is somehow getting messed up with autocomplete schema.
133+ // },
134+ });
135+
136+ // const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
137+ void Telemetry.capture("nextEditOutcome", outcome, true);
138+ }
139+}
modified core/nextEdit/NextEditProvider.ts +161 −114
@@ -1,26 +1,33 @@
1+import * as path from "path";
12 import { ConfigHandler } from "../config/ConfigHandler.js";
2-import { IDE, ILLM } from "../index.js";
3+import { ChatMessage, IDE, ILLM } from "../index.js";
34 import OpenAI from "../llm/llms/OpenAI.js";
45 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
56
6-import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js";
77 import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
88
99 import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
1010 import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
11-import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
1211 import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
13-import { getAllSnippets } from "../autocomplete/snippets/index.js";
14-import { renderPrompt } from "../autocomplete/templating/index.js";
12+import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
1513 import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
1614 import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
17-import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
1815 import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
1916 import { HelperVars } from "../autocomplete/util/HelperVars.js";
17+import { AutocompleteInput } from "../autocomplete/util/types.js";
18+import { replaceEscapedCharacters } from "../util/text.js";
2019 import {
21- AutocompleteInput,
22- AutocompleteOutcome,
23-} from "../autocomplete/util/types.js";
20+ NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
21+ NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
22+} from "./constants.js";
23+import { NextEditLoggingService } from "./NextEditLoggingService.js";
24+import {
25+ renderDefaultSystemPrompt,
26+ renderDefaultUserPrompt,
27+ renderPrompt,
28+} from "./templating/NextEditPromptEngine.js";
29+import { NextEditOutcome, Prompt, PromptMetadata } from "./types.js";
30+// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
2431
2532 const autocompleteCache = AutocompleteLruCache.get();
2633
@@ -33,23 +40,65 @@
3340 ];
3441
3542 export class NextEditProvider {
43+ private static instance: NextEditProvider | null = null;
44+
3645 private autocompleteCache = AutocompleteLruCache.get();
3746 public errorsShown: Set<string> = new Set();
3847 private bracketMatchingService = new BracketMatchingService();
3948 private debouncer = new AutocompleteDebouncer();
4049 private completionStreamer: CompletionStreamer;
41- private loggingService = new AutocompleteLoggingService();
50+ private loggingService: NextEditLoggingService;
4251 private contextRetrievalService: ContextRetrievalService;
43-
44- constructor(
52+ private endpointType: "default" | "fineTuned";
53+ private diffContext: string = "";
54+ private promptMetadata: PromptMetadata | null = null;
55+
56+ private constructor(
4557 private readonly configHandler: ConfigHandler,
4658 private readonly ide: IDE,
4759 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
4860 private readonly _onError: (e: any) => void,
4961 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
62+ endpointType: "default" | "fineTuned",
5063 ) {
5164 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
5265 this.contextRetrievalService = new ContextRetrievalService(this.ide);
66+ this.endpointType = endpointType;
67+ this.loggingService = NextEditLoggingService.getInstance();
68+ }
69+
70+ public static initialize(
71+ configHandler: ConfigHandler,
72+ ide: IDE,
73+ injectedGetLlm: () => Promise<ILLM | undefined>,
74+ onError: (e: any) => void,
75+ getDefinitionsFromLsp: GetLspDefinitionsFunction,
76+ endpointType: "default" | "fineTuned",
77+ ): NextEditProvider {
78+ if (!NextEditProvider.instance) {
79+ NextEditProvider.instance = new NextEditProvider(
80+ configHandler,
81+ ide,
82+ injectedGetLlm,
83+ onError,
84+ getDefinitionsFromLsp,
85+ endpointType,
86+ );
87+ }
88+ return NextEditProvider.instance;
89+ }
90+
91+ public static getInstance(): NextEditProvider {
92+ if (!NextEditProvider.instance) {
93+ throw new Error(
94+ "NextEditProvider has not been initialized. Call initialize() first.",
95+ );
96+ }
97+ return NextEditProvider.instance;
98+ }
99+
100+ public addDiffToContext(diff: string): void {
101+ this.diffContext = diff;
53102 }
54103
55104 private async _prepareLlm(): Promise<ILLM | undefined> {
@@ -109,18 +158,21 @@
109158 this.loggingService.cancel();
110159 }
111160
112- public accept(completionId: string) {
113- const outcome = this.loggingService.accept(completionId);
114- if (!outcome) {
115- return;
116- }
117- this.bracketMatchingService.handleAcceptedCompletion(
118- outcome.completion,
119- outcome.filepath,
120- );
121- }
122-
123- public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
161+ // public accept(completionId: string) {
162+ // const outcome = this.loggingService.accept(completionId);
163+ // if (!outcome) {
164+ // return;
165+ // }
166+ // }
167+
168+ // public reject(completionId: string) {
169+ // const outcome = this.loggingService.reject(completionId);
170+ // if (!outcome) {
171+ // return;
172+ // }
173+ // }
174+
175+ public markDisplayed(completionId: string, outcome: NextEditOutcome) {
124176 this.loggingService.markDisplayed(completionId, outcome);
125177 }
126178
@@ -136,7 +188,7 @@
136188 public async provideInlineCompletionItems(
137189 input: AutocompleteInput,
138190 token: AbortSignal | undefined,
139- ): Promise<AutocompleteOutcome | undefined> {
191+ ): Promise<NextEditOutcome | undefined> {
140192 try {
141193 // Create abort signal if not given
142194 if (!token) {
@@ -174,7 +226,7 @@
174226 }
175227
176228 const [snippetPayload, workspaceDirs] = await Promise.all([
177- getAllSnippets({
229+ getAllSnippetsWithoutRace({
178230 helper,
179231 ide: this.ide,
180232 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@@ -183,100 +235,95 @@
183235 this.ide.getWorkspaceDirs(),
184236 ]);
185237
186- const { prompt, prefix, suffix, completionOptions } = renderPrompt({
187- snippetPayload,
188- workspaceDirs,
189- helper,
190- });
191-
192- // Completion
193- let completion: string | undefined = "";
194-
195- const cache = await autocompleteCache;
196- const cachedCompletion = helper.options.useCache
197- ? await cache.get(helper.prunedPrefix)
198- : undefined;
199- let cacheHit = false;
200- if (cachedCompletion) {
201- // Cache
202- cacheHit = true;
203- completion = cachedCompletion;
238+ // TODO: Toggle between the default endpoint and the finetuned endpoint.
239+ const prompts: Prompt[] = [];
240+
241+ if (this.endpointType === "default") {
242+ prompts.push(renderDefaultSystemPrompt());
243+ prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
204244 } else {
205- const multiline =
206- !helper.options.transform || shouldCompleteMultiline(helper);
207-
208- const completionStream =
209- this.completionStreamer.streamCompletionWithFilters(
210- token,
211- llm,
212- prefix,
213- suffix,
214- prompt,
215- multiline,
216- completionOptions,
217- helper,
218- );
245+ const promptMetadata = renderPrompt(helper, this.diffContext);
246+ this.promptMetadata = promptMetadata;
247+ prompts.push(promptMetadata.prompt);
248+ }
219249
220- for await (const update of completionStream) {
221- completion += update;
250+ if (this.endpointType === "default") {
251+ const msg: ChatMessage = await llm.chat(prompts, token);
252+ if (typeof msg.content === "string") {
253+ const nextCompletion = JSON.parse(msg.content).newCode;
254+ const outcomeNext: NextEditOutcome = {
255+ elapsed: Date.now() - startTime,
256+ modelProvider: llm.underlyingProviderName,
257+ modelName: llm.model + ":zetaDataset",
258+ completionOptions: null,
259+ // filepath: helper.filepath,
260+ completionId: helper.input.completionId,
261+ gitRepo: await this.ide.getRepoName(helper.filepath),
262+ uniqueId: await this.ide.getUniqueId(),
263+ timestamp: Date.now(),
264+ fileUri: helper.filepath,
265+ workspaceDirUri:
266+ helper.workspaceUris[0] ?? path.dirname(helper.filepath),
267+ prompt: prompts.join("\n"),
268+ userEdits: "",
269+ userExcerpts: "",
270+ originalEditableRange: "",
271+ completion: nextCompletion,
272+ cursorPosition: helper.pos,
273+ ...helper.options,
274+ };
275+ return outcomeNext;
276+ } else {
277+ return undefined;
222278 }
223-
224- // Don't postprocess if aborted
225- if (token.aborted) {
279+ } else {
280+ const msg: ChatMessage = await llm.chat(prompts, token);
281+ if (typeof msg.content === "string") {
282+ // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
283+ const nextCompletion = replaceEscapedCharacters(
284+ msg.content.split("<|editable_region_start|>\n")[1],
285+ ).replace(/\n$/, "");
286+
287+ const currCursorPos = helper.pos;
288+ const editableRegionStartLine = Math.max(
289+ currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
290+ 0,
291+ );
292+ const editableRegionEndLine = Math.min(
293+ currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
294+ helper.fileLines.length - 1,
295+ );
296+ const oldEditRangeSlice = helper.fileContents
297+ .split("\n")
298+ .slice(editableRegionStartLine, editableRegionEndLine + 1)
299+ .join("\n");
300+
301+ const outcomeNext: NextEditOutcome = {
302+ elapsed: Date.now() - startTime,
303+ modelProvider: llm.underlyingProviderName,
304+ modelName: llm.model + ":zetaDataset",
305+ completionOptions: null,
306+ // filepath: helper.filepath,
307+ completionId: helper.input.completionId,
308+ gitRepo: await this.ide.getRepoName(helper.filepath),
309+ uniqueId: await this.ide.getUniqueId(),
310+ timestamp: Date.now(),
311+ fileUri: helper.filepath,
312+ workspaceDirUri:
313+ helper.workspaceUris[0] ?? path.dirname(helper.filepath),
314+ prompt: this.promptMetadata!.prompt.content,
315+ userEdits: this.promptMetadata!.userEdits,
316+ userExcerpts: this.promptMetadata!.userExcerpts,
317+ originalEditableRange: oldEditRangeSlice,
318+ completion: nextCompletion,
319+ cursorPosition: helper.pos,
320+ ...helper.options,
321+ };
322+ return outcomeNext;
323+ } else {
226324 return undefined;
227325 }
228-
229- const processedCompletion = helper.options.transform
230- ? postprocessCompletion({
231- completion,
232- prefix: helper.prunedPrefix,
233- suffix: helper.prunedSuffix,
234- llm,
235- })
236- : completion;
237-
238- completion = processedCompletion;
239- }
240-
241- if (!completion) {
242- return undefined;
243326 }
244-
245- const outcome: AutocompleteOutcome = {
246- time: Date.now() - startTime,
247- completion,
248- prefix,
249- suffix,
250- prompt,
251- modelProvider: llm.underlyingProviderName,
252- modelName: llm.model,
253- completionOptions,
254- cacheHit,
255- filepath: helper.filepath,
256- numLines: completion.split("\n").length,
257- completionId: helper.input.completionId,
258- gitRepo: await this.ide.getRepoName(helper.filepath),
259- uniqueId: await this.ide.getUniqueId(),
260- timestamp: Date.now(),
261- ...helper.options,
262- };
263-
264- //////////
265-
266- // Save to cache
267- if (!outcome.cacheHit && helper.options.useCache) {
268- (await this.autocompleteCache)
269- .put(outcome.prefix, outcome.completion)
270- .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
271- }
272-
273- // When using the JetBrains extension, Mark as displayed
274- const ideType = (await this.ide.getIdeInfo()).ideType;
275- if (ideType === "jetbrains") {
276- this.markDisplayed(input.completionId, outcome);
277- }
278-
279- return outcome;
280327 } catch (e: any) {
281328 this.onError(e);
282329 } finally {
added core/nextEdit/README.md +29 −0
@@ -0,0 +1,29 @@
1+# Next Edit Prediction
2+
3+## What is it?
4+
5+## How is it different from autocomplete?
6+
7+## Where are we right now?
8+
9+- Users can decide to switch between autocomplete and next edit.
10+- Next edit triggers at the same time autocomplete is triggered, via vscode's inline completion provider.
11+- The following happens after the trigger:
12+ - User's current cursor position is captured.
13+ - We define an editable range, ±5 lines from the current cursor position.
14+ - User's most recent edit is captured as a unified diff. (this is currently buggy)
15+ - This is sent to the model, which returns a new editable range with next edit predictions.
16+ - We display this new editable range in a SVG decoration.
17+ - User can either tab to accept or esc to reject.
18+ - On accept, the old editable range will be replaced by the new editable region. The cursor will be moved to the last line containing some change.
19+ - On reject, nothing happens.
20+
21+## What needs to be worked on?
22+
23+- User edit captures.
24+- Find a better way to trigger next edit (this links back to the diff capture problem).
25+ - We can see that next edit triggers as soon as the user accepts a change. This is because autocomplete runs the same way.
26+ - I think autocomplete has some filter logic that doesn't display the ghost text under some conditions, which I am guessing are the following:
27+ - The model does not have any more completions to create.
28+ - The prediction at the cursor location has been cached.
29+- JetBrains integration.
modified core/nextEdit/constants.ts +5 −0
@@ -1,1 +1,6 @@
11 export const IS_NEXT_EDIT_ACTIVE = false;
2+export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
3+export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
4+export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
5+export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
6+export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";
added core/nextEdit/context/aggregateEdits.ts +576 −0
@@ -0,0 +1,576 @@
1+import { Position, RangeInFileWithNextEditInfo } from "../..";
2+import {
3+ BeforeAfterDiff,
4+ DiffFormatType,
5+ createBeforeAfterDiff,
6+ createDiff,
7+} from "./diffFormatting";
8+
9+interface ClusterState {
10+ beforeState: string; // stores content of cluster before edit
11+ startRange: { minLine: number; maxLine: number };
12+ currentRange: { minLine: number; maxLine: number };
13+ edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster
14+ firstTimestamp: number;
15+ lastTimestamp: number;
16+ lastLine: number;
17+ firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster
18+ lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster
19+}
20+
21+interface FileState {
22+ activeClusters: ClusterState[]; // Stores active clusters for the file
23+ currentContent: string; // Stores the current content of the file
24+ priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use)
25+ processingQueue: Array<() => Promise<void>>; // Stores a queue of small edits to be processed into clusters
26+ isProcessing: boolean;
27+}
28+
29+export interface EditClusterConfig {
30+ deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created
31+ deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created
32+ maxEdits: number; // Maximum number of edits in a cluster
33+ maxDuration: number; // Maximum total duration of an edit in seconds
34+ contextSize: number; // Number of previous edits to store; not currently used but kept for future use
35+ contextLines: number; // Used for computations involving deltaL
36+}
37+
38+export class EditAggregator {
39+ private fileStates: Map<string, FileState> = new Map();
40+ public config: EditClusterConfig;
41+ private previousEditFinalCursorPosition: Position;
42+ private lastProcessedFilePath: string | null = null;
43+ public onComparisonFinalized: (
44+ diff: BeforeAfterDiff,
45+ beforeCursorPos: Position,
46+ afterPrevEditCursorPos: Position,
47+ ) => void;
48+
49+ private static _instance: EditAggregator | null = null;
50+
51+ public static getInstance(
52+ config?: Partial<EditClusterConfig>,
53+ onComparisonFinalized?: (
54+ diff: BeforeAfterDiff,
55+ beforeCursorPos: Position,
56+ afterPrevEditCursorPos: Position,
57+ ) => void,
58+ ): EditAggregator {
59+ // Create instance if it doesn't exist
60+ if (!EditAggregator._instance) {
61+ EditAggregator._instance = new EditAggregator(
62+ config,
63+ onComparisonFinalized,
64+ );
65+ }
66+ // Update instance if new parameters are provided
67+ else if (config || onComparisonFinalized) {
68+ if (config) {
69+ EditAggregator._instance.config = {
70+ deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT,
71+ deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL,
72+ maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits,
73+ maxDuration:
74+ config.maxDuration ?? EditAggregator._instance.config.maxDuration,
75+ contextSize:
76+ config.contextSize ?? EditAggregator._instance.config.contextSize,
77+ contextLines:
78+ config.contextLines ?? EditAggregator._instance.config.contextLines,
79+ };
80+ }
81+
82+ if (onComparisonFinalized) {
83+ EditAggregator._instance.onComparisonFinalized = onComparisonFinalized;
84+ }
85+ }
86+
87+ return EditAggregator._instance;
88+ }
89+
90+ constructor(
91+ config: Partial<EditClusterConfig> = {},
92+ onComparisonFinalized: (
93+ diff: BeforeAfterDiff,
94+ beforeCursorPos: Position,
95+ afterPrevEditCursorPos: Position,
96+ ) => void = () => {},
97+ ) {
98+ this.config = {
99+ deltaT: config.deltaT ?? 1.0,
100+ deltaL: config.deltaL ?? 5,
101+ maxEdits: config.maxEdits ?? 500,
102+ maxDuration: config.maxDuration ?? 100.0,
103+ contextSize: config.contextSize ?? 5,
104+ contextLines: config.contextLines ?? 3,
105+ };
106+ this.onComparisonFinalized = onComparisonFinalized;
107+ this.previousEditFinalCursorPosition = { line: 0, character: 0 };
108+ }
109+
110+ async processEdit(
111+ edit: RangeInFileWithNextEditInfo,
112+ timestamp: number = Date.now(),
113+ ): Promise<void> {
114+ const filePath = edit.filepath;
115+
116+ // If we're switching to a different file, finalize all clusters from the previous file
117+ if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
118+ await this.finalizeClustersForFile(this.lastProcessedFilePath);
119+ }
120+
121+ // Update the last processed file path
122+ this.lastProcessedFilePath = filePath;
123+
124+ if (!this.fileStates.has(filePath)) {
125+ this.fileStates.set(filePath, {
126+ activeClusters: [],
127+ currentContent: edit.fileContents,
128+ priorComparisons: [],
129+ processingQueue: [],
130+ isProcessing: false,
131+ });
132+ }
133+
134+ const fileState = this.fileStates.get(filePath)!;
135+ const task = async () => {
136+ await this._processEditInternal(edit, timestamp, fileState);
137+ };
138+
139+ fileState.processingQueue.push(task);
140+
141+ if (!fileState.isProcessing) {
142+ void this._processQueue(filePath);
143+ }
144+ }
145+
146+ private async _processQueue(filePath: string): Promise<void> {
147+ const fileState = this.fileStates.get(filePath);
148+ if (!fileState) return;
149+
150+ fileState.isProcessing = true;
151+
152+ // Process chunks of (5) edits instead of one at a time
153+ while (fileState.processingQueue.length > 0) {
154+ const tasks = fileState.processingQueue.splice(0, 5);
155+ if (tasks.length > 0) {
156+ try {
157+ await Promise.all(tasks.map((task) => task()));
158+ } catch (error) {
159+ console.error(`Error processing edits in ${filePath}:`, error);
160+ }
161+
162+ // Yield to the event loop to prevent blocking
163+ await new Promise((resolve) => setTimeout(resolve, 0));
164+ }
165+ }
166+
167+ fileState.isProcessing = false;
168+ }
169+
170+ private async _processEditInternal(
171+ edit: RangeInFileWithNextEditInfo,
172+ timestamp: number,
173+ fileState: FileState,
174+ ): Promise<void> {
175+ const filePath = edit.filepath;
176+
177+ const editLine = edit.range.start.line;
178+ const currentFileLines = fileState.currentContent.split("\n");
179+
180+ const clustersToFinalize = this.identifyClustersToFinalize(
181+ fileState,
182+ edit,
183+ timestamp,
184+ false,
185+ );
186+
187+ for (const cluster of clustersToFinalize) {
188+ await this.finalizeCluster(filePath, cluster, fileState);
189+ }
190+
191+ let suitableCluster = this.findSuitableCluster(
192+ fileState,
193+ editLine,
194+ timestamp,
195+ );
196+
197+ // Check if adding this edit would exceed deltaL lines for the cluster
198+ if (suitableCluster) {
199+ const potentialMinLine = Math.min(
200+ suitableCluster.currentRange.minLine,
201+ Math.max(0, editLine - this.config.contextLines),
202+ );
203+ const potentialMaxLine = Math.max(
204+ suitableCluster.currentRange.maxLine,
205+ Math.min(
206+ currentFileLines.length - 1,
207+ editLine + this.config.contextLines,
208+ ),
209+ );
210+ const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
211+
212+ if (potentialLineSpan > this.config.deltaL * 2) {
213+ // Auto-finalize the current cluster before creating a new one
214+ await this.finalizeCluster(filePath, suitableCluster, fileState);
215+ suitableCluster = null;
216+ }
217+ }
218+
219+ // initialize a cluster
220+ if (!suitableCluster) {
221+ suitableCluster = {
222+ beforeState: fileState.currentContent,
223+ startRange: {
224+ minLine: Math.max(0, editLine - this.config.contextLines),
225+ maxLine: Math.min(
226+ currentFileLines.length - 1,
227+ editLine + this.config.contextLines,
228+ ),
229+ },
230+ currentRange: {
231+ minLine: Math.max(0, editLine - this.config.contextLines),
232+ maxLine: Math.min(
233+ currentFileLines.length - 1,
234+ editLine + this.config.contextLines,
235+ ),
236+ },
237+ edits: [],
238+ firstTimestamp: timestamp,
239+ lastTimestamp: timestamp,
240+ lastLine: editLine,
241+ firstEditBeforeCursor: edit.beforeCursorPos,
242+ lastEditAfterCursor: edit.afterCursorPos,
243+ };
244+ fileState.activeClusters.push(suitableCluster);
245+ }
246+
247+ suitableCluster.edits.push(edit);
248+ suitableCluster.lastTimestamp = timestamp;
249+ suitableCluster.lastLine = editLine;
250+ suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
251+
252+ const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
253+ edit,
254+ fileState.currentContent,
255+ );
256+
257+ if (!isWhitespaceOnly) {
258+ suitableCluster.currentRange.minLine = Math.min(
259+ suitableCluster.currentRange.minLine,
260+ Math.max(0, editLine - this.config.contextLines),
261+ );
262+ suitableCluster.currentRange.maxLine = Math.max(
263+ suitableCluster.currentRange.maxLine,
264+ Math.min(
265+ currentFileLines.length - 1,
266+ editLine + this.config.contextLines,
267+ ),
268+ );
269+ }
270+
271+ fileState.currentContent = edit.fileContents;
272+
273+ const isStructuralEdit =
274+ edit.editText.includes("\n") ||
275+ edit.range.start.line !== edit.range.end.line;
276+
277+ if (isStructuralEdit) {
278+ const additionalClustersToFinalize = fileState.activeClusters.filter(
279+ (c) =>
280+ c !== suitableCluster && this.clustersOverlap(c, suitableCluster),
281+ );
282+
283+ for (const cluster of additionalClustersToFinalize) {
284+ await this.finalizeCluster(filePath, cluster, fileState);
285+ }
286+ }
287+ }
288+
289+ private isWhitespaceOnlyEdit(
290+ edit: RangeInFileWithNextEditInfo,
291+ currentContent: string,
292+ ): boolean {
293+ const lines = currentContent.split("\n");
294+ const line = edit.range.start.line;
295+
296+ if (line >= lines.length) return false;
297+
298+ if (edit.range.start.line === edit.range.end.line) {
299+ const beforeEdit = lines[line];
300+ const afterEdit =
301+ beforeEdit.substring(0, edit.range.start.character) +
302+ edit.editText +
303+ beforeEdit.substring(edit.range.end.character);
304+
305+ return beforeEdit.trim() === afterEdit.trim();
306+ }
307+
308+ return false;
309+ }
310+
311+ private clustersOverlap(
312+ cluster1: ClusterState,
313+ cluster2: ClusterState,
314+ ): boolean {
315+ return (
316+ cluster1.currentRange.minLine <=
317+ cluster2.currentRange.maxLine + this.config.deltaL &&
318+ cluster1.currentRange.maxLine >=
319+ cluster2.currentRange.minLine - this.config.deltaL
320+ );
321+ }
322+
323+ async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
324+ const timestamp = Date.now();
325+
326+ // Only process the last edit during rapid typing
327+ if (this.getProcessingQueueSize() > 50) {
328+ if (edits.length > 0) {
329+ await this.processEdit(edits[edits.length - 1], timestamp);
330+ }
331+ return;
332+ }
333+
334+ for (const edit of edits) {
335+ await this.processEdit(edit, timestamp);
336+ }
337+ }
338+
339+ /**
340+ * Finalizes all clusters for a specific file
341+ */
342+ private async finalizeClustersForFile(filePath: string): Promise<void> {
343+ const fileState = this.fileStates.get(filePath);
344+ if (!fileState) return;
345+
346+ // Create a copy of the clusters to finalize to avoid modifying array during iteration
347+ const clustersToFinalize = [...fileState.activeClusters];
348+
349+ for (const cluster of clustersToFinalize) {
350+ await this.finalizeCluster(filePath, cluster, fileState);
351+ }
352+ }
353+
354+ async finalizeAllClusters(): Promise<void> {
355+ const filePromises: Promise<void>[] = [];
356+
357+ this.fileStates.forEach((fileState, filePath) => {
358+ const filePromise = this.finalizeClustersForFile(filePath);
359+ filePromises.push(filePromise);
360+ });
361+
362+ await Promise.all(filePromises);
363+ }
364+
365+ private findSuitableCluster(
366+ fileState: FileState,
367+ editLine: number,
368+ timestamp: number,
369+ ): ClusterState | null {
370+ const activeClusters = [...fileState.activeClusters];
371+
372+ for (const cluster of activeClusters) {
373+ // If we're outside the line range but within the time window,
374+ // we should finalize the current cluster
375+ const isOutsideLineRange =
376+ editLine < cluster.currentRange.minLine - this.config.deltaL ||
377+ editLine > cluster.currentRange.maxLine + this.config.deltaL;
378+
379+ const isWithinTimeWindow =
380+ (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
381+
382+ // If user quickly jumped far away, finalize this cluster before continuing
383+ if (isOutsideLineRange && isWithinTimeWindow) {
384+ void this.finalizeCluster(
385+ cluster.edits[0].filepath,
386+ cluster,
387+ fileState,
388+ );
389+ }
390+ }
391+
392+ // Now look for a suitable cluster for the new edit
393+ for (const cluster of fileState.activeClusters) {
394+ const isOnSameLine = editLine === cluster.lastLine;
395+ const isWithinTimeWindow =
396+ (timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
397+ const isWithinLineRange =
398+ editLine >= cluster.currentRange.minLine - this.config.deltaL &&
399+ editLine <= cluster.currentRange.maxLine + this.config.deltaL;
400+ const isWithinEditLimit = cluster.edits.length < this.config.maxEdits;
401+ const isWithinDurationLimit =
402+ (timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration;
403+
404+ if (
405+ (isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) &&
406+ isWithinEditLimit &&
407+ isWithinDurationLimit
408+ ) {
409+ return cluster;
410+ }
411+ }
412+ return null;
413+ }
414+
415+ private identifyClustersToFinalize(
416+ fileState: FileState,
417+ edit: RangeInFileWithNextEditInfo,
418+ timestamp: number,
419+ isStructuralEdit: boolean,
420+ ): ClusterState[] {
421+ const clustersToFinalize: ClusterState[] = [];
422+ const editLine = edit.range.start.line;
423+
424+ fileState.activeClusters.forEach((cluster) => {
425+ const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
426+
427+ const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
428+
429+ const isOnDifferentLineByNewline = edit.editText.includes("\n");
430+
431+ // Use different time thresholds for different types of line change detection
432+ const shouldFinalizeByLineNumber =
433+ isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
434+
435+ const shouldFinalizeByNewline =
436+ isOnDifferentLineByNewline &&
437+ timeSinceLastEdit > this.config.deltaT * 1.5;
438+
439+ // Finalize if we moved to a different line AND the time gap exceeds the respective threshold
440+ const shouldFinalizeByTime =
441+ shouldFinalizeByLineNumber || shouldFinalizeByNewline;
442+ const shouldFinalizeByCount =
443+ cluster.edits.length >= this.config.maxEdits;
444+ const shouldFinalizeByDuration =
445+ (timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
446+
447+ // For structural edits, use the combined line detection
448+ const isOnDifferentLine =
449+ isOnDifferentLineByNumber || isOnDifferentLineByNewline;
450+ const shouldFinalizeByStructuralEdit =
451+ isStructuralEdit && isOnDifferentLine;
452+
453+ if (
454+ shouldFinalizeByTime ||
455+ shouldFinalizeByCount ||
456+ shouldFinalizeByDuration ||
457+ shouldFinalizeByStructuralEdit
458+ ) {
459+ clustersToFinalize.push(cluster);
460+ }
461+ });
462+
463+ return clustersToFinalize;
464+ }
465+
466+ private async finalizeCluster(
467+ filePath: string,
468+ cluster: ClusterState,
469+ fileState: FileState,
470+ ): Promise<void> {
471+ const beforeContent = cluster.beforeState;
472+ const afterContent = fileState.currentContent;
473+
474+ // Skip whitespace-only diffs
475+ const isWhitespaceOnlyDiff =
476+ beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "");
477+
478+ if (isWhitespaceOnlyDiff) {
479+ fileState.activeClusters = fileState.activeClusters.filter(
480+ (c) => c !== cluster,
481+ );
482+ return;
483+ }
484+
485+ const diff = createDiff({
486+ beforeContent: beforeContent,
487+ afterContent: afterContent,
488+ filePath: filePath,
489+ diffType: DiffFormatType.Unified,
490+ contextLines: 3,
491+ }); // Used for checks, not for final output
492+
493+ // Skip diffs with too many changed lines
494+ const changedLineCount = this.countChangedLines(diff);
495+ if (changedLineCount > this.config.deltaL * 2) {
496+ fileState.activeClusters = fileState.activeClusters.filter(
497+ (c) => c !== cluster,
498+ );
499+ return;
500+ }
501+
502+ fileState.priorComparisons.push(diff);
503+ if (fileState.priorComparisons.length > this.config.contextSize) {
504+ fileState.priorComparisons.shift();
505+ }
506+
507+ fileState.activeClusters = fileState.activeClusters.filter(
508+ (c) => c !== cluster,
509+ );
510+
511+ // Give format-agnostic diff to the callback
512+ const fullFileVersionsDiff = createBeforeAfterDiff(
513+ beforeContent,
514+ afterContent,
515+ filePath,
516+ );
517+
518+ // Store this cluster's final cursor position for future reference
519+ this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
520+
521+ this.onComparisonFinalized(
522+ fullFileVersionsDiff,
523+ cluster.firstEditBeforeCursor,
524+ this.previousEditFinalCursorPosition,
525+ );
526+ }
527+
528+ private countChangedLines(diff: string): number {
529+ let count = 0;
530+ let addedLines = new Set<number>();
531+ let removedLines = new Set<number>();
532+
533+ // Parse the diff lines
534+ const lines = diff.split("\n");
535+ for (const line of lines) {
536+ if (
537+ line.startsWith("+++ ") ||
538+ line.startsWith("--- ") ||
539+ line.startsWith("@@")
540+ ) {
541+ continue; // Skip header lines
542+ }
543+
544+ if (line.startsWith("+")) {
545+ addedLines.add(count);
546+ count++;
547+ } else if (line.startsWith("-")) {
548+ removedLines.add(count);
549+ count++;
550+ }
551+ }
552+
553+ return Math.max(addedLines.size, removedLines.size);
554+ }
555+
556+ getActiveClusterCount(): number {
557+ let count = 0;
558+ this.fileStates.forEach((fileState) => {
559+ count += fileState.activeClusters.length;
560+ });
561+ return count;
562+ }
563+
564+ getProcessingQueueSize(): number {
565+ let count = 0;
566+ this.fileStates.forEach((fileState) => {
567+ count += fileState.processingQueue.length;
568+ });
569+ return count;
570+ }
571+
572+ resetState(): void {
573+ this.fileStates.clear();
574+ this.lastProcessedFilePath = null;
575+ }
576+}
added core/nextEdit/context/autocompleteContextFetching.ts +140 −0
@@ -0,0 +1,140 @@
1+import { Position } from "../..";
2+import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
3+import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
4+import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
5+import { renderPrompt } from "../../autocomplete/templating";
6+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
7+import { HelperVars } from "../../autocomplete/util/HelperVars";
8+import {
9+ AutocompleteInput,
10+ RecentlyEditedRange,
11+} from "../../autocomplete/util/types";
12+import { ConfigHandler } from "../../config/ConfigHandler";
13+import { IDE, ILLM } from "../../index";
14+import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
15+
16+/**
17+ * Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
18+ * This function mimics the context generation pipeline from the autocomplete system without triggering
19+ * an actual completion.
20+ *
21+ * @param filepath - The file path where context is being requested
22+ * @param pos - The position in the file where context is being requested
23+ * @param ide - The IDE interface for file system operations
24+ * @param configHandler - The config handler to load user configuration
25+ * @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
26+ * @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
27+ * @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
28+ * @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
29+ * @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
30+ * @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
31+ * @returns Promise that resolves to the formatted context string
32+ */
33+export const getAutocompleteContext = async (
34+ filepath: string,
35+ pos: Position,
36+ ide: IDE,
37+ configHandler: ConfigHandler,
38+ getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
39+ recentlyEditedRanges: RecentlyEditedRange[],
40+ recentlyVisitedRanges: AutocompleteCodeSnippet[],
41+ maxPromptTokens: number,
42+ manuallyPassFileContents: string,
43+ autocompleteModel?: ILLM | string,
44+ // eslint-disable-next-line max-params
45+): Promise<string> => {
46+ if (!recentlyEditedRanges) recentlyEditedRanges = [];
47+ if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
48+
49+ const input: AutocompleteInput = {
50+ isUntitledFile: false,
51+ completionId: `context-fetch-${Date.now()}`,
52+ filepath,
53+ pos,
54+ recentlyVisitedRanges,
55+ recentlyEditedRanges,
56+ manuallyPassFileContents,
57+ };
58+
59+ const { config } = await configHandler.loadConfig();
60+ if (!config) {
61+ throw new Error("No config available");
62+ }
63+
64+ // Use provided autocomplete model or fall back to configured autocomplete model
65+ let finalModel: ILLM;
66+ let modelNameForTemplating: string;
67+
68+ if (autocompleteModel) {
69+ if (typeof autocompleteModel === "string") {
70+ // Try to find the model in config first
71+ const foundModel = config.modelsByRole.autocomplete.find(
72+ (m) => m.title === autocompleteModel,
73+ );
74+ if (foundModel) {
75+ finalModel = foundModel;
76+ modelNameForTemplating = foundModel.model;
77+ } else {
78+ // Model not found in config, but we can still use it for template selection
79+ const configuredModel = config.selectedModelByRole.autocomplete;
80+ if (!configuredModel) {
81+ throw new Error(
82+ "No autocomplete model configured and provided model not found in config",
83+ );
84+ }
85+ finalModel = configuredModel;
86+ modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
87+ }
88+ } else {
89+ finalModel = autocompleteModel;
90+ modelNameForTemplating = autocompleteModel.model;
91+ }
92+ } else {
93+ const configuredModel = config.selectedModelByRole.autocomplete;
94+ if (!configuredModel) {
95+ throw new Error("No autocomplete model configured and no model provided");
96+ }
97+ finalModel = configuredModel;
98+ modelNameForTemplating = configuredModel.model;
99+ }
100+
101+ const options = {
102+ ...DEFAULT_AUTOCOMPLETE_OPTS,
103+ ...config.tabAutocompleteOptions,
104+ ...finalModel.autocompleteOptions,
105+ ...(maxPromptTokens && { maxPromptTokens }),
106+ };
107+
108+ if (finalModel.promptTemplates?.autocomplete) {
109+ options.template = finalModel.promptTemplates.autocomplete as string;
110+ }
111+
112+ const helper = await HelperVars.create(
113+ input,
114+ options,
115+ modelNameForTemplating,
116+ ide,
117+ );
118+
119+ const contextRetrievalService = new ContextRetrievalService(ide);
120+
121+ await contextRetrievalService.initializeForFile(filepath);
122+
123+ const [snippetPayload, workspaceDirs] = await Promise.all([
124+ getAllSnippetsWithoutRace({
125+ helper,
126+ ide: ide,
127+ getDefinitionsFromLsp: getDefinitionsFromLsp,
128+ contextRetrievalService: contextRetrievalService,
129+ }),
130+ ide.getWorkspaceDirs(),
131+ ]);
132+
133+ const { prompt, prefix, suffix, completionOptions } = renderPrompt({
134+ snippetPayload,
135+ workspaceDirs,
136+ helper,
137+ });
138+
139+ return prefix;
140+};
added core/nextEdit/context/diffFormatting.ts +97 −0
@@ -0,0 +1,97 @@
1+import { createPatch } from "diff";
2+
3+export enum DiffFormatType {
4+ Unified = "unified",
5+ RawBeforeAfter = "beforeAfter",
6+ TokenLineDiff = "linediff",
7+}
8+
9+export type BeforeAfterDiff = {
10+ filePath: string;
11+ beforeContent: string;
12+ afterContent: string;
13+};
14+
15+export interface CreateDiffArgs {
16+ beforeContent: string;
17+ afterContent: string;
18+ filePath: string;
19+ diffType: DiffFormatType;
20+ contextLines: number;
21+}
22+
23+export const createDiff = ({
24+ beforeContent,
25+ afterContent,
26+ filePath,
27+ diffType,
28+ contextLines,
29+}: CreateDiffArgs) => {
30+ switch (diffType) {
31+ case DiffFormatType.Unified:
32+ return createUnifiedDiff(
33+ beforeContent,
34+ afterContent,
35+ filePath,
36+ contextLines,
37+ );
38+ case DiffFormatType.TokenLineDiff:
39+ return createTokenLineDiff(beforeContent, afterContent, filePath);
40+ }
41+ return "";
42+};
43+
44+const createUnifiedDiff = (
45+ beforeContent: string,
46+ afterContent: string,
47+ filePath: string,
48+ contextLines: number,
49+) => {
50+ const normalizedBefore = beforeContent.endsWith("\n")
51+ ? beforeContent
52+ : beforeContent + "\n";
53+ const normalizedAfter = afterContent.endsWith("\n")
54+ ? afterContent
55+ : afterContent + "\n";
56+
57+ const patch = createPatch(
58+ filePath,
59+ normalizedBefore,
60+ normalizedAfter,
61+ "before",
62+ "after",
63+ { context: contextLines },
64+ );
65+
66+ return patch;
67+};
68+
69+export const createBeforeAfterDiff = (
70+ beforeContent: string,
71+ afterContent: string,
72+ filePath: string,
73+) => {
74+ const normalizedBefore = beforeContent.endsWith("\n")
75+ ? beforeContent
76+ : beforeContent + "\n";
77+ const normalizedAfter = afterContent.endsWith("\n")
78+ ? afterContent
79+ : afterContent + "\n";
80+
81+ const result: BeforeAfterDiff = {
82+ filePath: filePath,
83+ beforeContent: normalizedBefore,
84+ afterContent: normalizedAfter,
85+ };
86+
87+ return result;
88+};
89+
90+const createTokenLineDiff = (
91+ beforeContent: string,
92+ afterContent: string,
93+ filePath: string,
94+) => {
95+ // TODO: Implement token line diff
96+ return "";
97+};
added core/nextEdit/context/prevEditLruCache.ts +30 −0
@@ -0,0 +1,30 @@
1+import QuickLRU from "quick-lru";
2+
3+export interface prevEdit {
4+ unidiff: string;
5+ fileUri: string;
6+ workspaceUri: string;
7+ timestamp: number;
8+}
9+const maxPrevEdits = 5;
10+
11+export const prevEditLruCache = new QuickLRU<string, prevEdit>({
12+ maxSize: maxPrevEdits,
13+});
14+
15+export const setPrevEdit = (edit: prevEdit): void => {
16+ const uniqueSuffix = Math.random().toString(36).substring(2, 8);
17+ const key = `${edit.fileUri}:${edit.timestamp}:${uniqueSuffix}`;
18+ prevEditLruCache.set(key, edit);
19+};
20+
21+export const getPrevEditsDescending = (): prevEdit[] => {
22+ const edits: prevEdit[] = [];
23+ for (const [_, edit] of prevEditLruCache.entriesDescending()) {
24+ if (edits.length >= maxPrevEdits) {
25+ break;
26+ }
27+ edits.push(edit);
28+ }
29+ return edits;
30+};
added core/nextEdit/context/processNextEditData.ts +143 −0
@@ -0,0 +1,143 @@
1+import { IDE, Position } from "../..";
2+import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
3+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
4+import { ConfigHandler } from "../../config/ConfigHandler";
5+import { DataLogger } from "../../data/log";
6+import { RecentlyEditedRange } from "../types";
7+import { getAutocompleteContext } from "./autocompleteContextFetching";
8+import { createDiff, DiffFormatType } from "./diffFormatting";
9+import {
10+ getPrevEditsDescending,
11+ prevEdit,
12+ prevEditLruCache,
13+ setPrevEdit,
14+} from "./prevEditLruCache";
15+
16+const randomNumberBetween = (min: number, max: number) => {
17+ min = Math.ceil(min); // Ensure min is an integer
18+ max = Math.floor(max); // Ensure max is an integer
19+ return Math.floor(Math.random() * (max - min + 1)) + min;
20+};
21+
22+interface ProcessNextEditDataParams {
23+ filePath: string;
24+ beforeContent: string;
25+ afterContent: string;
26+ cursorPosBeforeEdit: Position;
27+ cursorPosAfterPrevEdit: Position;
28+ ide: IDE;
29+ configHandler: ConfigHandler;
30+ getDefinitionsFromLsp: GetLspDefinitionsFunction;
31+ recentlyEditedRanges: RecentlyEditedRange[];
32+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
33+ workspaceDir: string;
34+ modelNameOrInstance?: string | undefined;
35+}
36+
37+interface filenameAndDiff {
38+ filename: string;
39+ diff: string;
40+}
41+
42+export const processNextEditData = async ({
43+ filePath,
44+ beforeContent,
45+ afterContent,
46+ cursorPosBeforeEdit,
47+ cursorPosAfterPrevEdit,
48+ ide,
49+ configHandler,
50+ getDefinitionsFromLsp,
51+ recentlyEditedRanges,
52+ recentlyVisitedRanges,
53+ workspaceDir,
54+ modelNameOrInstance,
55+}: ProcessNextEditDataParams) => {
56+ // To switch to the user's autocomplete model, uncomment the following lines
57+ // const { config } = await configHandler.loadConfig();
58+ // const autocompleteModel =
59+ // (modelNameOrInstance || config?.selectedModelByRole.autocomplete) ??
60+ // undefined;
61+
62+ const modelName = "Codestral";
63+ const maxPromptTokens = randomNumberBetween(500, 12000);
64+
65+ const autocompleteContext = await getAutocompleteContext(
66+ filePath,
67+ cursorPosBeforeEdit,
68+ ide,
69+ configHandler,
70+ getDefinitionsFromLsp,
71+ recentlyEditedRanges,
72+ recentlyVisitedRanges,
73+ maxPromptTokens,
74+ beforeContent,
75+ modelName,
76+ );
77+
78+ // console.log(
79+ // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
80+ // );
81+
82+ let filenamesAndDiffs: filenameAndDiff[] = [];
83+
84+ const timestamp = Date.now();
85+ let prevEdits: prevEdit[] = getPrevEditsDescending(); // edits from most to least recent
86+ if (prevEdits.length > 0) {
87+ // if last edit was 10+ minutes ago or the workspace changed, forget previous edits
88+ if (
89+ timestamp - prevEdits[0].timestamp >= 1000 * 60 * 10 ||
90+ workspaceDir !== prevEdits[0].workspaceUri
91+ ) {
92+ prevEditLruCache.clear();
93+ prevEdits = [];
94+ }
95+
96+ // extract filenames and diffs for logging
97+ filenamesAndDiffs = prevEdits.map(
98+ (edit) =>
99+ ({
100+ // filename relative to workspace dir
101+ filename: edit.fileUri
102+ .replace(edit.workspaceUri, "")
103+ .replace(/^[/\\]/, ""),
104+
105+ // diff without the first 4 lines (the file header)
106+ diff: edit.unidiff.split("\n").slice(4).join("\n"),
107+ }) as filenameAndDiff,
108+ );
109+ }
110+
111+ if (filenamesAndDiffs.length > 0) {
112+ // if there are previous edits, log
113+ void DataLogger.getInstance().logDevData({
114+ name: "nextEditWithHistory",
115+ data: {
116+ previousEdits: filenamesAndDiffs,
117+ fileURI: filePath,
118+ workspaceDirURI: workspaceDir,
119+ beforeContent,
120+ afterContent,
121+ beforeCursorPos: cursorPosBeforeEdit,
122+ afterCursorPos: cursorPosAfterPrevEdit,
123+ context: autocompleteContext,
124+ },
125+ });
126+ }
127+
128+ // add current edit to history
129+ const thisEdit: prevEdit = {
130+ unidiff: createDiff({
131+ beforeContent: beforeContent,
132+ afterContent: afterContent,
133+ filePath: filePath,
134+ diffType: DiffFormatType.Unified,
135+ contextLines: 25, // storing many context lines for downstream trimming
136+ }),
137+ fileUri: filePath,
138+ workspaceUri: workspaceDir,
139+ timestamp: timestamp,
140+ };
141+
142+ setPrevEdit(thisEdit);
143+};
added core/nextEdit/context/processSmallEdit.ts +49 −0
@@ -0,0 +1,49 @@
1+import { IDE, Position } from "../..";
2+import { GetLspDefinitionsFunction } from "../../autocomplete/types";
3+import { ConfigHandler } from "../../config/ConfigHandler";
4+import { NextEditProvider } from "../NextEditProvider";
5+import { EditAggregator } from "./aggregateEdits";
6+import { BeforeAfterDiff, createDiff, DiffFormatType } from "./diffFormatting";
7+import { processNextEditData } from "./processNextEditData";
8+
9+export const processSmallEdit = async (
10+ beforeAfterdiff: BeforeAfterDiff,
11+ cursorPosBeforeEdit: Position,
12+ cursorPosAfterPrevEdit: Position,
13+ configHandler: ConfigHandler,
14+ getDefsFromLspFunction: GetLspDefinitionsFunction,
15+ ide: IDE,
16+) => {
17+ NextEditProvider.getInstance().addDiffToContext(
18+ createDiff({
19+ beforeContent: beforeAfterdiff.beforeContent,
20+ afterContent: beforeAfterdiff.afterContent,
21+ filePath: beforeAfterdiff.filePath,
22+ diffType: DiffFormatType.Unified,
23+ contextLines: 3, // NOTE: This can change depending on experiments!
24+ }),
25+ );
26+
27+ // Get the current context data from the most recent message
28+ const currentData = (EditAggregator.getInstance() as any)
29+ .latestContextData || {
30+ configHandler: configHandler,
31+ getDefsFromLspFunction: getDefsFromLspFunction,
32+ recentlyEditedRanges: [],
33+ recentlyVisitedRanges: [],
34+ };
35+
36+ void processNextEditData({
37+ filePath: beforeAfterdiff.filePath,
38+ beforeContent: beforeAfterdiff.beforeContent,
39+ afterContent: beforeAfterdiff.afterContent,
40+ cursorPosBeforeEdit: cursorPosBeforeEdit,
41+ cursorPosAfterPrevEdit: cursorPosAfterPrevEdit,
42+ ide: ide,
43+ configHandler: currentData.configHandler,
44+ getDefinitionsFromLsp: currentData.getDefsFromLspFunction,
45+ recentlyEditedRanges: currentData.recentlyEditedRanges,
46+ recentlyVisitedRanges: currentData.recentlyVisitedRanges,
47+ workspaceDir: currentData.workspaceDir,
48+ });
49+};
added core/nextEdit/diff/diff.ts +194 −0
@@ -0,0 +1,194 @@
1+import { DiffLine } from "../..";
2+
3+/**
4+ * Given a diff of two editable regions, get the offset position at the last new line inside the editable region.
5+ * @param diffLines Result of myersDiff.
6+ * @param lineContentAtCursorPos Content of the line at cursor position.
7+ * @param lineOffsetAtCursorPos Offset of the line at cursor position compared to the start of the editable region.
8+ * @returns Offset position at last new line inside the editable region.
9+ */
10+export function getOffsetPositionAtLastNewLine(
11+ diffLines: DiffLine[],
12+ lineContentAtCursorPos: string,
13+ lineOffsetAtCursorPos: number,
14+): {
15+ line: number;
16+ character: number;
17+} {
18+ let lastNewLineContent = "";
19+ let lineOffset = -1;
20+ let currentResultLine = 0;
21+ let hasChanges = false;
22+
23+ // Build the string while tracking line numbers in the result
24+ diffLines.reduce((acc, curr, i) => {
25+ // Add the current line to our result
26+ acc += curr.line;
27+
28+ // Add newline if not the last line
29+ if (i < diffLines.length - 1) {
30+ acc += "\n";
31+ }
32+
33+ // If this is a "new" or "same" line, it will be part of the result
34+ if (curr.type === "new" || curr.type === "same") {
35+ if (curr.type === "new") {
36+ // If it's a new line, update our tracking
37+ lastNewLineContent = curr.line;
38+ lineOffset = currentResultLine;
39+ hasChanges = true;
40+ }
41+ // Increment our position in the result
42+ currentResultLine++;
43+ }
44+
45+ return acc;
46+ }, "");
47+
48+ // If nothing has changed, return the original position
49+ if (!hasChanges) {
50+ lineOffset = lineOffsetAtCursorPos;
51+ lastNewLineContent = lineContentAtCursorPos;
52+ }
53+ // Calculate the character position for the end of the last relevant line
54+ const endOfCharPos = lastNewLineContent.length;
55+ return {
56+ line: lineOffset,
57+ character: endOfCharPos,
58+ };
59+}
60+
61+export function getRenderableDiffWithGutterAnnotations(
62+ diffLines: DiffLine[],
63+ lineContentAtCursorPos: string,
64+ lineOffsetAtCursorPos: number,
65+): {
66+ offset: {
67+ line: number;
68+ character: number;
69+ };
70+} {
71+ let lastNewLineContent = "";
72+ let lineOffset = -1;
73+ let currentResultLine = 0;
74+ let hasChanges = false;
75+
76+ // Build the string while tracking line numbers in the result
77+ diffLines.reduce((acc, curr, i) => {
78+ // Add the current line to our result
79+ acc += curr.line;
80+
81+ // Add newline if not the last line
82+ if (i < diffLines.length - 1) {
83+ acc += "\n";
84+ }
85+
86+ // If this is a "new" or "same" line, it will be part of the result
87+ if (curr.type === "new" || curr.type === "same") {
88+ if (curr.type === "new") {
89+ // If it's a new line, update our tracking
90+ lastNewLineContent = curr.line;
91+ lineOffset = currentResultLine;
92+ hasChanges = true;
93+ }
94+ // Increment our position in the result
95+ currentResultLine++;
96+ }
97+
98+ return acc;
99+ }, "");
100+
101+ // If nothing has changed, return the original position
102+ if (!hasChanges) {
103+ lineOffset = lineOffsetAtCursorPos;
104+ lastNewLineContent = lineContentAtCursorPos;
105+ }
106+ // Calculate the character position for the end of the last relevant line
107+ const endOfCharPos = lastNewLineContent.length;
108+ return {
109+ offset: {
110+ line: lineOffset,
111+ character: endOfCharPos,
112+ },
113+ };
114+}
115+
116+/**
117+ * Check if the diff is indeed a FIM.
118+ * @param oldEditRange Original string content.
119+ * @param newEditRange New string content.
120+ * @param cursorPosition The position of the cursor in the old string.
121+ * @returns boolean indicating if the change is purely additive (FIM)
122+ * @returns string of FIM text content.
123+ */
124+export function checkFim(
125+ oldEditRange: string,
126+ newEditRange: string,
127+ cursorPosition: { line: number; character: number },
128+):
129+ | {
130+ isFim: true;
131+ fimText: string;
132+ }
133+ | {
134+ isFim: false;
135+ fimText: null;
136+ } {
137+ // Find the common prefix.
138+ let prefixLength = 0;
139+ while (
140+ prefixLength < oldEditRange.length &&
141+ prefixLength < newEditRange.length &&
142+ oldEditRange[prefixLength] === newEditRange[prefixLength]
143+ ) {
144+ prefixLength++;
145+ }
146+
147+ // Find the common suffix
148+ let oldSuffixPos = oldEditRange.length - 1;
149+ let newSuffixPos = newEditRange.length - 1;
150+
151+ while (
152+ oldSuffixPos >= prefixLength &&
153+ newSuffixPos >= prefixLength &&
154+ oldEditRange[oldSuffixPos] === newEditRange[newSuffixPos]
155+ ) {
156+ oldSuffixPos--;
157+ newSuffixPos--;
158+ }
159+
160+ // The old text is purely preserved if:
161+ // 1. The prefix ends before or at the cursor.
162+ // 2. The suffix starts after or at the cursor.
163+ // 3. There's no gap between prefix and suffix in the old text.
164+
165+ const suffixStartInOld = oldSuffixPos + 1;
166+ const suffixStartInNew = newSuffixPos + 1;
167+
168+ // Convert cursor position to an offset in the string.
169+ // For simplicity, we need to calculate the cursor's position in the string.
170+ // This requires knowledge of line endings in the oldEditRange.
171+ const lines = oldEditRange.substring(0, prefixLength).split("\n");
172+ const cursorOffset =
173+ lines.length > 1
174+ ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) +
175+ cursorPosition.character
176+ : cursorPosition.character;
177+
178+ // Check if the cursor is positioned between the prefix and suffix.
179+ const cursorBetweenPrefixAndSuffix =
180+ prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld;
181+
182+ // Check if the old text is completely preserved (no deletion).
183+ const noTextDeleted = suffixStartInOld - prefixLength <= 0;
184+
185+ const isFim = cursorBetweenPrefixAndSuffix && noTextDeleted;
186+
187+ if (isFim) {
188+ // Extract the content between prefix and suffix in the new string.
189+ const fimText = newEditRange.substring(prefixLength, suffixStartInNew);
190+ return { isFim, fimText };
191+ } else {
192+ return { isFim, fimText: null };
193+ }
194+}
added core/nextEdit/diff/diff.vitest.ts +92 −0
@@ -0,0 +1,92 @@
1+import { describe, expect, it } from "vitest";
2+import { checkFim } from "./diff";
3+
4+describe("checkFim", () => {
5+ const testCases = [
6+ {
7+ name: "simple insertion at cursor",
8+ oldEditRange: ["function test() {", " ", "}"].join("\n"),
9+ newEditRange: ["function test() {", " console.log('hello');", "}"].join(
10+ "\n",
11+ ),
12+ cursorPosition: { line: 1, character: 2 },
13+ expected: {
14+ isFim: true,
15+ fimText: "console.log('hello');",
16+ },
17+ },
18+ {
19+ name: "not a FIM because insertion starts before { and new suffix is different from {}",
20+ oldEditRange: ["function test() {}"].join("\n"),
21+ newEditRange: ["function test() {console.log('test');}"].join("\n"),
22+ cursorPosition: { line: 0, character: 16 },
23+ expected: {
24+ isFim: false,
25+ fimText: null,
26+ },
27+ },
28+ {
29+ name: "insertion with cursor at beginning",
30+ oldEditRange: ["function test() {}"].join("\n"),
31+ newEditRange: ["function test() {console.log('test');}"].join("\n"),
32+ cursorPosition: { line: 0, character: 17 },
33+ expected: {
34+ isFim: true,
35+ fimText: "console.log('test');",
36+ },
37+ },
38+ {
39+ name: "not a FIM because text was deleted",
40+ oldEditRange: ["function test() {", " return 42;", "}"].join("\n"),
41+ newEditRange: ["function test() {", " console.log('hello');", "}"].join(
42+ "\n",
43+ ),
44+ cursorPosition: { line: 1, character: 2 },
45+ expected: {
46+ isFim: false,
47+ fimText: null,
48+ },
49+ },
50+ {
51+ name: "not a FIM because text was changed before cursor",
52+ oldEditRange: ["let x = 1;"].join("\n"),
53+ newEditRange: ["const x = 1; // initialized x"].join("\n"),
54+ cursorPosition: { line: 0, character: 8 },
55+ expected: {
56+ isFim: false,
57+ fimText: null,
58+ },
59+ },
60+ {
61+ name: "multi-line insertion at cursor",
62+ oldEditRange: [
63+ "function process() {",
64+ " ",
65+ " return result;",
66+ "}",
67+ ].join("\n"),
68+ newEditRange: [
69+ "function process() {",
70+ " const data = fetchData();",
71+ " const result = processData(data);",
72+ " return result;",
73+ "}",
74+ ].join("\n"),
75+ cursorPosition: { line: 1, character: 2 },
76+ expected: {
77+ isFim: true,
78+ fimText:
79+ "const data = fetchData();\n const result = processData(data);",
80+ },
81+ },
82+ ];
83+
84+ testCases.forEach(
85+ ({ name, oldEditRange, newEditRange, cursorPosition, expected }) => {
86+ it(name, () => {
87+ const result = checkFim(oldEditRange, newEditRange, cursorPosition);
88+ expect(result).toEqual(expected);
89+ });
90+ },
91+ );
92+});
added core/nextEdit/templating/NextEditPromptEngine.ts +336 −0
@@ -0,0 +1,336 @@
1+import Handlebars from "handlebars";
2+import { Position } from "../..";
3+import { SnippetPayload } from "../../autocomplete/snippets";
4+import { HelperVars } from "../../autocomplete/util/HelperVars";
5+import {
6+ EDITABLE_REGION_END_TOKEN,
7+ EDITABLE_REGION_START_TOKEN,
8+ NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
9+ NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
10+ USER_CURSOR_IS_HERE_TOKEN,
11+} from "../constants";
12+import {
13+ NextEditTemplate,
14+ PromptMetadata,
15+ SystemPrompt,
16+ TemplateVars,
17+ UserPrompt,
18+} from "../types";
19+
20+type TemplateRenderer = (vars: TemplateVars) => string;
21+
22+type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
23+
24+const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
25+ "mercury-coder-nextedit": {
26+ template:
27+ "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
28+ },
29+ "this field is not used": {
30+ template: "NEXT_EDIT",
31+ },
32+};
33+
34+function templateRendererOfModel(
35+ modelName: NextEditModelName,
36+): TemplateRenderer {
37+ let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
38+ if (!template) {
39+ throw new Error(`Model ${modelName} is not supported for next edit.`);
40+ }
41+
42+ const compiledTemplate = Handlebars.compile(template.template);
43+
44+ return (vars: TemplateVars): string => {
45+ return compiledTemplate(vars);
46+ };
47+}
48+
49+export function renderPrompt(
50+ helper: HelperVars,
51+ userEdits: string,
52+): PromptMetadata {
53+ let modelName = helper.modelName as NextEditModelName;
54+
55+ if (modelName === "this field is not used") {
56+ return {
57+ prompt: {
58+ role: "user",
59+ content: "NEXT_EDIT",
60+ },
61+ userEdits,
62+ userExcerpts: helper.fileContents,
63+ };
64+ }
65+
66+ // Validate that the modelName is actually a supported model.
67+ if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
68+ // Check if modelName includes any known model name as substring.
69+ const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
70+ modelName.includes(key),
71+ );
72+
73+ if (matchingModel) {
74+ modelName = matchingModel as NextEditModelName;
75+ } else {
76+ throw new Error(
77+ `${helper.modelName} is not yet supported for next edit.`,
78+ );
79+ }
80+ }
81+
82+ const renderer = templateRendererOfModel(modelName);
83+ const editedCodeWithTokens = insertTokens(
84+ helper.fileContents.split("\n"),
85+ helper.pos,
86+ );
87+
88+ const tv: TemplateVars = {
89+ userEdits,
90+ languageShorthand: helper.lang.name,
91+ userExcerpts: editedCodeWithTokens,
92+ };
93+
94+ return {
95+ prompt: {
96+ role: "user",
97+ content: renderer(tv),
98+ },
99+ userEdits,
100+ userExcerpts: editedCodeWithTokens,
101+ };
102+}
103+
104+export function renderDefaultSystemPrompt(): SystemPrompt {
105+ return {
106+ role: "system",
107+ content: [
108+ /* Identity forming */
109+ "You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
110+ "You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
111+ "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
112+ /* Action crash course */
113+ "An action is a change in code state that preserves the well-formedness of the code.",
114+ "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
115+ /* Input description */
116+ // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
117+ // "language is the language the code is written in.",
118+ // "originalCode is the code state before the junior has taken some edit action.",
119+ // "editedCode is the code state after the junior has taken some edit action.",
120+ // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
121+ // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
122+ 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
123+ "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
124+ "recentlyEditedRange is the code that the junior has recently edited.",
125+ "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
126+ "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
127+ "The junior might want to add new code, delete existing code, or replace different parts of code.",
128+ "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
129+ /* Output description */
130+ 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
131+ /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
132+ /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
133+ "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
134+ // "actionType is the type of action the junior has taken.",
135+ "newCode is what the full code looks like after applying your nextEditContent.",
136+ // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
137+ "Given the above definition of an action, you should prioritize fixing the following:",
138+ "- Patterns and repetition in code.",
139+ "- Static errors that the compiler of the language may return.",
140+ "- The junior's code style.",
141+ "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
142+ "If the junior has added some code, there's a good chance that the next edit will also be additions.",
143+ "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
144+ "Careful of language intricacies.",
145+ // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
146+ "Do not reply in markdown.",
147+ "Do not hallucinate.",
148+ ].join(" "),
149+ };
150+}
151+
152+export function renderDefaultUserPrompt(
153+ // originalCode: string,
154+ // editedCode: string,
155+ snippets: SnippetPayload,
156+ helper: HelperVars,
157+): UserPrompt {
158+ const userEdit = {
159+ language: helper.lang,
160+ rootPathSnippets: snippets.rootPathSnippets,
161+ importDefinitionSnippets: snippets.importDefinitionSnippets,
162+ ideSnippets: snippets.ideSnippets,
163+ recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
164+ diffSnippets: snippets.diffSnippets,
165+ clipboardSnippets: snippets.clipboardSnippets,
166+ recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
167+ };
168+
169+ return {
170+ role: "user",
171+ content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
172+ };
173+}
174+
175+// export async function renderFineTunedUserPrompt(
176+// snippets: SnippetPayload,
177+// ide: IDE,
178+// helper: HelperVars,
179+// ): Promise<UserPrompt> {
180+// const ideInfo = await ide.getIdeInfo();
181+// switch (ideInfo.ideType) {
182+// case "vscode":
183+// const editedCodeWithPins = insertTokens(
184+// helper.fileContents.split("\n"),
185+// helper.pos,
186+// );
187+
188+// return {
189+// role: "user",
190+// content: renderStringTemplate(
191+// mercuryCoderTemplate,
192+// snippets.diffSnippets.join("\n"),
193+// helper.lang.name,
194+// editedCodeWithPins,
195+// ),
196+// };
197+
198+// case "jetbrains":
199+// return {
200+// role: "user",
201+// content: "",
202+// };
203+// }
204+// }
205+
206+// export async function renderDefaultBasicUserPrompt(
207+// snippets: SnippetPayload,
208+// ide: IDE,
209+// helper: HelperVars,
210+// ): Promise<UserPrompt> {
211+// const ideInfo = await ide.getIdeInfo();
212+// switch (ideInfo.ideType) {
213+// case "vscode":
214+// const editedCodeWithPins = insertTokens(
215+// helper.fileContents.split("\n"),
216+// helper.pos,
217+// );
218+
219+// return {
220+// role: "user",
221+// content: renderStringTemplate(
222+// mercuryCoderTemplate,
223+// JSON.stringify(snippets),
224+// helper.lang.name,
225+// editedCodeWithPins,
226+// ),
227+// };
228+
229+// case "jetbrains":
230+// return {
231+// role: "user",
232+// content: "",
233+// };
234+// }
235+// }
236+
237+// export async function renderFineTunedBasicUserPrompt(
238+// snippets: SnippetPayload,
239+// ide: IDE,
240+// helper: HelperVars,
241+// diffContext: string,
242+// ): Promise<UserPrompt> {
243+// const ideInfo = await ide.getIdeInfo();
244+// switch (ideInfo.ideType) {
245+// case "vscode":
246+// const lines = helper.fileContents.split("\n");
247+// const editedCodeWithPins = insertTokens(lines, helper.pos);
248+
249+// return {
250+// role: "user",
251+// content: renderStringTemplate(
252+// mercuryCoderTemplate,
253+// diffContext,
254+// helper.lang.name,
255+// editedCodeWithPins,
256+// ),
257+// };
258+
259+// case "jetbrains":
260+// return {
261+// role: "user",
262+// content: "",
263+// };
264+// }
265+// }
266+
267+function insertTokens(lines: string[], cursorPos: Position) {
268+ const a = insertCursorToken(lines, cursorPos);
269+ const b = insertEditableRegionTokensWithStaticRange(a, cursorPos);
270+ return b.join("\n");
271+}
272+
273+function insertCursorToken(lines: string[], cursorPos: Position) {
274+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
275+ return lines;
276+ }
277+
278+ // Ensure character position is within bounds or at the end of the line.
279+ const lineLength = lines[cursorPos.line].length;
280+ const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
281+
282+ lines[cursorPos.line] =
283+ lines[cursorPos.line].slice(0, charPos) +
284+ USER_CURSOR_IS_HERE_TOKEN +
285+ lines[cursorPos.line].slice(charPos);
286+
287+ return lines;
288+}
289+
290+function insertEditableRegionTokensWithStaticRange(
291+ lines: string[],
292+ cursorPos: Position,
293+) {
294+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
295+ return lines;
296+ }
297+
298+ // Ensure editable regions are within bounds.
299+ const editableRegionStart = Math.max(
300+ cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
301+ 0,
302+ );
303+ const editableRegionEnd = Math.min(
304+ cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
305+ lines.length - 1, // Line numbers should be zero-indexed.
306+ );
307+
308+ const instrumentedLines = [
309+ ...lines.slice(0, editableRegionStart),
310+ EDITABLE_REGION_START_TOKEN,
311+ ...lines.slice(editableRegionStart, editableRegionEnd + 1),
312+ EDITABLE_REGION_END_TOKEN,
313+ ...lines.slice(editableRegionEnd + 1),
314+ ];
315+
316+ return instrumentedLines;
317+}
318+
319+function insertEditableRegionTokensWithAst(
320+ lines: string[],
321+ cursorPos: Position,
322+) {
323+ if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
324+ return lines;
325+ }
326+
327+ // Ensure character position is within bounds or at the end of the line.
328+ const lineLength = lines[cursorPos.line].length;
329+ const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
330+
331+ (lines[cursorPos.line] =
332+ lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN),
333+ lines[cursorPos.line].slice(charPos);
334+
335+ return lines;
336+}
added core/nextEdit/types.ts +85 −0
@@ -0,0 +1,85 @@
1+import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../";
2+import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
3+
4+export type RecentlyEditedRange = RangeInFile & {
5+ timestamp: number;
6+ lines: string[];
7+ symbols: Set<string>;
8+};
9+
10+export interface AutocompleteInput {
11+ isUntitledFile: boolean;
12+ completionId: string;
13+ filepath: string;
14+ pos: Position;
15+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
16+ recentlyEditedRanges: RecentlyEditedRange[];
17+ // Used for notebook files
18+ manuallyPassFileContents?: string;
19+ // Used for VS Code git commit input box
20+ manuallyPassPrefix?: string;
21+ selectedCompletionInfo?: {
22+ text: string;
23+ range: Range;
24+ };
25+ injectDetails?: string;
26+}
27+
28+export interface NextEditOutcome extends TabAutocompleteOptions {
29+ // Originally from Autocomplete.
30+ // accepted?: boolean;
31+ elapsed: number;
32+ // prefix: string;
33+ // suffix: string;
34+ // prompt: string;
35+ // completion: string;
36+ modelProvider: string;
37+ modelName: string;
38+ completionOptions: any;
39+ // cacheHit: boolean;
40+ // numLines: number;
41+ // filepath: string;
42+ completionId: string;
43+ gitRepo?: string;
44+ uniqueId: string;
45+ timestamp: number;
46+
47+ // New for Next Edit.
48+ fileUri: string;
49+ workspaceDirUri: string;
50+ prompt: string;
51+ userEdits: string;
52+ userExcerpts: string;
53+ originalEditableRange: string;
54+ completion: string;
55+ cursorPosition: { line: number; character: number };
56+ accepted?: boolean;
57+}
58+
59+export interface PromptMetadata {
60+ prompt: UserPrompt;
61+ userEdits: string;
62+ userExcerpts: string;
63+}
64+
65+export type Prompt = SystemPrompt | UserPrompt;
66+
67+export interface SystemPrompt {
68+ role: "system";
69+ content: string;
70+}
71+
72+export interface UserPrompt {
73+ role: "user";
74+ content: string;
75+}
76+
77+export interface NextEditTemplate {
78+ template: string;
79+}
80+
81+export interface TemplateVars {
82+ userEdits: string;
83+ languageShorthand: string;
84+ userExcerpts: string;
85+}
modified core/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified core/package.json +5 −2
@@ -18,6 +18,8 @@
1818 "@babel/preset-env": "^7.24.7",
1919 "@biomejs/biome": "1.6.4",
2020 "@google/generative-ai": "^0.11.4",
21+ "@shikijs/colorized-brackets": "^3.7.0",
22+ "@shikijs/transformers": "^3.7.0",
2123 "@types/diff": "^7.0.1",
2224 "@types/follow-redirects": "^1.14.4",
2325 "@types/jest": "^29.5.12",
@@ -41,6 +43,7 @@
4143 "myers-diff": "^2.1.0",
4244 "onnxruntime-common": "1.14.0",
4345 "onnxruntime-web": "1.14.0",
46+ "shiki": "^3.6.0",
4447 "ts-jest": "^29.1.1",
4548 "typescript": "^5.6.3",
4649 "vitest": "^3.1.4"
@@ -51,9 +54,9 @@
5154 "@aws-sdk/credential-providers": "^3.778.0",
5255 "@continuedev/config-types": "^1.0.13",
5356 "@continuedev/config-yaml": "file:../packages/config-yaml",
54- "@continuedev/fetch": "^1.0.13",
57+ "@continuedev/fetch": "^1.0.14",
5558 "@continuedev/llm-info": "^1.0.8",
56- "@continuedev/openai-adapters": "^1.0.32",
59+ "@continuedev/openai-adapters": "file:../packages/openai-adapters",
5760 "@modelcontextprotocol/sdk": "^1.12.0",
5861 "@mozilla/readability": "^0.5.0",
5962 "@octokit/rest": "^20.1.1",
added core/promptFiles/createNewPromptFile.ts +76 −0
@@ -0,0 +1,76 @@
1+import { IDE } from "..";
2+import { GlobalContext } from "../util/GlobalContext";
3+import { joinPathsToUri } from "../util/uri";
4+
5+const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
6+# It is used to define and reuse prompts within Continue
7+# Each .prompt file can be accessed by typing "@prompts" in the Chat input
8+
9+# A prompt file consists of two parts:
10+# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
11+# 2. Everything below the "---" is the prompt body
12+
13+# If you do not want to set any options, you do not need to include the "---"
14+
15+# In the body, you can reference:
16+# 1. Files, using either absolute or relative paths (based on the workspace root)
17+ # @README.md
18+ # @src/test/test.py
19+ # @/Users/me/Desktop/my-project/src/test/test.py
20+# 2. URLs, for example
21+ # @https://example.com
22+# 3. Context providers, for example
23+ # @currentFile
24+ # @os
25+ # @repo-map
26+
27+# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
28+name: Example
29+description: Example prompt file
30+---
31+
32+Here is information about the current repo:
33+
34+@README.md`;
35+
36+const DEFAULT_PROMPT_FILE = "";
37+
38+export async function createNewPromptFileV2(
39+ ide: IDE,
40+ promptPath: string | undefined,
41+): Promise<void> {
42+ const workspaceDirs = await ide.getWorkspaceDirs();
43+ if (workspaceDirs.length === 0) {
44+ throw new Error(
45+ "No workspace directories found. Make sure you've opened a folder in your IDE.",
46+ );
47+ }
48+
49+ const baseDirUri = joinPathsToUri(
50+ workspaceDirs[0],
51+ promptPath ?? ".continue/prompts",
52+ );
53+
54+ // Find the first available filename
55+ let counter = 0;
56+ let promptFileUri: string;
57+ do {
58+ const suffix = counter === 0 ? "" : `-${counter}`;
59+ promptFileUri = joinPathsToUri(
60+ baseDirUri,
61+ `new-prompt-file${suffix}.prompt`,
62+ );
63+ counter++;
64+ } while (await ide.fileExists(promptFileUri));
65+
66+ const globalContext = new GlobalContext();
67+ const PROMPT_FILE =
68+ globalContext.get("hasAlreadyCreatedAPromptFile") === true
69+ ? DEFAULT_PROMPT_FILE
70+ : FIRST_TIME_DEFAULT_PROMPT_FILE;
71+
72+ globalContext.update("hasAlreadyCreatedAPromptFile", true);
73+
74+ await ide.writeFile(promptFileUri, PROMPT_FILE);
75+ await ide.openFile(promptFileUri);
76+}
added core/promptFiles/getPromptFiles.ts +152 −0
@@ -0,0 +1,152 @@
1+import { DEFAULT_PROMPTS_FOLDER_V1 } from ".";
2+import { IDE } from "..";
3+import { walkDir } from "../indexing/walkDir";
4+import { readAllGlobalPromptFiles } from "../util/paths";
5+import { joinPathsToUri } from "../util/uri";
6+
7+// The hardcoded init prompt content
8+const INIT_PROMPT_CONTENT = `name: Init
9+description: Initialize Codebase
10+---
11+You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
12+
13+## Step 1: Check Required Tools
14+First, verify that you have access to the necessary tools:
15+- builtin_file_glob_search: To discover project files
16+- builtin_read_file: To analyze file contents
17+- builtin_ls: To explore directory structure
18+- builtin_create_new_file: To generate the CONTINUE.md file
19+
20+If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
21+
22+## Step 2: Project Analysis
23+Analyze the project structure and key files to understand:
24+- The programming languages and frameworks used
25+- The overall architecture and organization
26+- Key components and their responsibilities
27+- Important configuration files
28+- Build/deployment system
29+
30+## Step 3: Generate CONTINUE.md
31+Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
32+
33+1. **Project Overview**
34+ - Brief description of the project's purpose
35+ - Key technologies used
36+ - High-level architecture
37+
38+2. **Getting Started**
39+ - Prerequisites (required software, dependencies)
40+ - Installation instructions
41+ - Basic usage examples
42+ - Running tests
43+
44+3. **Project Structure**
45+ - Overview of main directories and their purpose
46+ - Key files and their roles
47+ - Important configuration files
48+
49+4. **Development Workflow**
50+ - Coding standards or conventions
51+ - Testing approach
52+ - Build and deployment process
53+ - Contribution guidelines
54+
55+5. **Key Concepts**
56+ - Domain-specific terminology
57+ - Core abstractions
58+ - Design patterns used
59+
60+6. **Common Tasks**
61+ - Step-by-step guides for frequent development tasks
62+ - Examples of common operations
63+
64+7. **Troubleshooting**
65+ - Common issues and their solutions
66+ - Debugging tips
67+
68+8. **References**
69+ - Links to relevant documentation
70+ - Important resources
71+
72+Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
73+
74+## Step 4: Finalize
75+After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
76+1. Review and edit the file as needed
77+2. Commit it to their repository to share with their team
78+3. Explain that Continue will automatically load this file into context when working with the project
79+
80+Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
81+
82+export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
83+
84+export async function getPromptFilesFromDir(
85+ ide: IDE,
86+ dir: string,
87+): Promise<{ path: string; content: string }[]> {
88+ try {
89+ const exists = await ide.fileExists(dir);
90+
91+ if (!exists) {
92+ return [];
93+ }
94+
95+ const uris = await walkDir(dir, ide, {
96+ source: "get dir prompt files",
97+ });
98+ const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
99+ const results = promptFilePaths.map(async (uri) => {
100+ const content = await ide.readFile(uri); // make a try catch
101+ return { path: uri, content };
102+ });
103+ return Promise.all(results);
104+ } catch (e) {
105+ console.error(e);
106+ return [];
107+ }
108+}
109+
110+export async function getAllPromptFiles(
111+ ide: IDE,
112+ overridePromptFolder?: string,
113+ checkV1DefaultFolder: boolean = false,
114+): Promise<{ path: string; content: string }[]> {
115+ const workspaceDirs = await ide.getWorkspaceDirs();
116+ let promptFiles: { path: string; content: string }[] = [];
117+
118+ let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
119+ if (checkV1DefaultFolder) {
120+ dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
121+ }
122+ if (overridePromptFolder) {
123+ dirsToCheck = [overridePromptFolder];
124+ }
125+
126+ const fullDirs = workspaceDirs
127+ .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
128+ .flat();
129+
130+ promptFiles = (
131+ await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
132+ ).flat();
133+
134+ // Also read from ~/.continue/.prompts
135+ promptFiles.push(...readAllGlobalPromptFiles());
136+
137+ // Add hardcoded init prompt
138+ promptFiles.push({
139+ path: "builtin:/init.prompt",
140+ content: INIT_PROMPT_CONTENT,
141+ });
142+
143+ return await Promise.all(
144+ promptFiles.map(async (file) => {
145+ if (file.path.startsWith("builtin:")) {
146+ return file;
147+ }
148+ const content = await ide.readFile(file.path);
149+ return { path: file.path, content };
150+ }),
151+ );
152+}
added core/promptFiles/index.ts +19 −0
@@ -0,0 +1,19 @@
1+import { ContextProviderName } from "..";
2+
3+export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
4+export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
5+
6+export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
7+ "file",
8+ "clipboard",
9+ "repo-map",
10+ "currentFile",
11+ "os",
12+ "problems",
13+ "codebase",
14+ "tree",
15+ "open",
16+ "debugger",
17+ "terminal",
18+ "diff",
19+];
added core/promptFiles/parsePromptFile.ts +24 −0
@@ -0,0 +1,24 @@
1+import * as YAML from "yaml";
2+
3+import { getLastNPathParts } from "../util/uri";
4+
5+export function parsePromptFile(path: string, content: string) {
6+ let [preambleRaw, prompt] = content.split("\n---\n");
7+ if (prompt === undefined) {
8+ prompt = preambleRaw;
9+ preambleRaw = "";
10+ }
11+
12+ const preamble = YAML.parse(preambleRaw) ?? {};
13+ const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14+ const description = preamble.description ?? name;
15+ const version = preamble.version ?? 2;
16+
17+ let systemMessage: string | undefined = undefined;
18+ if (prompt.includes("<system>")) {
19+ systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
20+ prompt = prompt.split("</system>")[1].trim();
21+ }
22+
23+ return { name, description, systemMessage, prompt, version };
24+}
deleted core/promptFiles/v1/getContextProviderHelpers.ts +0 −38
@@ -1,38 +0,0 @@
1-import Handlebars from "handlebars";
2-import { ContextItem, ContinueSDK, IContextProvider } from "../..";
3-
4-function createContextItem(item: ContextItem, provider: IContextProvider) {
5- return {
6- ...item,
7- id: {
8- itemId: item.description,
9- providerTitle: provider.description.title,
10- },
11- };
12-}
13-
14-export function getContextProviderHelpers(
15- context: ContinueSDK,
16-): Array<[string, Handlebars.HelperDelegate]> | undefined {
17- return context.config.contextProviders?.map((provider: IContextProvider) => [
18- provider.description.title,
19- async (helperContext: any) => {
20- const items = await provider.getContextItems(helperContext, {
21- config: context.config,
22- embeddingsProvider: context.config.selectedModelByRole.embed,
23- fetch: context.fetch,
24- fullInput: context.input,
25- ide: context.ide,
26- llm: context.llm,
27- reranker: context.config.selectedModelByRole.rerank,
28- selectedCode: context.selectedCode,
29- });
30-
31- items.forEach((item) =>
32- context.addContextItem(createContextItem(item, provider)),
33- );
34-
35- return items.map((item) => item.content).join("\n\n");
36- },
37- ]);
38-}
deleted core/promptFiles/v1/handlebarUtils.ts +0 −117
@@ -1,117 +0,0 @@
1-import Handlebars from "handlebars";
2-import { v4 as uuidv4 } from "uuid";
3-
4-function convertToLetter(num: number): string {
5- let result = "";
6- while (num > 0) {
7- const remainder = (num - 1) % 26;
8- result = String.fromCharCode(97 + remainder) + result;
9- num = Math.floor((num - 1) / 26);
10- }
11- return result;
12-}
13-
14-/**
15- * We replace filepaths with alphabetic characters to handle
16- * escaping issues.
17- */
18-const replaceFilepaths = (
19- value: string,
20- ctxProviderNames: string[],
21-): [string, { [key: string]: string }] => {
22- const ast = Handlebars.parse(value);
23-
24- const keysToFilepath: { [key: string]: string } = {};
25-
26- let keyIndex = 1;
27-
28- for (const i in ast.body) {
29- const node = ast.body[i] as any;
30-
31- if (node.type === "MustacheStatement") {
32- const originalNodeVal = node.path.original;
33- const isFilepath = !ctxProviderNames.includes(originalNodeVal);
34-
35- if (isFilepath) {
36- const letter = convertToLetter(keyIndex);
37-
38- keysToFilepath[letter] = originalNodeVal;
39-
40- value = value.replace(
41- new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
42- `{{${letter}}}`,
43- );
44-
45- keyIndex++;
46- }
47- }
48- }
49-
50- return [value, keysToFilepath];
51-};
52-
53-export function registerHelpers(
54- helpers: Array<[string, Handlebars.HelperDelegate]>,
55-): {
56- [key: string]: Promise<string>;
57-} {
58- const promises: { [key: string]: Promise<string> } = {};
59-
60- for (const [name, helper] of helpers) {
61- Handlebars.registerHelper(name, (...args) => {
62- const id = uuidv4();
63- promises[id] = helper(...args);
64- return `__${id}__`;
65- });
66- }
67-
68- return promises;
69-}
70-
71-export async function prepareTemplateAndData(
72- template: string,
73- readFile: (filepath: string) => Promise<string>,
74- inputData: Record<string, string>,
75- ctxProviderNames: string[],
76-): Promise<[string, any]> {
77- const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
78-
79- const data: any = { ...inputData };
80-
81- for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
82- data[replacedName] =
83- inputData[originalCtxProviderName] ?? originalCtxProviderName;
84-
85- // If it's not a context provider, assume it's a filepath.
86- if (!ctxProviderNames.includes(originalCtxProviderName)) {
87- const fileContents = await readFile(vars[replacedName]);
88-
89- if (fileContents) {
90- data[replacedName] = fileContents;
91- }
92- }
93- }
94-
95- return [newTemplate, data];
96-}
97-
98-export function compileAndRenderTemplate(
99- template: string,
100- data: Record<string, string>,
101-): string {
102- const templateFn = Handlebars.compile(template);
103- return templateFn(data);
104-}
105-
106-export async function resolveHelperPromises(
107- renderedString: string,
108- promises: { [key: string]: Promise<string> },
109-): Promise<string> {
110- await Promise.all(Object.values(promises));
111-
112- for (const id in promises) {
113- renderedString = renderedString.replace(`__${id}__`, await promises[id]);
114- }
115-
116- return renderedString;
117-}
deleted core/promptFiles/v1/index.ts +0 −1
@@ -1,1 +0,0 @@
1-export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
deleted core/promptFiles/v1/renderTemplatedString.ts +0 −30
@@ -1,30 +0,0 @@
1-import {
2- compileAndRenderTemplate,
3- prepareTemplateAndData,
4- registerHelpers,
5- resolveHelperPromises,
6-} from "./handlebarUtils";
7-
8-export async function renderTemplatedString(
9- template: string,
10- readFile: (filepath: string) => Promise<string>,
11- inputData: Record<string, string>,
12- availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
13-): Promise<string> {
14- const helperPromises = availableHelpers
15- ? registerHelpers(availableHelpers)
16- : {};
17-
18- const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
19-
20- const [newTemplate, data] = await prepareTemplateAndData(
21- template,
22- readFile,
23- inputData,
24- ctxProviderNames,
25- );
26-
27- let renderedString = compileAndRenderTemplate(newTemplate, data);
28-
29- return resolveHelperPromises(renderedString, helperPromises);
30-}
deleted core/promptFiles/v1/slashCommandFromPromptFile.ts +0 −89
@@ -1,89 +0,0 @@
1-import { ContinueSDK, SlashCommand } from "../..";
2-import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
3-import { renderChatMessage } from "../../util/messageContent";
4-import { getLastNPathParts } from "../../util/uri";
5-import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
6-import { renderPromptFileV2 } from "../v2/renderPromptFile";
7-
8-import { getContextProviderHelpers } from "./getContextProviderHelpers";
9-import { renderTemplatedString } from "./renderTemplatedString";
10-import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
11-
12-export function extractName(preamble: { name?: string }, path: string): string {
13- return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14-}
15-
16-async function renderPromptV1(
17- prompt: string,
18- context: ContinueSDK,
19- userInput: string,
20-) {
21- const helpers = getContextProviderHelpers(context);
22-
23- const inputData: Record<string, string> = {
24- input: userInput,
25- };
26-
27- // A few context providers that don't need to be in config.json to work in .prompt files
28- if (helpers?.find((helper) => helper[0] === "diff")) {
29- const diffs = await getDiffsFromCache(context.ide);
30- inputData.diff = diffs.join("\n");
31- }
32- if (helpers?.find((helper) => helper[0] === "currentFile")) {
33- const currentFile = await context.ide.getCurrentFile();
34- if (currentFile) {
35- inputData.currentFile = currentFile.path;
36- }
37- }
38-
39- return renderTemplatedString(
40- prompt,
41- context.ide.readFile.bind(context.ide),
42- inputData,
43- helpers,
44- );
45-}
46-
47-export function slashCommandFromPromptFileV1(
48- path: string,
49- content: string,
50-): SlashCommand | null {
51- const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
52- path,
53- content,
54- );
55-
56- return {
57- name,
58- description,
59- prompt,
60- promptFile: path,
61- run: async function* (context) {
62- const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
63- config: context.config,
64- fullInput: context.input,
65- embeddingsProvider: context.config.modelsByRole.embed[0],
66- reranker: context.config.modelsByRole.rerank[0],
67- llm: context.llm,
68- ide: context.ide,
69- selectedCode: context.selectedCode,
70- fetch: context.fetch,
71- });
72-
73- const messages = replaceSlashCommandWithPromptInChatHistory(
74- context.history,
75- name,
76- renderedPrompt,
77- systemMessage,
78- );
79-
80- for await (const chunk of context.llm.streamChat(
81- messages,
82- new AbortController().signal,
83- context.completionOptions,
84- )) {
85- yield renderChatMessage(chunk);
86- }
87- },
88- };
89-}
deleted core/promptFiles/v1/updateChatHistory.ts +0 −64
@@ -1,64 +0,0 @@
1-import { ChatMessage } from "../..";
2-
3-export function replaceSlashCommandWithPromptInChatHistory(
4- history: ChatMessage[],
5- commandName: string,
6- renderedPrompt: string,
7- systemMessageOverride?: string,
8-): ChatMessage[] {
9- const messages = [...history];
10-
11- for (let i = messages.length - 1; i >= 0; i--) {
12- const { role, content } = messages[i];
13- if (role !== "user") {
14- continue;
15- }
16-
17- if (Array.isArray(content)) {
18- if (
19- content.some(
20- (part) =>
21- part.type === "text" && part.text?.startsWith(`/${commandName}`),
22- )
23- ) {
24- messages[i] = updateArrayContent(
25- messages[i],
26- commandName,
27- renderedPrompt,
28- );
29- break;
30- }
31- } else if (
32- typeof content === "string" &&
33- content.startsWith(`/${commandName}`)
34- ) {
35- messages[i] = { ...messages[i], content: renderedPrompt };
36- break;
37- }
38- }
39-
40- if (systemMessageOverride) {
41- if (messages[0]?.role === "system") {
42- messages[0].content = systemMessageOverride;
43- } else {
44- messages.unshift({ role: "system", content: systemMessageOverride });
45- }
46- }
47-
48- return messages;
49-}
50-
51-function updateArrayContent(
52- message: any,
53- commandName: string,
54- renderedPrompt: string,
55-) {
56- return {
57- ...message,
58- content: message.content.map((part: any) =>
59- part.text?.startsWith(`/${commandName}`)
60- ? { ...part, text: renderedPrompt }
61- : part,
62- ),
63- };
64-}
deleted core/promptFiles/v2/createNewPromptFile.ts +0 −76
@@ -1,76 +0,0 @@
1-import { IDE } from "../..";
2-import { GlobalContext } from "../../util/GlobalContext";
3-import { joinPathsToUri } from "../../util/uri";
4-
5-const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
6-# It is used to define and reuse prompts within Continue
7-# Each .prompt file can be accessed by typing "@prompts" in the Chat input
8-
9-# A prompt file consists of two parts:
10-# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
11-# 2. Everything below the "---" is the prompt body
12-
13-# If you do not want to set any options, you do not need to include the "---"
14-
15-# In the body, you can reference:
16-# 1. Files, using either absolute or relative paths (based on the workspace root)
17- # @README.md
18- # @src/test/test.py
19- # @/Users/me/Desktop/my-project/src/test/test.py
20-# 2. URLs, for example
21- # @https://example.com
22-# 3. Context providers, for example
23- # @currentFile
24- # @os
25- # @repo-map
26-
27-# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
28-name: Example
29-description: Example prompt file
30----
31-
32-Here is information about the current repo:
33-
34-@README.md`;
35-
36-const DEFAULT_PROMPT_FILE = "";
37-
38-export async function createNewPromptFileV2(
39- ide: IDE,
40- promptPath: string | undefined,
41-): Promise<void> {
42- const workspaceDirs = await ide.getWorkspaceDirs();
43- if (workspaceDirs.length === 0) {
44- throw new Error(
45- "No workspace directories found. Make sure you've opened a folder in your IDE.",
46- );
47- }
48-
49- const baseDirUri = joinPathsToUri(
50- workspaceDirs[0],
51- promptPath ?? ".continue/prompts",
52- );
53-
54- // Find the first available filename
55- let counter = 0;
56- let promptFileUri: string;
57- do {
58- const suffix = counter === 0 ? "" : `-${counter}`;
59- promptFileUri = joinPathsToUri(
60- baseDirUri,
61- `new-prompt-file${suffix}.prompt`,
62- );
63- counter++;
64- } while (await ide.fileExists(promptFileUri));
65-
66- const globalContext = new GlobalContext();
67- const PROMPT_FILE =
68- globalContext.get("hasAlreadyCreatedAPromptFile") === true
69- ? DEFAULT_PROMPT_FILE
70- : FIRST_TIME_DEFAULT_PROMPT_FILE;
71-
72- globalContext.update("hasAlreadyCreatedAPromptFile", true);
73-
74- await ide.writeFile(promptFileUri, PROMPT_FILE);
75- await ide.openFile(promptFileUri);
76-}
deleted core/promptFiles/v2/getPromptFiles.ts +0 −67
@@ -1,67 +0,0 @@
1-import { IDE } from "../..";
2-import { walkDir } from "../../indexing/walkDir";
3-import { readAllGlobalPromptFiles } from "../../util/paths";
4-import { joinPathsToUri } from "../../util/uri";
5-import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
6-
7-export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
8-export async function getPromptFilesFromDir(
9- ide: IDE,
10- dir: string,
11-): Promise<{ path: string; content: string }[]> {
12- try {
13- const exists = await ide.fileExists(dir);
14-
15- if (!exists) {
16- return [];
17- }
18-
19- const uris = await walkDir(dir, ide, {
20- source: "get dir prompt files",
21- });
22- const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
23- const results = promptFilePaths.map(async (uri) => {
24- const content = await ide.readFile(uri); // make a try catch
25- return { path: uri, content };
26- });
27- return Promise.all(results);
28- } catch (e) {
29- console.error(e);
30- return [];
31- }
32-}
33-
34-export async function getAllPromptFiles(
35- ide: IDE,
36- overridePromptFolder?: string,
37- checkV1DefaultFolder: boolean = false,
38-): Promise<{ path: string; content: string }[]> {
39- const workspaceDirs = await ide.getWorkspaceDirs();
40- let promptFiles: { path: string; content: string }[] = [];
41-
42- let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
43- if (checkV1DefaultFolder) {
44- dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
45- }
46- if (overridePromptFolder) {
47- dirsToCheck = [overridePromptFolder];
48- }
49-
50- const fullDirs = workspaceDirs
51- .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
52- .flat();
53-
54- promptFiles = (
55- await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
56- ).flat();
57-
58- // Also read from ~/.continue/.prompts
59- promptFiles.push(...readAllGlobalPromptFiles());
60-
61- return await Promise.all(
62- promptFiles.map(async (file) => {
63- const content = await ide.readFile(file.path);
64- return { path: file.path, content };
65- }),
66- );
67-}
deleted core/promptFiles/v2/parse.ts +0 −34
@@ -1,34 +0,0 @@
1-import * as YAML from "yaml";
2-
3-import { getLastNPathParts } from "../../util/uri";
4-
5-export function extractName(preamble: { name?: string }, path: string): string {
6- return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
7-}
8-
9-export function getPreambleAndBody(content: string): [string, string] {
10- let [preamble, body] = content.split("\n---\n");
11- if (body === undefined) {
12- // This means there is no preamble
13- body = preamble;
14- preamble = "";
15- }
16- return [preamble, body];
17-}
18-
19-export function parsePreamble(
20- path: string,
21- content: string,
22-): { [key: string]: any; name: string; description: string } {
23- const [preambleRaw, _] = getPreambleAndBody(content);
24-
25- const preamble = YAML.parse(preambleRaw) ?? {};
26- const name = extractName(preamble, path);
27- const description = preamble.description ?? name;
28-
29- return {
30- ...preamble,
31- name,
32- description,
33- };
34-}
deleted core/promptFiles/v2/parsePromptFileV1V2.ts +0 −24
@@ -1,24 +0,0 @@
1-import * as YAML from "yaml";
2-
3-import { getLastNPathParts } from "../../util/uri";
4-
5-export function parsePromptFileV1V2(path: string, content: string) {
6- let [preambleRaw, prompt] = content.split("\n---\n");
7- if (prompt === undefined) {
8- prompt = preambleRaw;
9- preambleRaw = "";
10- }
11-
12- const preamble = YAML.parse(preambleRaw) ?? {};
13- const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14- const description = preamble.description ?? name;
15- const version = preamble.version ?? 2;
16-
17- let systemMessage: string | undefined = undefined;
18- if (prompt.includes("<system>")) {
19- systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
20- prompt = prompt.split("</system>")[1].trim();
21- }
22-
23- return { name, description, systemMessage, prompt, version };
24-}
deleted core/promptFiles/v2/renderPromptFile.ts +0 −84
@@ -1,84 +0,0 @@
1-import { ContextItem, ContextProviderExtras } from "../..";
2-import { contextProviderClassFromName } from "../../context/providers";
3-import { getUrlContextItems } from "../../context/providers/URLContextProvider";
4-import { resolveRelativePathInDir } from "../../util/ideUtils";
5-import { getUriPathBasename } from "../../util/uri";
6-
7-import { getPreambleAndBody } from "./parse";
8-
9-async function resolveAttachment(
10- name: string,
11- extras: ContextProviderExtras,
12-): Promise<ContextItem[]> {
13- // Context providers
14- const contextProvider = extras.config.contextProviders?.find(
15- (provider) => provider.description.title === name,
16- );
17- if (contextProvider) {
18- const items = await contextProvider.getContextItems("", extras);
19- return items;
20- } else {
21- // Just instantiate it here
22- const providerClass = contextProviderClassFromName(name) as any;
23- if (providerClass) {
24- const providerInstance = new providerClass({});
25- return providerInstance.getContextItems("", extras);
26- }
27- }
28-
29- // Files
30- const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
31- if (resolvedFileUri) {
32- let subItems: ContextItem[] = [];
33- if (name.endsWith(".prompt")) {
34- // Recurse
35- const [items, _] = await renderPromptFileV2(
36- await extras.ide.readFile(resolvedFileUri),
37- extras,
38- );
39- subItems.push(...items);
40- }
41-
42- const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
43- return [
44- ...subItems,
45- {
46- name: getUriPathBasename(resolvedFileUri),
47- content,
48- description: resolvedFileUri,
49- },
50- ];
51- }
52-
53- // URLs
54- if (name.startsWith("http")) {
55- const items = getUrlContextItems(name, extras.fetch);
56- return items;
57- }
58-
59- return [];
60-}
61-
62-export async function renderPromptFileV2(
63- rawContent: string,
64- extras: ContextProviderExtras,
65-): Promise<[ContextItem[], string]> {
66- const [_, body] = getPreambleAndBody(rawContent);
67-
68- const contextItemsPromises: Promise<ContextItem[]>[] = [];
69- const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
70- contextItemsPromises.push(resolveAttachment(name, extras));
71- return match;
72- });
73-
74- const contextItems = (await Promise.all(contextItemsPromises)).flat();
75- const renderedPrompt = [
76- ...contextItems.map((item) => item.content),
77- renderedBody,
78- extras.fullInput,
79- ]
80- .join("\n\n")
81- .trim();
82-
83- return [contextItems, renderedPrompt];
84-}
deleted core/promptFiles/v2/renderPromptFile.vitest.ts +0 −175
@@ -1,175 +0,0 @@
1-import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
2-import { testConfigHandler, testIde } from "../../test/fixtures";
3-import {
4- addToTestDir,
5- setUpTestDir,
6- tearDownTestDir,
7-} from "../../test/testDir";
8-import { renderPromptFileV2 } from "./renderPromptFile";
9-
10-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11-
12-vi.mock(
13- import("../../context/providers/URLContextProvider"),
14- async (importOriginal) => {
15- const actual = await importOriginal();
16- return {
17- ...actual,
18- getUrlContextItems: vi.fn().mockResolvedValue([
19- {
20- description: "https://example.com",
21- content: "Example Content",
22- name: "Example site",
23- uri: {
24- type: "url",
25- value: "https://example.com",
26- },
27- },
28- ]),
29- };
30- },
31-);
32-
33-describe("renderPromptFileV2", () => {
34- let extras: ContextProviderExtras;
35- const mockGetContextItems = vi.fn().mockResolvedValue([
36- {
37- name: "custom",
38- content: "Custom provider content",
39- description: "Custom provider",
40- },
41- ]);
42- beforeEach(async () => {
43- const { config } = await testConfigHandler.loadConfig();
44-
45- // Setup mock extras
46- extras = {
47- config: {
48- ...config!,
49- contextProviders: [
50- {
51- description: {
52- type: "normal",
53- title: "CustomProvider",
54- displayTitle: "Custom Provider",
55- description: "A custom context provider",
56- },
57- loadSubmenuItems: vi.fn().mockResolvedValue([]),
58- getContextItems: mockGetContextItems,
59- },
60- ],
61- },
62- fullInput: "User input",
63- embeddingsProvider: null,
64- reranker: null,
65- llm: {} as ILLM,
66- ide: testIde,
67- selectedCode: [] as RangeInFile[],
68- fetch: vi.fn(),
69- };
70-
71- // Clear all mocks
72- vi.clearAllMocks();
73- setUpTestDir();
74- });
75-
76- afterEach(() => {
77- tearDownTestDir();
78- });
79-
80- it("should render a prompt file with no attachments", async () => {
81- const rawContent = "Simple prompt with no attachments";
82- const [contextItems, renderedPrompt] = await renderPromptFileV2(
83- rawContent,
84- extras,
85- );
86-
87- expect(contextItems).toHaveLength(0);
88- expect(renderedPrompt).toBe(
89- "Simple prompt with no attachments\n\nUser input",
90- );
91- });
92-
93- it("should handle URL attachments", async () => {
94- const rawContent = "Content with URL @https://example.com";
95-
96- const [contextItems, renderedPrompt] = await renderPromptFileV2(
97- rawContent,
98- extras,
99- );
100-
101- expect(contextItems).toHaveLength(1);
102- expect(renderedPrompt).toContain("Example Content");
103- });
104-
105- it("should resolve file attachments", async () => {
106- const rawContent = "Content with file attachment @test.txt";
107-
108- addToTestDir([["test.txt", "File content"]]);
109-
110- const [contextItems, renderedPrompt] = await renderPromptFileV2(
111- rawContent,
112- extras,
113- );
114-
115- expect(contextItems).toHaveLength(1);
116- expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
117- expect(renderedPrompt).toContain("Content with file attachment @test.txt");
118- });
119-
120- it("should handle nested prompt files", async () => {
121- const rawContent = "Main prompt with nested @nested.prompt";
122- addToTestDir([
123- ["nested.prompt", "Nested prompt content with @CustomProvider"],
124- ]);
125-
126- const [contextItems, renderedPrompt] = await renderPromptFileV2(
127- rawContent,
128- extras,
129- );
130-
131- expect(renderedPrompt).toContain("Custom provider content");
132- });
133-
134- it("should handle custom context providers", async () => {
135- const rawContent = "Content with custom provider @CustomProvider";
136-
137- const [contextItems, renderedPrompt] = await renderPromptFileV2(
138- rawContent,
139- extras,
140- );
141-
142- expect(contextItems).toHaveLength(1);
143- expect(renderedPrompt).toContain("Custom provider content");
144- expect(mockGetContextItems).toHaveBeenCalled();
145- });
146-
147- it("should handle multiple attachments", async () => {
148- const rawContent = "Content with @file1.txt and @file2.txt";
149- addToTestDir([
150- ["file1.txt", "Content 1"],
151- ["file2.txt", "Content 2"],
152- ]);
153-
154- const [contextItems, renderedPrompt] = await renderPromptFileV2(
155- rawContent,
156- extras,
157- );
158-
159- expect(contextItems).toHaveLength(2);
160- expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
161- expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
162- });
163-
164- it("should handle failed attachment resolutions gracefully", async () => {
165- const rawContent = "Content with @nonexistent";
166-
167- const [contextItems, renderedPrompt] = await renderPromptFileV2(
168- rawContent,
169- extras,
170- );
171-
172- expect(contextItems).toHaveLength(0);
173- expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
174- });
175-});
modified core/protocol/core.ts +32 −3
@@ -5,7 +5,10 @@
55 ModelRole,
66 } from "@continuedev/config-yaml";
77
8-import { AutocompleteInput } from "../autocomplete/util/types";
8+import {
9+ AutocompleteInput,
10+ RecentlyEditedRange,
11+} from "../autocomplete/util/types";
912 import { SharedConfigSchema } from "../config/sharedConfig";
1013 import { GlobalContextModelSelections } from "../util/GlobalContext";
1114
@@ -25,14 +28,18 @@
2528 ModelDescription,
2629 PromptLog,
2730 RangeInFile,
31+ RangeInFileWithNextEditInfo,
2832 SerializedContinueConfig,
2933 Session,
3034 SessionMetadata,
3135 SiteIndexingConfig,
32- SlashCommandDescription,
36+ SlashCommandDescWithSource,
3337 StreamDiffLinesPayload,
3438 ToolCall,
3539 } from "../";
40+import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
41+import { GetLspDefinitionsFunction } from "../autocomplete/types";
42+import { ConfigHandler } from "../config/ConfigHandler";
3643 import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
3744 import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
3845 import { FreeTrialStatus } from "../control-plane/client";
@@ -109,6 +116,7 @@
109116 query: string;
110117 fullInput: string;
111118 selectedCode: RangeInFile[];
119+ isInAgentMode: boolean;
112120 },
113121 ContextItemWithId[],
114122 ];
@@ -118,6 +126,17 @@
118126 },
119127 void,
120128 ];
129+ "mcp/getPrompt": [
130+ {
131+ serverName: string;
132+ promptName: string;
133+ args?: Record<string, string>;
134+ },
135+ {
136+ prompt: string;
137+ description: string | undefined;
138+ },
139+ ];
121140 "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
122141 "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
123142 "autocomplete/complete": [AutocompleteInput, string[]];
@@ -141,7 +160,7 @@
141160 completionOptions: LLMFullCompletionOptions;
142161 title: string;
143162 legacySlashCommandData?: {
144- command: SlashCommandDescription;
163+ command: SlashCommandDescWithSource;
145164 input: string;
146165 contextItems: ContextItemWithId[];
147166 historyIndex: number;
@@ -182,6 +201,16 @@
182201 "files/created": [{ uris?: string[] }, void];
183202 "files/deleted": [{ uris?: string[] }, void];
184203 "files/closed": [{ uris?: string[] }, void];
204+ "files/smallEdit": [
205+ {
206+ actions: RangeInFileWithNextEditInfo[];
207+ configHandler: ConfigHandler;
208+ getDefsFromLspFunction: GetLspDefinitionsFunction;
209+ recentlyEditedRanges: RecentlyEditedRange[];
210+ recentlyVisitedRanges: AutocompleteCodeSnippet[];
211+ },
212+ void,
213+ ];
185214
186215 // Docs etc. Indexing. TODO move codebase to this
187216 "indexing/reindex": [{ type: string; id: string }, void];
modified core/protocol/ide.ts +3 −12
@@ -1,6 +1,5 @@
11 import type {
22 ContinueRcJson,
3- DiffLine,
43 FileStatsMap,
54 FileType,
65 IDE,
@@ -29,21 +28,12 @@
2928 openFile: [{ path: string }, void];
3029 openUrl: [string, void];
3130 runCommand: [{ command: string; options?: TerminalOptions }, void];
32- getSearchResults: [{ query: string }, string];
33- getFileResults: [{ pattern: string }, string[]];
31+ getSearchResults: [{ query: string; maxResults?: number }, string];
32+ getFileResults: [{ pattern: string; maxResults?: number }, string[]];
3433 subprocess: [{ command: string; cwd?: string }, [string, string]];
3534 saveFile: [{ filepath: string }, void];
3635 fileExists: [{ filepath: string }, boolean];
3736 readFile: [{ filepath: string }, string];
38- diffLine: [
39- {
40- diffLine: DiffLine;
41- filepath: string;
42- startLine: number;
43- endLine: number;
44- },
45- void,
46- ];
4737 getProblems: [{ filepath: string }, Problem[]];
4838 getOpenFiles: [undefined, string[]];
4939 getCurrentFile: [
@@ -70,6 +60,7 @@
7060 ];
7161 getAvailableThreads: [undefined, Thread[]];
7262 isTelemetryEnabled: [undefined, boolean];
63+ isWorkspaceRemote: [undefined, boolean];
7364 getUniqueId: [undefined, string];
7465 getTags: [string, IndexTag[]];
7566 readSecrets: [{ keys: string[] }, Record<string, string>];
modified core/protocol/ideWebview.ts +3 −9
@@ -4,6 +4,7 @@
44 import {
55 AcceptOrRejectDiffPayload,
66 ApplyState,
7+ ApplyToFilePayload,
78 HighlightedCodePayload,
89 MessageContent,
910 RangeInFileWithContents,
@@ -13,15 +14,7 @@
1314
1415 export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
1516 openUrl: [string, void];
16- applyToFile: [
17- {
18- text: string;
19- streamId: string;
20- filepath?: string;
21- toolCallId?: string;
22- },
23- void,
24- ];
17+ applyToFile: [ApplyToFilePayload, void];
2518 overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
2619 showTutorial: [undefined, void];
2720 showFile: [ShowFilePayload, void];
@@ -84,4 +77,5 @@
8477 updateApplyState: [ApplyState, void];
8578 exitEditMode: [undefined, void];
8679 focusEdit: [undefined, void];
80+ generateRule: [undefined, void];
8781 };
modified core/protocol/messenger/messageIde.ts +6 −2
@@ -106,6 +106,10 @@
106106 return this.request("isTelemetryEnabled", undefined);
107107 }
108108
109+ isWorkspaceRemote(): Promise<boolean> {
110+ return this.request("isWorkspaceRemote", undefined);
111+ }
112+
109113 getUniqueId(): Promise<string> {
110114 return this.request("getUniqueId", undefined);
111115 }
@@ -185,8 +189,8 @@
185189 return this.request("getPinnedFiles", undefined);
186190 }
187191
188- getSearchResults(query: string): Promise<string> {
189- return this.request("getSearchResults", { query });
192+ getSearchResults(query: string, maxResults?: number): Promise<string> {
193+ return this.request("getSearchResults", { query, maxResults });
190194 }
191195
192196 getFileResults(pattern: string): Promise<string[]> {
modified core/protocol/messenger/reverseMessageIde.ts +2 −2
@@ -159,11 +159,11 @@
159159 });
160160
161161 this.on("getSearchResults", (data) => {
162- return this.ide.getSearchResults(data.query);
162+ return this.ide.getSearchResults(data.query, data.maxResults);
163163 });
164164
165165 this.on("getFileResults", (data) => {
166- return this.ide.getFileResults(data.pattern);
166+ return this.ide.getFileResults(data.pattern, data.maxResults);
167167 });
168168
169169 this.on("getProblems", (data) => {
modified core/protocol/passThrough.ts +1 −0
@@ -27,6 +27,7 @@
2727 "config/updateSharedConfig",
2828 "config/updateSelectedModel",
2929 "mcp/reloadServer",
30+ "mcp/getPrompt",
3031 "context/getContextItems",
3132 "context/getSymbolsForFiles",
3233 "context/loadSubmenuItems",
added core/rules.md +10 −0
@@ -0,0 +1,10 @@
1+# `core` rules
2+
3+Whenever a new protocol message is added to the `protocol/` directory, check the following:
4+
5+- It's type is defined correctly
6+- If it is a message from webview to core or vice versa:
7+ - It has been added to `core/protocol/passThrough.ts`
8+ - It has been added to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`
9+- It is implemented in either `core/core.ts` (for messages to the core), in a `useWebviewListener` (for messages to the gui), or in `VsCodeMessenger.ts` for VS Code or `IdeProtocolClient.kt` for JetBriains (for messages to the IDE).
10+- It does not duplicate functionality from another message type that already exists.
added core/test/vitest.global-setup.ts +11 −0
@@ -0,0 +1,11 @@
1+import fs from "fs";
2+import path from "path";
3+
4+// Sets up the GLOBAL directory for testing - equivalent to ~/.continue
5+// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths
6+export default async function () {
7+ process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
8+ if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
9+ fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
10+ }
11+}
added core/test/vitest.setup.ts +16 −0
@@ -0,0 +1,16 @@
1+import { TextDecoder, TextEncoder } from "util";
2+
3+import fetch, { Request, Response } from "node-fetch";
4+import { beforeAll } from "vitest";
5+
6+beforeAll(() => {
7+ // @ts-ignore
8+ globalThis.fetch = fetch;
9+ // @ts-ignore
10+ globalThis.Request = Request;
11+ // @ts-ignore
12+ globalThis.Response = Response;
13+ globalThis.TextEncoder = TextEncoder;
14+ // @ts-ignore
15+ globalThis.TextDecoder = TextDecoder;
16+});
modified core/tools/builtIn.ts +21 −16
@@ -1,23 +1,28 @@
11 export enum BuiltInToolNames {
2- ReadFile = "builtin_read_file",
3- EditExistingFile = "builtin_edit_existing_file",
4- ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
5- CreateNewFile = "builtin_create_new_file",
6- RunTerminalCommand = "builtin_run_terminal_command",
7- GrepSearch = "builtin_grep_search",
8- FileGlobSearch = "builtin_file_glob_search",
9- SearchWeb = "builtin_search_web",
10- ViewDiff = "builtin_view_diff",
11- LSTool = "builtin_ls",
12- CreateRuleBlock = "builtin_create_rule_block",
13- RequestRule = "builtin_request_rule",
14- FetchUrlContent = "builtin_fetch_url_content",
2+ ReadFile = "read_file",
3+ EditExistingFile = "edit_existing_file",
4+ SearchAndReplaceInFile = "search_and_replace_in_file",
5+ ReadCurrentlyOpenFile = "read_currently_open_file",
6+ CreateNewFile = "create_new_file",
7+ RunTerminalCommand = "run_terminal_command",
8+ GrepSearch = "grep_search",
9+ FileGlobSearch = "file_glob_search",
10+ SearchWeb = "search_web",
11+ ViewDiff = "view_diff",
12+ LSTool = "ls",
13+ CreateRuleBlock = "create_rule_block",
14+ RequestRule = "request_rule",
15+ FetchUrlContent = "fetch_url_content",
16+ CodebaseTool = "codebase",
1517
1618 // excluded from allTools for now
17- ViewRepoMap = "builtin_view_repo_map",
18- ViewSubdirectory = "builtin_view_subdirectory",
19+ ViewRepoMap = "view_repo_map",
20+ ViewSubdirectory = "view_subdirectory",
1921 }
2022
2123 export const BUILT_IN_GROUP_NAME = "Built-In";
2224
23-export const CLIENT_TOOLS_IMPLS = [BuiltInToolNames.EditExistingFile];
25+export const CLIENT_TOOLS_IMPLS = [
26+ BuiltInToolNames.EditExistingFile,
27+ BuiltInToolNames.SearchAndReplaceInFile,
28+];
modified core/tools/callTool.ts +10 −1
@@ -3,6 +3,7 @@
33 import { canParseUrl } from "../util/url";
44 import { BuiltInToolNames } from "./builtIn";
55
6+import { codebaseToolImpl } from "./implementations/codebaseTool";
67 import { createNewFileImpl } from "./implementations/createNewFile";
78 import { createRuleBlockImpl } from "./implementations/createRuleBlock";
89 import { fetchUrlContentImpl } from "./implementations/fetchUrlContent";
@@ -15,6 +16,8 @@
1516 import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
1617 import { searchWebImpl } from "./implementations/searchWeb";
1718 import { viewDiffImpl } from "./implementations/viewDiff";
19+import { viewRepoMapImpl } from "./implementations/viewRepoMap";
20+import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
1821 import { safeParseToolCallArgs } from "./parseArgs";
1922
2023 async function callHttpTool(
@@ -134,7 +137,7 @@
134137 }
135138 }
136139
137-async function callBuiltInTool(
140+export async function callBuiltInTool(
138141 functionName: string,
139142 args: any,
140143 extras: ToolExtras,
@@ -164,6 +167,12 @@
164167 return await createRuleBlockImpl(args, extras);
165168 case BuiltInToolNames.RequestRule:
166169 return await requestRuleImpl(args, extras);
170+ case BuiltInToolNames.CodebaseTool:
171+ return await codebaseToolImpl(args, extras);
172+ case BuiltInToolNames.ViewRepoMap:
173+ return await viewRepoMapImpl(args, extras);
174+ case BuiltInToolNames.ViewSubdirectory:
175+ return await viewSubdirectoryImpl(args, extras);
167176 default:
168177 throw new Error(`Tool "${functionName}" not found`);
169178 }
added core/tools/definitions/codebaseTool.ts +29 −0
@@ -0,0 +1,29 @@
1+import { Tool } from "../..";
2+import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
3+
4+export const codebaseTool: Tool = {
5+ type: "function",
6+ displayTitle: "Codebase Search",
7+ wouldLikeTo: "search the codebase for: {{{ query }}}",
8+ isCurrently: "searching the codebase for: {{{ query }}}",
9+ hasAlready: "searched the codebase for: {{{ query }}}",
10+ readonly: true,
11+ isInstant: false,
12+ group: BUILT_IN_GROUP_NAME,
13+ function: {
14+ name: BuiltInToolNames.CodebaseTool,
15+ description:
16+ "Use this tool to semantically search through the codebase and retrieve relevant code snippets based on a natural language query. This helps find relevant code context for understanding or working with the codebase.",
17+ parameters: {
18+ type: "object",
19+ required: ["query"],
20+ properties: {
21+ query: {
22+ type: "string",
23+ description:
24+ "Natural language description of what you're looking for in the codebase (e.g., 'authentication logic', 'database connection setup', 'error handling')",
25+ },
26+ },
27+ },
28+ },
29+};
modified core/tools/definitions/createRuleBlock.ts +14 −3
@@ -13,10 +13,10 @@
1313 function: {
1414 name: BuiltInToolNames.CreateRuleBlock,
1515 description:
16- "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
16+ 'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
1717 parameters: {
1818 type: "object",
19- required: ["name", "rule", "alwaysApply", "description"],
19+ required: ["name", "rule", "description"],
2020 properties: {
2121 name: {
2222 type: "string",
@@ -30,13 +30,24 @@
3030 },
3131 description: {
3232 type: "string",
33- description: "Short description of the rule",
33+ description:
34+ "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.",
3435 },
3536 globs: {
3637 type: "string",
3738 description:
3839 "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
3940 },
41+ regex: {
42+ type: "string",
43+ description:
44+ "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
45+ },
46+ alwaysApply: {
47+ type: "boolean",
48+ description:
49+ "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.",
50+ },
4051 },
4152 },
4253 },
modified core/tools/definitions/editFile.ts +2 −2
@@ -1,4 +1,5 @@
11 import { Tool } from "../..";
2+import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
23 import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
34
45 export interface EditToolArgs {
@@ -17,8 +18,7 @@
1718 isInstant: false,
1819 function: {
1920 name: BuiltInToolNames.EditExistingFile,
20- description:
21- "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
21+ description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}`,
2222 parameters: {
2323 type: "object",
2424 required: ["filepath", "changes"],
modified core/tools/definitions/globSearch.ts +2 −1
@@ -12,7 +12,8 @@
1212 group: BUILT_IN_GROUP_NAME,
1313 function: {
1414 name: BuiltInToolNames.FileGlobSearch,
15- description: "Search for files in the project",
15+ description:
16+ "Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
1617 parameters: {
1718 type: "object",
1819 required: ["pattern"],
modified core/tools/definitions/grepSearch.ts +2 −1
@@ -12,7 +12,8 @@
1212 group: BUILT_IN_GROUP_NAME,
1313 function: {
1414 name: BuiltInToolNames.GrepSearch,
15- description: "Perform a search over the repository using ripgrep.",
15+ description:
16+ "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
1617 parameters: {
1718 type: "object",
1819 required: ["query"],
added core/tools/definitions/searchAndReplaceInFile.ts +86 −0
@@ -0,0 +1,86 @@
1+import { Tool } from "../..";
2+import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
3+
4+export interface SearchAndReplaceInFileArgs {
5+ filepath: string;
6+ diff: string;
7+}
8+
9+/**
10+ * This tool is in an experimental state.
11+ * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
12+ */
13+export const searchAndReplaceInFileTool: Tool = {
14+ type: "function",
15+ displayTitle: "Edit File",
16+ wouldLikeTo: "edit {{{ filepath }}}",
17+ isCurrently: "editing {{{ filepath }}}",
18+ hasAlready: "edited {{{ filepath }}}",
19+ group: BUILT_IN_GROUP_NAME,
20+ readonly: false,
21+ isInstant: false,
22+ function: {
23+ name: BuiltInToolNames.SearchAndReplaceInFile,
24+ description:
25+ "Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
26+ parameters: {
27+ type: "object",
28+ required: ["filepath", "diff"],
29+ properties: {
30+ filepath: {
31+ type: "string",
32+ description:
33+ "The path of the file to modify, relative to the root of the workspace.",
34+ },
35+ diff: {
36+ type: "string",
37+ description: `One or more SEARCH/REPLACE blocks following this exact format:
38+\`\`\`
39+------- SEARCH
40+[exact content to find]
41+=======
42+[new content to replace with]
43++++++++ REPLACE
44+\`\`\`
45+
46+Critical rules:
47+1. SEARCH content must match the associated file section to find EXACTLY:
48+ * Match character-for-character including whitespace, indentation, line endings
49+ * Include all comments, docstrings, etc.
50+2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
51+ * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
52+ * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
53+ * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
54+3. Keep SEARCH/REPLACE blocks concise:
55+ * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
56+ * Include just the changing lines, and a few surrounding lines if needed for uniqueness.
57+ * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
58+ * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
59+4. Splitting up tool calls:
60+ * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
61+ * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
62+ * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
63+5. Special operations:
64+ * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
65+ * To delete code: Use empty REPLACE section
66+
67+Usage:
68+\`\`\`
69+------- SEARCH
70+[exact content to find]
71+=======
72+[new content to replace with]
73++++++++ REPLACE
74+
75+------- SEARCH
76+[exact content to find]
77+=======
78+[new content to replace with]
79++++++++ REPLACE
80+ \`\`\`
81+`,
82+ },
83+ },
84+ },
85+ },
86+};
added core/tools/implementations/codebaseTool.ts +62 −0
@@ -0,0 +1,62 @@
1+import { ToolImpl } from ".";
2+import { RangeInFile } from "../..";
3+import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
4+
5+export const codebaseToolImpl: ToolImpl = async (args, extras) => {
6+ if (!args.query || args.query.trim() === "") {
7+ return [
8+ {
9+ name: "Error",
10+ description: "Codebase search error",
11+ content: "Query parameter is required and cannot be empty.",
12+ },
13+ ];
14+ }
15+
16+ try {
17+ const contextExtras = {
18+ config: extras.config,
19+ fullInput: args.query,
20+ embeddingsProvider: extras.config.selectedModelByRole.embed,
21+ reranker: extras.config.selectedModelByRole.rerank,
22+ llm: extras.llm,
23+ ide: extras.ide,
24+ selectedCode: [] as RangeInFile[],
25+ fetch: extras.fetch,
26+ isInAgentMode: true, // always true in tool call
27+ };
28+
29+ // Use the existing retrieval function to get context items
30+ const results = await retrieveContextItemsFromEmbeddings(
31+ contextExtras,
32+ undefined,
33+ undefined,
34+ );
35+
36+ // If no results found, return helpful message
37+ if (results.length === 0) {
38+ return [
39+ {
40+ name: "No Results",
41+ description: "Codebase search",
42+ content: `No relevant code found for query: "${args.query}". This could mean:
43+- The codebase hasn't been indexed yet
44+- No code matches the search criteria
45+- Embeddings provider is not configured
46+
47+Try re-indexing the codebase or using a more specific query.`,
48+ },
49+ ];
50+ }
51+
52+ return results;
53+ } catch (error) {
54+ return [
55+ {
56+ name: "Error",
57+ description: "Codebase search error",
58+ content: `Failed to search codebase: ${error instanceof Error ? error.message : String(error)}`,
59+ },
60+ ];
61+ }
62+};
modified core/tools/implementations/createRuleBlock.test.ts +5 −4
@@ -1,5 +1,5 @@
1+import { parseMarkdownRule } from "@continuedev/config-yaml";
12 import { jest } from "@jest/globals";
2-import { parseMarkdownRule } from "../../config/markdown";
33 import { createRuleBlockImpl } from "./createRuleBlock";
44
55 const mockIde = {
@@ -36,11 +36,11 @@
3636 const { frontmatter, markdown } = parseMarkdownRule(fileContent);
3737
3838 expect(frontmatter).toEqual({
39+ alwaysApply: true,
3940 description: "Always use interfaces",
4041 globs: "**/*.{ts,tsx}",
4142 });
4243
43- expect(markdown).toContain("# TypeScript Rule");
4444 expect(markdown).toContain("Use interfaces for object shapes");
4545 });
4646
@@ -73,10 +73,10 @@
7373 const { frontmatter, markdown } = parseMarkdownRule(fileContent);
7474
7575 expect(frontmatter).toEqual({
76+ alwaysApply: true,
7677 description: "This is a detailed explanation of the rule",
7778 });
7879
79- expect(markdown).toContain("# Description Test");
8080 expect(markdown).toContain("This is the rule content");
8181 });
8282
@@ -96,11 +96,11 @@
9696 const { frontmatter, markdown } = parseMarkdownRule(fileContent);
9797
9898 expect(frontmatter).toEqual({
99+ alwaysApply: false,
99100 description: "This rule enforces our team standards",
100101 globs: "**/*.js",
101102 });
102103
103- expect(markdown).toContain("# Complete Rule");
104104 expect(markdown).toContain("Follow this standard");
105105 });
106106
@@ -119,6 +119,7 @@
119119 const { frontmatter } = parseMarkdownRule(fileContent);
120120
121121 expect(frontmatter).toEqual({
122+ alwaysApply: false,
122123 description: "Optional rule",
123124 });
124125 });
modified core/tools/implementations/createRuleBlock.ts +8 −10
@@ -1,24 +1,22 @@
1+import { createRuleMarkdown } from "@continuedev/config-yaml";
12 import { ToolImpl } from ".";
23 import { RuleWithSource } from "../..";
3-import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown";
4+import { createRuleFilePath } from "../../config/markdown/utils";
45
56 export type CreateRuleBlockArgs = Pick<
67 Required<RuleWithSource>,
7- "rule" | "description" | "alwaysApply" | "name"
8+ "rule" | "name"
89 > &
9- Pick<RuleWithSource, "globs">;
10+ Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
1011
1112 export const createRuleBlockImpl: ToolImpl = async (
12- args: CreateRuleBlockArgs,
13+ { name, rule, ...otherArgs }: CreateRuleBlockArgs,
1314 extras,
1415 ) => {
15- const fileContent = createRuleMarkdown(args.name, args.rule, {
16- description: args.description,
17- globs: args.globs,
18- });
16+ const fileContent = createRuleMarkdown(name, rule, otherArgs);
1917
2018 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
21- const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
19+ const ruleFilePath = createRuleFilePath(localContinueDir, name);
2220
2321 await extras.ide.writeFile(ruleFilePath, fileContent);
2422 await extras.ide.openFile(ruleFilePath);
@@ -26,7 +24,7 @@
2624 return [
2725 {
2826 name: "New Rule Block",
29- description: args.description || "",
27+ description: otherArgs.description || "",
3028 uri: {
3129 type: "file",
3230 value: ruleFilePath,
modified core/tools/implementations/fetchUrlContent.ts +29 −1
@@ -1,6 +1,34 @@
11 import { ToolImpl } from ".";
22 import { getUrlContextItems } from "../../context/providers/URLContextProvider";
33
4+const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
5+
46 export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
5- return getUrlContextItems(args.url, extras.fetch);
7+ const contextItems = await getUrlContextItems(args.url, extras.fetch);
8+
9+ // Track truncated content
10+ const truncatedUrls: string[] = [];
11+
12+ // Check and truncate each context item
13+ const processedItems = contextItems.map((item) => {
14+ if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
15+ truncatedUrls.push(args.url);
16+ return {
17+ ...item,
18+ content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),
19+ };
20+ }
21+ return item;
22+ });
23+
24+ // Add truncation warning if needed
25+ if (truncatedUrls.length > 0) {
26+ processedItems.push({
27+ name: "URL content truncation warning",
28+ description: "Informs that URL content was truncated",
29+ content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`,
30+ });
31+ }
32+
33+ return processedItems;
634 };
added core/tools/implementations/fetchUrlContent.vitest.ts +91 −0
@@ -0,0 +1,91 @@
1+import { expect, test, vi } from "vitest";
2+import { fetchUrlContentImpl } from "./fetchUrlContent";
3+
4+vi.mock("../../context/providers/URLContextProvider", () => ({
5+ getUrlContextItems: vi.fn(),
6+}));
7+
8+import { ToolExtras } from "../..";
9+import { getUrlContextItems } from "../../context/providers/URLContextProvider";
10+const mockExtras = {
11+ fetch: vi.fn() as any,
12+ ide: {} as any,
13+} as unknown as ToolExtras;
14+
15+test("fetchUrlContent should not truncate content under character limit", async () => {
16+ const shortContent = "This is a short content";
17+ const mockContextItems = [
18+ {
19+ name: "Test URL",
20+ description: "Test URL description",
21+ content: shortContent,
22+ },
23+ ];
24+
25+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
26+
27+ const result = await fetchUrlContentImpl(
28+ { url: "https://example.com" },
29+ mockExtras,
30+ );
31+
32+ expect(result).toHaveLength(1);
33+ expect(result[0].content).toBe(shortContent);
34+});
35+
36+test("fetchUrlContent should truncate content exceeding character limit", async () => {
37+ const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
38+ // Create a string exceeding the character limit
39+ const longContent = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
40+ const mockContextItems = [
41+ {
42+ name: "Test URL",
43+ description: "Test URL description",
44+ content: longContent,
45+ },
46+ ];
47+
48+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
49+
50+ const result = await fetchUrlContentImpl(
51+ { url: "https://example.com" },
52+ mockExtras,
53+ );
54+
55+ expect(result).toHaveLength(2); // Original item + warning
56+ expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
57+ expect(result[1].name).toBe("URL content truncation warning");
58+ expect(result[1].content).toContain("was truncated");
59+ expect(result[1].content).toContain("20000 character limit");
60+});
61+
62+test("fetchUrlContent should add truncation warning with multiple truncated items", async () => {
63+ const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
64+ // Create strings exceeding the character limit
65+ const longContent1 = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 500);
66+ const longContent2 = "b".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
67+ const mockContextItems = [
68+ {
69+ name: "Test URL 1",
70+ description: "Test URL description 1",
71+ content: longContent1,
72+ },
73+ {
74+ name: "Test URL 2",
75+ description: "Test URL description 2",
76+ content: longContent2,
77+ },
78+ ];
79+
80+ (getUrlContextItems as any).mockResolvedValue(mockContextItems);
81+
82+ const result = await fetchUrlContentImpl(
83+ { url: "https://example.com" },
84+ mockExtras,
85+ );
86+
87+ expect(result).toHaveLength(3); // Two original items + warning
88+ expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
89+ expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
90+ expect(result[2].name).toBe("URL content truncation warning");
91+});
modified core/tools/implementations/globSearch.ts +18 −2
@@ -1,12 +1,28 @@
11 import { ToolImpl } from ".";
2+import { ContextItem } from "../..";
23
4+const MAX_AGENT_GLOB_RESULTS = 100;
35 export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
4- const results = await extras.ide.getFileResults(args.pattern);
5- return [
6+ const results = await extras.ide.getFileResults(
7+ args.pattern,
8+ MAX_AGENT_GLOB_RESULTS,
9+ );
10+ const contextItems: ContextItem[] = [
611 {
712 name: "File results",
813 description: "Results from file glob search",
914 content: results.join("\n"),
1015 },
1116 ];
17+
18+ // In case of truncation, add a warning
19+ if (results.length === MAX_AGENT_GLOB_RESULTS) {
20+ contextItems.push({
21+ name: "Truncation warning",
22+ description: "Inform the model that results were truncated",
23+ content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
24+ });
25+ }
26+
27+ return contextItems;
1228 };
modified core/tools/implementations/grepSearch.ts +82 −8
@@ -1,13 +1,87 @@
11 import { ToolImpl } from ".";
2+import { ContextItem } from "../..";
23 import { formatGrepSearchResults } from "../../util/grepSearch";
34
5+const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
6+const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
7+
8+function splitGrepResultsByFile(content: string): ContextItem[] {
9+ const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
10+
11+ if (matches.length === 0) {
12+ return [];
13+ }
14+
15+ const contextItems: ContextItem[] = [];
16+
17+ for (let i = 0; i < matches.length; i++) {
18+ const match = matches[i];
19+ const filepath = match[1];
20+ const startIndex = match.index!;
21+ const endIndex =
22+ i < matches.length - 1 ? matches[i + 1].index! : content.length;
23+
24+ // Extract grepped content for this file
25+ const fileContent = content
26+ .substring(startIndex, endIndex)
27+ .replace(/^\.\/[^\n]+\n/, "") // remove the line with file path
28+ .trim();
29+
30+ if (fileContent) {
31+ contextItems.push({
32+ name: `Search results in ${filepath}`,
33+ description: `Grep search results from ${filepath}`,
34+ content: fileContent,
35+ uri: { type: "file", value: filepath },
36+ });
37+ }
38+ }
39+
40+ return contextItems;
41+}
42+
443 export const grepSearchImpl: ToolImpl = async (args, extras) => {
5- const results = await extras.ide.getSearchResults(args.query);
6- return [
7- {
8- name: "Search results",
9- description: "Results from grep search",
10- content: formatGrepSearchResults(results),
11- },
12- ];
44+ const results = await extras.ide.getSearchResults(
45+ args.query,
46+ DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
47+ );
48+ const { formatted, numResults, truncated } = formatGrepSearchResults(
49+ results,
50+ DEFAULT_GREP_SEARCH_CHAR_LIMIT,
51+ );
52+ const truncationReasons: string[] = [];
53+ if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
54+ truncationReasons.push(
55+ `the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`,
56+ );
57+ }
58+ if (truncated) {
59+ truncationReasons.push(
60+ `the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`,
61+ );
62+ }
63+
64+ let contextItems: ContextItem[] = [];
65+
66+ const splitByFile: boolean = args.splitByFile || false;
67+ if (splitByFile) {
68+ contextItems = splitGrepResultsByFile(formatted);
69+ } else {
70+ contextItems = [
71+ {
72+ name: "Search results",
73+ description: "Results from grep search",
74+ content: formatted,
75+ },
76+ ];
77+ }
78+
79+ if (truncationReasons.length > 0) {
80+ contextItems.push({
81+ name: "Search truncation warning",
82+ description: "Informs the model that search results were truncated",
83+ content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
84+ });
85+ }
86+ return contextItems;
1387 };
modified core/tools/implementations/lsTool.ts +38 −9
@@ -2,30 +2,59 @@
22 import { walkDir } from "../../indexing/walkDir";
33 import { resolveRelativePathInDir } from "../../util/ideUtils";
44
5+export function resolveLsToolDirPath(dirPath: string | undefined) {
6+ if (!dirPath || dirPath === ".") {
7+ return "/";
8+ }
9+ if (dirPath.startsWith(".")) {
10+ return dirPath.slice(1);
11+ }
12+ return dirPath.replace(/\\/g, "/");
13+}
14+
15+const MAX_LS_TOOL_LINES = 200;
16+
517 export const lsToolImpl: ToolImpl = async (args, extras) => {
6- const uri = await resolveRelativePathInDir(args.dirPath, extras.ide);
18+ const dirPath = resolveLsToolDirPath(args?.dirPath);
19+ const uri = await resolveRelativePathInDir(dirPath, extras.ide);
720 if (!uri) {
821 throw new Error(
9- `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`,
22+ `Directory ${args.dirPath} not found. Make sure to use forward-slash paths`,
1023 );
1124 }
1225
1326 const entries = await walkDir(uri, extras.ide, {
1427 returnRelativeUrisPaths: true,
1528 include: "both",
16- recursive: args.recursive ?? false,
29+ recursive: args?.recursive ?? false,
1730 });
1831
19- const content =
20- entries.length > 0
21- ? entries.join("\n")
22- : `No files/folders found in ${args.dirPath}`;
32+ const lines = entries.slice(0, MAX_LS_TOOL_LINES);
2333
24- return [
34+ let content =
35+ lines.length > 0
36+ ? lines.join("\n")
37+ : `No files/folders found in ${dirPath}`;
38+
39+ const contextItems = [
2540 {
2641 name: "File/folder list",
27- description: `Files/folders in ${args.dirPath}`,
42+ description: `Files/folders in ${dirPath}`,
2843 content,
2944 },
3045 ];
46+
47+ if (entries.length > MAX_LS_TOOL_LINES) {
48+ let warningContent = `${entries.length - MAX_LS_TOOL_LINES} ls entries were truncated`;
49+ if (args?.recursive) {
50+ warningContent += ". Try using a non-recursive search";
51+ }
52+ contextItems.push({
53+ name: "ls truncation warning",
54+ description: "Informs the model that ls results were truncated",
55+ content: warningContent,
56+ });
57+ }
58+
59+ return contextItems;
3160 };
added core/tools/implementations/lsTool.vitest.ts +96 −0
@@ -0,0 +1,96 @@
1+import { expect, test, vi } from "vitest";
2+import { ToolExtras } from "../..";
3+import * as walkDirModule from "../../indexing/walkDir";
4+import { lsToolImpl, resolveLsToolDirPath } from "./lsTool";
5+
6+vi.mock("../../indexing/walkDir");
7+
8+const mockExtras = {
9+ ide: {
10+ fileExists: async (path: string) => true,
11+ getWorkspaceDirs: async () => ["dir1"],
12+ },
13+} as unknown as ToolExtras;
14+
15+test("resolveLsToolDirPath handles undefined path", () => {
16+ expect(resolveLsToolDirPath(undefined)).toBe("/");
17+});
18+
19+test("resolveLsToolDirPath handles empty string", () => {
20+ expect(resolveLsToolDirPath("")).toBe("/");
21+});
22+
23+test("resolveLsToolDirPath handles dot", () => {
24+ expect(resolveLsToolDirPath(".")).toBe("/");
25+});
26+
27+test("resolveLsToolDirPath handles dot relative", () => {
28+ expect(resolveLsToolDirPath("./hi")).toBe("/hi");
29+});
30+
31+test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => {
32+ expect(resolveLsToolDirPath("path\\to\\dir")).toBe("path/to/dir");
33+});
34+
35+test("resolveLsToolDirPath preserves forward slashes", () => {
36+ expect(resolveLsToolDirPath("path/to/dir")).toBe("path/to/dir");
37+});
38+
39+test("lsToolImpl truncates output when entries exceed MAX_LS_TOOL_LINES", async () => {
40+ // Generate more than MAX_LS_TOOL_LINES entries (which is 200)
41+ const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
42+
43+ // Mock walkDir to return our large array
44+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
45+
46+ const result = await lsToolImpl(
47+ { dirPath: "testDir", recursive: true },
48+ mockExtras,
49+ );
50+
51+ // Check that the result contains the truncation message
52+ expect(result.length).toBe(2);
53+ expect(result[0].content).toContain("file1.txt");
54+ expect(result[0].content).toContain("file199.txt");
55+ expect(result[1].content).toContain("Try using a non-recursive search");
56+ expect(result[1].content).toContain("50 ls entries were truncated");
57+
58+ // Check that only MAX_LS_TOOL_LINES entries are included
59+ const contentLines = result[0].content.split("\n");
60+ // Account for the truncation message line
61+ expect(contentLines.length).toBe(200);
62+
63+ // Check the suggestion to use non-recursive search is included
64+ expect(result[1].content).toContain("Try using a non-recursive search");
65+});
66+
67+test("lsToolImpl shows truncation message without suggestion for non-recursive search", async () => {
68+ // Generate more than MAX_LS_TOOL_LINES entries
69+ const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
70+
71+ // Mock walkDir to return our large array
72+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
73+
74+ const result = await lsToolImpl(
75+ { dirPath: "testDir", recursive: false },
76+ mockExtras,
77+ );
78+
79+ // Check that the result contains the truncation message
80+ expect(result.length).toBe(2);
81+ expect(result[1].content).toContain("50 ls entries were truncated");
82+
83+ // Check that the suggestion to use non-recursive search is NOT included
84+ expect(result[1].content).not.toContain("Try using a non-recursive search");
85+});
86+
87+test("lsToolImpl shows message when no files are found", async () => {
88+ // Mock walkDir to return empty array
89+ vi.spyOn(walkDirModule, "walkDir").mockResolvedValue([]);
90+
91+ const result = await lsToolImpl({ dirPath: "emptyDir" }, mockExtras);
92+
93+ // Check that the result contains the "no files found" message
94+ expect(result.length).toBe(1);
95+ expect(result[0].content).toBe("No files/folders found in emptyDir");
96+});
modified core/tools/implementations/readCurrentlyOpenFile.ts +31 −18
@@ -1,28 +1,41 @@
11 import { getUriDescription } from "../../util/uri";
22
33 import { ToolImpl } from ".";
4+import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
45
56 export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
67 const result = await extras.ide.getCurrentFile();
78
8- if (!result) {
9- return [];
10- }
9+ if (result) {
10+ await throwIfFileExceedsHalfOfContext(
11+ result.path,
12+ result.contents,
13+ extras.config.selectedModelByRole.chat,
14+ );
15+
16+ const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
17+ result.path,
18+ await extras.ide.getWorkspaceDirs(),
19+ );
1120
12- const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
13- result.path,
14- await extras.ide.getWorkspaceDirs(),
15- );
16-
17- return [
18- {
19- name: `Current file: ${baseName}`,
20- description: last2Parts,
21- content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
22- uri: {
23- type: "file",
24- value: result.path,
21+ return [
22+ {
23+ name: `Current file: ${baseName}`,
24+ description: last2Parts,
25+ content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
26+ uri: {
27+ type: "file",
28+ value: result.path,
29+ },
2530 },
26- },
27- ];
31+ ];
32+ } else {
33+ return [
34+ {
35+ name: `No Current File`,
36+ description: "",
37+ content: "There are no files currently open.",
38+ },
39+ ];
40+ }
2841 };
modified core/tools/implementations/readFile.ts +8 −0
@@ -2,6 +2,7 @@
22 import { getUriPathBasename } from "../../util/uri";
33
44 import { ToolImpl } from ".";
5+import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
56
67 export const readFileImpl: ToolImpl = async (args, extras) => {
78 const firstUriMatch = await resolveRelativePathInDir(
@@ -12,6 +13,13 @@
1213 throw new Error(`Could not find file ${args.filepath}`);
1314 }
1415 const content = await extras.ide.readFile(firstUriMatch);
16+
17+ await throwIfFileExceedsHalfOfContext(
18+ args.filepath,
19+ content,
20+ extras.config.selectedModelByRole.chat,
21+ );
22+
1523 return [
1624 {
1725 name: getUriPathBasename(args.filepath),
added core/tools/implementations/readFileLimit.ts +18 −0
@@ -0,0 +1,18 @@
1+import { ILLM } from "../..";
2+import { countTokensAsync } from "../../llm/countTokens";
3+
4+export async function throwIfFileExceedsHalfOfContext(
5+ filepath: string,
6+ content: string,
7+ model: ILLM | null,
8+) {
9+ if (model) {
10+ const tokens = await countTokensAsync(content, model.title);
11+ const tokenLimit = model.contextLength / 2;
12+ if (tokens > tokenLimit) {
13+ throw new Error(
14+ `File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`,
15+ );
16+ }
17+ }
18+}
modified core/tools/implementations/requestRule.ts +3 −7
@@ -1,5 +1,4 @@
11 import { ToolImpl } from ".";
2-import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
32
43 export const requestRuleImpl: ToolImpl = async (args, extras) => {
54 // Find the rule by name in the config
@@ -11,14 +10,11 @@
1110 );
1211 }
1312
14- const fileContent = await extras.ide.readFile(rule.ruleFile);
15- const { markdown, frontmatter } = parseMarkdownRule(fileContent);
16-
1713 return [
1814 {
19- name: frontmatter.name ?? "",
20- description: frontmatter.description ?? "",
21- content: markdown,
15+ name: rule.name ?? "",
16+ description: rule.description ?? "",
17+ content: rule.rule,
2218 uri: {
2319 type: "file",
2420 value: rule.ruleFile,
modified core/tools/implementations/runTerminalCommand.ts +63 −47
@@ -10,6 +10,16 @@
1010
1111 const asyncExec = util.promisify(childProcess.exec);
1212
13+// Add color-supporting environment variables
14+const getColorEnv = () => ({
15+ ...process.env,
16+ FORCE_COLOR: "1",
17+ COLORTERM: "truecolor",
18+ TERM: "xterm-256color",
19+ CLICOLOR: "1",
20+ CLICOLOR_FORCE: "1",
21+});
22+
1323 const ENABLED_FOR_REMOTES = [
1424 "",
1525 "local",
@@ -56,10 +66,11 @@
5666 }
5767 }
5868
59- // Use spawn instead of exec to get streaming output
69+ // Use spawn with color environment
6070 const childProc = childProcess.spawn(args.command, {
6171 cwd,
6272 shell: true,
73+ env: getColorEnv(), // Add enhanced environment for colors
6374 });
6475
6576 childProc.stdout?.on("data", (data) => {
@@ -130,26 +141,7 @@
130141 return;
131142 }
132143
133- if (!waitForCompletion) {
134- // Already resolved, just update the UI with final output
135- if (extras.onPartialOutput) {
136- const status =
137- code === 0 || !code
138- ? "\nBackground command completed"
139- : `\nBackground command failed with exit code ${code}`;
140- extras.onPartialOutput({
141- toolCallId,
142- contextItems: [
143- {
144- name: "Terminal",
145- description: "Terminal command output",
146- content: terminalOutput,
147- status: status,
148- },
149- ],
150- });
151- }
152- } else {
144+ if (waitForCompletion) {
153145 // Normal completion, resolve now
154146 if (code === 0) {
155147 const status = "Command completed";
@@ -172,6 +164,25 @@
172164 },
173165 ]);
174166 }
167+ } else {
168+ // Already resolved, just update the UI with final output
169+ if (extras.onPartialOutput) {
170+ const status =
171+ code === 0 || !code
172+ ? "\nBackground command completed"
173+ : `\nBackground command failed with exit code ${code}`;
174+ extras.onPartialOutput({
175+ toolCallId,
176+ contextItems: [
177+ {
178+ name: "Terminal",
179+ description: "Terminal command output",
180+ content: terminalOutput,
181+ status: status,
182+ },
183+ ],
184+ });
185+ }
175186 }
176187 });
177188
@@ -197,14 +208,43 @@
197208 const workspaceDirs = await extras.ide.getWorkspaceDirs();
198209 const cwd = fileURLToPath(workspaceDirs[0]);
199210
200- if (!waitForCompletion) {
211+ if (waitForCompletion) {
212+ // Standard execution, waiting for completion
213+ try {
214+ // Use color environment for exec as well
215+ const output = await asyncExec(args.command, {
216+ cwd,
217+ env: getColorEnv(),
218+ });
219+ const status = "Command completed";
220+ return [
221+ {
222+ name: "Terminal",
223+ description: "Terminal command output",
224+ content: output.stdout ?? "",
225+ status: status,
226+ },
227+ ];
228+ } catch (error: any) {
229+ const status = `Command failed with: ${error.message || error.toString()}`;
230+ return [
231+ {
232+ name: "Terminal",
233+ description: "Terminal command output",
234+ content: error.stderr ?? error.toString(),
235+ status: status,
236+ },
237+ ];
238+ }
239+ } else {
201240 // For non-streaming but also not waiting for completion, use spawn
202241 // but don't attach any listeners other than error
203242 try {
204- // Use spawn instead of exec but don't wait
243+ // Use spawn with color environment
205244 const childProc = childProcess.spawn(args.command, {
206245 cwd,
207246 shell: true,
247+ env: getColorEnv(), // Add color environment
208248 // Detach the process so it's not tied to the parent
209249 detached: true,
210250 // Redirect to /dev/null equivalent (works cross-platform)
@@ -246,30 +286,6 @@
246286 },
247287 ];
248288 }
249- } else {
250- // Standard execution, waiting for completion
251- try {
252- const output = await asyncExec(args.command, { cwd });
253- const status = "Command completed";
254- return [
255- {
256- name: "Terminal",
257- description: "Terminal command output",
258- content: output.stdout ?? "",
259- status: status,
260- },
261- ];
262- } catch (error: any) {
263- const status = `Command failed with: ${error.message || error.toString()}`;
264- return [
265- {
266- name: "Terminal",
267- description: "Terminal command output",
268- content: error.stderr ?? error.toString(),
269- status: status,
270- },
271- ];
272- }
273289 }
274290 }
275291 }
modified core/tools/implementations/searchWeb.ts +30 −2
@@ -1,8 +1,36 @@
1+import { ToolImpl } from ".";
12 import { fetchSearchResults } from "../../context/providers/WebContextProvider";
23
3-import { ToolImpl } from ".";
4+const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
45
56 export const searchWebImpl: ToolImpl = async (args, extras) => {
67 const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
7- return webResults;
8+
9+ // Track truncated results
10+ const truncatedResults: string[] = [];
11+
12+ // Check and truncate each result
13+ const processedResults = webResults.map((result, index) => {
14+ if (result.content.length > DEFAULT_WEB_SEARCH_CHAR_LIMIT) {
15+ truncatedResults.push(
16+ result.name || result.description || `Result #${index + 1}`,
17+ );
18+ return {
19+ ...result,
20+ content: result.content.substring(0, DEFAULT_WEB_SEARCH_CHAR_LIMIT),
21+ };
22+ }
23+ return result;
24+ });
25+
26+ // Add truncation warning if needed
27+ if (truncatedResults.length > 0) {
28+ processedResults.push({
29+ name: "Web search truncation warning",
30+ description: "Informs that search results were truncated",
31+ content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`,
32+ });
33+ }
34+
35+ return processedResults;
836 };
added core/tools/implementations/searchWeb.vitest.ts +107 −0
@@ -0,0 +1,107 @@
1+import { expect, test, vi } from "vitest";
2+import { searchWebImpl } from "./searchWeb";
3+
4+// Mock the fetchSearchResults function
5+vi.mock("../../context/providers/WebContextProvider", () => ({
6+ fetchSearchResults: vi.fn(),
7+}));
8+const mockExtras = {
9+ fetch: vi.fn() as any,
10+ ide: {} as any,
11+} as unknown as ToolExtras;
12+
13+import { ToolExtras } from "../..";
14+import { fetchSearchResults } from "../../context/providers/WebContextProvider";
15+
16+test("searchWeb should not truncate results under character limit", async () => {
17+ const shortContent = "This is a short search result content";
18+ const mockSearchResults = [
19+ {
20+ name: "Result 1",
21+ description: "Search result description 1",
22+ content: shortContent,
23+ },
24+ {
25+ name: "Result 2",
26+ description: "Search result description 2",
27+ content: shortContent,
28+ },
29+ ];
30+
31+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
32+
33+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
34+
35+ expect(result).toHaveLength(2);
36+ expect(result[0].content).toBe(shortContent);
37+ expect(result[1].content).toBe(shortContent);
38+});
39+
40+test("searchWeb should truncate results exceeding character limit", async () => {
41+ const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
42+ // Create a string exceeding the character limit
43+ const longContent = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
44+ const shortContent = "This is a short search result content";
45+ const mockSearchResults = [
46+ {
47+ name: "Result 1",
48+ description: "Search result description 1",
49+ content: longContent,
50+ },
51+ {
52+ name: "Result 2",
53+ description: "Search result description 2",
54+ content: shortContent,
55+ },
56+ ];
57+
58+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
59+
60+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
61+
62+ expect(result).toHaveLength(3); // Two results + warning
63+ expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
64+ expect(result[1].content).toBe(shortContent);
65+ expect(result[2].name).toBe("Web search truncation warning");
66+ expect(result[2].content).toContain("truncated");
67+ expect(result[2].content).toContain("Result 1");
68+ expect(result[2].content).not.toContain("Result 2");
69+});
70+
71+test("searchWeb should include all truncated results in the warning", async () => {
72+ const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
73+ // Create strings exceeding the character limit
74+ const longContent1 = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 500);
75+ const longContent2 = "b".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
76+ const shortContent = "This is a short search result content";
77+ const mockSearchResults = [
78+ {
79+ name: "Result 1",
80+ description: "Search result description 1",
81+ content: longContent1,
82+ },
83+ {
84+ name: "Result 2",
85+ description: "Search result description 2",
86+ content: longContent2,
87+ },
88+ {
89+ name: "Result 3",
90+ description: "Search result description 3",
91+ content: shortContent,
92+ },
93+ ];
94+
95+ (fetchSearchResults as any).mockResolvedValue(mockSearchResults);
96+
97+ const result = await searchWebImpl({ query: "test query" }, mockExtras);
98+
99+ expect(result).toHaveLength(4); // Three results + warning
100+ expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
101+ expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
102+ expect(result[2].content).toBe(shortContent);
103+ expect(result[3].name).toBe("Web search truncation warning");
104+ expect(result[3].content).toContain("Result 1");
105+ expect(result[3].content).toContain("Result 2");
106+ expect(result[3].content).not.toContain("Result 3");
107+});
modified core/tools/implementations/viewDiff.ts +26 −2
@@ -1,15 +1,39 @@
11 import { ToolImpl } from ".";
2+import { ContextItem } from "../..";
23 import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
34
5+export const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
6+
47 export const viewDiffImpl: ToolImpl = async (args, extras) => {
58 const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true);
69 // TODO includeUnstaged should be an option
710
8- return [
11+ const combinedDiff = diffs.join("\n");
12+ const diffLines = combinedDiff.split("\n");
13+
14+ let truncated = false;
15+ let processedDiff = combinedDiff;
16+
17+ if (diffLines.length > DEFAULT_GIT_DIFF_LINE_LIMIT) {
18+ truncated = true;
19+ processedDiff = diffLines.slice(0, DEFAULT_GIT_DIFF_LINE_LIMIT).join("\n");
20+ }
21+
22+ const contextItems: ContextItem[] = [
923 {
1024 name: "Diff",
1125 description: "The current git diff",
12- content: diffs.join("\n"),
26+ content: processedDiff,
1327 },
1428 ];
29+
30+ if (truncated) {
31+ contextItems.push({
32+ name: "Diff truncation warning",
33+ description: "Informs that git diff was truncated",
34+ content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
35+ });
36+ }
37+
38+ return contextItems;
1539 };
added core/tools/implementations/viewDiff.vitest.ts +87 −0
@@ -0,0 +1,87 @@
1+import { expect, test, vi } from "vitest";
2+import { DEFAULT_GIT_DIFF_LINE_LIMIT, viewDiffImpl } from "./viewDiff";
3+
4+// Mock the getDiffsFromCache function
5+vi.mock("../../autocomplete/snippets/gitDiffCache", () => ({
6+ getDiffsFromCache: vi.fn(),
7+}));
8+
9+import { ToolExtras } from "../..";
10+import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
11+const mockExtras = {
12+ fetch: vi.fn() as any,
13+ ide: {} as any,
14+} as unknown as ToolExtras;
15+
16+test("viewDiff should not truncate diffs under line limit", async () => {
17+ // Create a small diff with just a few lines
18+ const smallDiff = [
19+ "diff --git a/file1.txt b/file1.txt",
20+ "index 1234..5678 100644",
21+ "--- a/file1.txt",
22+ "+++ b/file1.txt",
23+ "@@ -1,3 +1,4 @@",
24+ " line1",
25+ "-line2",
26+ "+line2 modified",
27+ "+line3 added",
28+ ];
29+
30+ (getDiffsFromCache as any).mockResolvedValue(smallDiff);
31+
32+ const result = await viewDiffImpl({}, mockExtras);
33+
34+ expect(result).toHaveLength(1); // Just the diff, no warning
35+ expect(result[0].name).toBe("Diff");
36+ expect(result[0].content).toBe(smallDiff.join("\n"));
37+});
38+
39+test("viewDiff should truncate diffs exceeding line limit", async () => {
40+ // Create a large diff that exceeds the line limit
41+ const largeDiffLines = Array(DEFAULT_GIT_DIFF_LINE_LIMIT + 1000).fill(
42+ "line content",
43+ );
44+ const largeDiff = [
45+ "diff --git a/file1.txt b/file1.txt",
46+ "index 1234..5678 100644",
47+ ...largeDiffLines,
48+ ];
49+
50+ (getDiffsFromCache as any).mockResolvedValue([largeDiff.join("\n")]);
51+
52+ const result = await viewDiffImpl({}, mockExtras);
53+
54+ expect(result).toHaveLength(2); // Diff + warning
55+
56+ // Count the number of lines in the result
57+ const resultLines = result[0].content.split("\n");
58+ expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
59+
60+ // Check the warning
61+ expect(result[1].name).toBe("Diff truncation warning");
62+ expect(result[1].content).toContain("truncated");
63+ expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
64+});
65+
66+test("viewDiff should handle multiple diffs correctly", async () => {
67+ const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
68+
69+ // Create multiple diffs that together exceed the line limit
70+ const diff1Lines = Array(3000).fill("diff1 line");
71+ const diff2Lines = Array(3000).fill("diff2 line");
72+ const diff1 = diff1Lines.join("\n");
73+ const diff2 = diff2Lines.join("\n");
74+
75+ (getDiffsFromCache as any).mockResolvedValue([diff1, diff2]);
76+
77+ const result = await viewDiffImpl({}, mockExtras);
78+
79+ expect(result).toHaveLength(2); // Diff + warning
80+
81+ // Count the number of lines in the result
82+ const resultLines = result[0].content.split("\n");
83+ expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
84+
85+ // Check the warning
86+ expect(result[1].name).toBe("Diff truncation warning");
87+});
modified core/tools/index.ts +26 −8
@@ -1,4 +1,5 @@
1-import { ConfigDependentToolParams, Tool } from "..";
1+import { ConfigDependentToolParams, IDE, Tool } from "..";
2+import { codebaseTool } from "./definitions/codebaseTool";
23 import { createNewFileTool } from "./definitions/createNewFile";
34 import { createRuleBlock } from "./definitions/createRuleBlock";
45 import { editFileTool } from "./definitions/editFile";
@@ -10,15 +11,21 @@
1011 import { readFileTool } from "./definitions/readFile";
1112 import { requestRuleTool } from "./definitions/requestRule";
1213 import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
14+import { searchAndReplaceInFileTool } from "./definitions/searchAndReplaceInFile";
1315 import { searchWebTool } from "./definitions/searchWeb";
1416 import { viewDiffTool } from "./definitions/viewDiff";
17+import { viewRepoMapTool } from "./definitions/viewRepoMap";
18+import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
1519
16-export const baseToolDefinitions = [
20+// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
21+
22+// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
23+const getLocalOnlyToolDefinitions = () => [grepSearchTool];
24+
25+const getBaseToolDefinitions = () => [
1726 readFileTool,
18- editFileTool,
1927 createNewFileTool,
2028 runTerminalCommandTool,
21- grepSearchTool,
2229 globSearchTool,
2330 searchWebTool,
2431 viewDiffTool,
@@ -26,11 +33,22 @@
2633 lsTool,
2734 createRuleBlock,
2835 fetchUrlContentTool,
29- // replacing with ls tool for now
30- // viewSubdirectoryTool,
31- // viewRepoMapTool,
3236 ];
3337
3438 export const getConfigDependentToolDefinitions = (
3539 params: ConfigDependentToolParams,
36-): Tool[] => [requestRuleTool(params)];
40+): Tool[] => [
41+ requestRuleTool(params),
42+ // Search and replace is now generally available
43+ searchAndReplaceInFileTool,
44+ // Keep edit file tool available for models that need it
45+ editFileTool,
46+ ...(params.enableExperimentalTools
47+ ? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
48+ : []),
49+];
50+
51+export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>
52+ (await ide.isWorkspaceRemote())
53+ ? getBaseToolDefinitions()
54+ : [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()];
modified core/tools/parseArgs.ts +4 −4
@@ -4,11 +4,11 @@
44 toolCall: ToolCallDelta,
55 ): Record<string, any> {
66 try {
7- return JSON.parse(toolCall.function?.arguments ?? "{}");
7+ return JSON.parse(toolCall.function?.arguments?.trim() || "{}");
88 } catch (e) {
9- console.error(
10- `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`,
11- );
9+ //console.error(
10+ // `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`,
11+ //);
1212 return {};
1313 }
1414 }
deleted core/util/abortManager.ts +0 −37
@@ -1,37 +0,0 @@
1-export class StreamAbortManager {
2- private static instance: StreamAbortManager;
3- private controllers: Map<string, AbortController>;
4-
5- private constructor() {
6- this.controllers = new Map();
7- }
8-
9- public static getInstance(): StreamAbortManager {
10- if (!StreamAbortManager.instance) {
11- StreamAbortManager.instance = new StreamAbortManager();
12- }
13- return StreamAbortManager.instance;
14- }
15-
16- public get(id: string): AbortController {
17- let controller = this.controllers.get(id);
18- if (!controller) {
19- controller = new AbortController();
20- this.controllers.set(id, controller);
21- }
22- return controller;
23- }
24-
25- public abort(id: string): void {
26- const controller = this.controllers.get(id);
27- if (controller) {
28- controller.abort();
29- this.controllers.delete(id);
30- }
31- }
32-
33- public clear(): void {
34- this.controllers.forEach((controller) => controller.abort());
35- this.controllers.clear();
36- }
37-}
modified core/util/filesystem.ts +9 −2
@@ -48,6 +48,10 @@
4848 return;
4949 }
5050
51+ isWorkspaceRemote(): Promise<boolean> {
52+ return Promise.resolve(false);
53+ }
54+
5155 async getIdeSettings(): Promise<IdeSettings> {
5256 return {
5357 remoteConfigServerUrl: undefined,
@@ -234,11 +238,14 @@
234238 return Promise.resolve([]);
235239 }
236240
237- async getSearchResults(query: string): Promise<string> {
241+ async getSearchResults(query: string, maxResults?: number): Promise<string> {
238242 return "";
239243 }
240244
241- async getFileResults(pattern: string): Promise<string[]> {
245+ async getFileResults(
246+ pattern: string,
247+ maxResults?: number,
248+ ): Promise<string[]> {
242249 return [];
243250 }
244251
modified core/util/findLast.ts +3 −3
@@ -1,6 +1,6 @@
1-export function findLastIndex(
2- arr: any[],
3- criterion: (item: any) => boolean,
1+export function findLastIndex<T = any>(
2+ arr: T[],
3+ criterion: (item: T) => boolean,
44 ): number {
55 let lastIndex = -1;
66
modified core/util/grepSearch.ts +31 −2
@@ -1,4 +1,19 @@
1-export function formatGrepSearchResults(results: string): string {
1+/*
2+ Formats the output of a grep search to reduce unnecessary indentation, lines, etc
3+ Assumes a command with these params
4+ ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
5+
6+ Also can truncate the output to a specified number of characters
7+*/
8+export function formatGrepSearchResults(
9+ results: string,
10+ maxChars?: number,
11+): {
12+ formatted: string;
13+ numResults: number;
14+ truncated: boolean;
15+} {
16+ let numResults = 0;
217 const keepLines: string[] = [];
318
419 function countLeadingSpaces(line: string) {
@@ -45,6 +60,7 @@
4560 if (line.startsWith("./") || line === "--") {
4661 processResult(resultLines); // process previous result
4762 resultLines = [line];
63+ numResults++;
4864 continue;
4965 }
5066
@@ -57,5 +73,18 @@
5773 }
5874 processResult(resultLines);
5975
60- return keepLines.join("\n");
76+ const formatted = keepLines.join("\n");
77+ if (maxChars && formatted.length > maxChars) {
78+ return {
79+ formatted: formatted.substring(0, maxChars),
80+ numResults,
81+ truncated: true,
82+ };
83+ } else {
84+ return {
85+ formatted,
86+ numResults,
87+ truncated: false,
88+ };
89+ }
6190 }
added core/util/grepSearch.vitest.ts +217 −0
@@ -0,0 +1,217 @@
1+import { expect, test } from "vitest";
2+import { formatGrepSearchResults } from "./grepSearch";
3+
4+// Sample grep output mimicking what would come from ripgrep with the params:
5+// ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
6+const sampleGrepOutput = `./program.cs
7+ Console.WriteLine("Hello World!");
8+ Calculator calc = new Calculator();
9+ calc.Add(5).Subtract(3);
10+ Console.WriteLine("Result: " + calc.GetResult());
11+ }
12+--
13+ }
14+
15+ public Calculator Subtract(double number)
16+ {
17+ result -= number;
18+
19+./test.kt
20+ }
21+
22+ fun subtract(number: Double): Test {
23+ result -= number
24+ return this
25+
26+./test.php
27+ }
28+
29+ public function subtract($number) {
30+ $this->result -= $number;
31+ return $this;
32+--
33+
34+$calc = new Calculator();
35+$calc->add(10)->subtract(5);
36+echo "Result: " . $calc->getResult() . "\n";
37+
38+
39+./Calculator.java
40+ }
41+
42+ public Calculator subtract(double number) {
43+ result -= number;
44+ return this;
45+--
46+ public static void main(String[] args) {
47+ Calculator calc = new Calculator();
48+ calc.add(10).subtract(5);
49+ System.out.println("Result: " + calc.getResult());
50+ }
51+
52+./calculator_test/Calculator.java
53+ }
54+
55+ public int subtract(int a, int b) {
56+ return a - b;
57+ }
58+
59+./test.rb
60+ end
61+
62+ def subtract(number)
63+ @result -= number
64+ self
65+--
66+
67+calc = Calculator.new
68+calc.add(5).subtract(3)
69+puts "Result: #{calc.get_result}"
70+
71+./test.js
72+ return this;
73+ }
74+ subtract(number) {
75+ return this;
76+ }
77+
78+./test.py
79+ return self
80+
81+ def subtract(self, number):
82+ self.result -= number
83+ return self
84+
85+./test.ts
86+ }
87+
88+ subtract(number: number): Calculator {
89+ this.result -= number;
90+ return this;`;
91+
92+test("formats grep search results correctly", () => {
93+ const result = formatGrepSearchResults(sampleGrepOutput);
94+
95+ expect(result.numResults).toBe(13); // 4 file paths in the sample
96+ expect(result.truncated).toBe(false);
97+
98+ // Check that all file paths are preserved
99+ expect(result.formatted).toContain("./program.cs");
100+ expect(result.formatted).toContain("./test.kt");
101+ expect(result.formatted).toContain("./test.php");
102+ expect(result.formatted).toContain("./Calculator.java");
103+
104+ // Check that content is preserved and properly indented
105+ expect(result.formatted).toContain('Console.WriteLine("Hello World!");');
106+ expect(result.formatted).toContain("fun subtract(number: Double): Test {");
107+ expect(result.formatted).toContain("public function subtract($number) {");
108+ expect(result.formatted).toContain(
109+ "public Calculator subtract(double number) {",
110+ );
111+});
112+
113+test("handles empty input", () => {
114+ const result = formatGrepSearchResults("");
115+
116+ expect(result.numResults).toBe(0);
117+ expect(result.truncated).toBe(false);
118+ expect(result.formatted).toBe("");
119+});
120+
121+test("handles input with only file paths (no content) - lines should be skipped", () => {
122+ const input =
123+ "./empty-file.ts\n./another-empty.js\n./has-content.ts\n searchMatch";
124+ const result = formatGrepSearchResults(input);
125+
126+ expect(result.numResults).toBe(3);
127+ expect(result.formatted).toBe("./has-content.ts\n searchMatch");
128+});
129+
130+test("truncates output when exceeding maxChars", () => {
131+ const maxChars = 50;
132+ const result = formatGrepSearchResults(sampleGrepOutput, maxChars);
133+
134+ expect(result.truncated).toBe(true);
135+ expect(result.formatted.length).toBe(maxChars);
136+});
137+
138+test("normalizes indentation to 2 spaces", () => {
139+ const input = `./file.ts
140+ function test() {
141+ const x = 1;
142+ console.log(x);
143+ }`;
144+
145+ const result = formatGrepSearchResults(input);
146+
147+ // The function should normalize the indentation to 2 spaces
148+ expect(result.formatted).toContain("./file.ts");
149+ expect(result.formatted).toContain(" function test() {");
150+ expect(result.formatted).toContain(" const x = 1;");
151+ expect(result.formatted).toContain(" console.log(x);");
152+ expect(result.formatted).toContain(" }");
153+});
154+
155+test("skips leading single-char or empty lines after file paths", () => {
156+ const input = `./file.ts
157+
158+function test() {
159+ console.log("test");
160+}`;
161+
162+ const result = formatGrepSearchResults(input);
163+
164+ expect(result.formatted).toContain("./file.ts");
165+ expect(result.formatted).not.toContain("\n \n"); // The single space line should be skipped
166+ expect(result.formatted).toContain("function test() {");
167+});
168+
169+test("processes separator lines correctly", () => {
170+ const input = `./file1.ts
171+function one() {
172+ return 1;
173+}
174+--
175+function two() {
176+ return 2;
177+}
178+
179+./file2.ts
180+class Test {
181+ method() {}
182+}`;
183+
184+ const result = formatGrepSearchResults(input);
185+
186+ expect(result.numResults).toBe(3);
187+ expect(result.formatted).toContain("./file1.ts");
188+ expect(result.formatted).toContain("--");
189+ expect(result.formatted).toContain("function two() {");
190+ expect(result.formatted).toContain("./file2.ts");
191+});
192+
193+test("increases indentation when original is less than 2 spaces", () => {
194+ const input = `./minimal-indent.ts
195+function test() {
196+ singleSpaceIndent();
197+}`;
198+
199+ const result = formatGrepSearchResults(input);
200+
201+ expect(result.formatted).toContain(" function test() {");
202+ expect(result.formatted).toContain(" singleSpaceIndent();");
203+ expect(result.formatted).toContain(" }");
204+});
205+
206+test("decreases indentation when original is more than 2 spaces", () => {
207+ const input = `./excessive-indent.ts
208+ function test() {
209+ tooMuchIndent();
210+ }`;
211+
212+ const result = formatGrepSearchResults(input);
213+
214+ expect(result.formatted).toContain(" function test() {");
215+ expect(result.formatted).toContain(" tooMuchIndent();");
216+ expect(result.formatted).toContain(" }");
217+});
added core/util/handlebars/handlebarUtils.ts +111 −0
@@ -0,0 +1,111 @@
1+import { v4 as uuidv4 } from "uuid";
2+
3+export type HandlebarsType = typeof import("handlebars");
4+
5+function convertToLetter(num: number): string {
6+ let result = "";
7+ while (num > 0) {
8+ const remainder = (num - 1) % 26;
9+ result = String.fromCharCode(97 + remainder) + result;
10+ num = Math.floor((num - 1) / 26);
11+ }
12+ return result;
13+}
14+
15+export function registerHelpers(
16+ handlebars: HandlebarsType,
17+ helpers: Array<[string, Handlebars.HelperDelegate]>,
18+): {
19+ [key: string]: Promise<string>;
20+} {
21+ const promises: { [key: string]: Promise<string> } = {};
22+
23+ for (const [name, helper] of helpers) {
24+ handlebars.registerHelper(name, (...args) => {
25+ const id = uuidv4();
26+ promises[id] = helper(...args);
27+ return `__${id}__`;
28+ });
29+ }
30+
31+ return promises;
32+}
33+
34+export async function prepareTemplatedFilepaths(
35+ handlebars: HandlebarsType,
36+ template: string,
37+ inputData: Record<string, string>,
38+ ctxProviderNames: string[],
39+ readFile: (filepath: string) => Promise<string>,
40+ getUriFromPath: (path: string) => Promise<string | undefined>,
41+) {
42+ // First, replace filepaths with letters to avoid escaping issues
43+ const ast = handlebars.parse(template);
44+
45+ const filepathLetters: Map<string, string> = new Map();
46+ const requiredContextProviders: Set<string> = new Set();
47+ let withLetterKeys = template;
48+
49+ let letterIndex = 1;
50+
51+ for (const i in ast.body) {
52+ const node = ast.body[i] as any;
53+
54+ if (node.type === "MustacheStatement") {
55+ const originalNodeVal = node.path.original;
56+ if (originalNodeVal.toLowerCase() === "input") {
57+ continue;
58+ }
59+ const isFilepath = !ctxProviderNames.includes(originalNodeVal);
60+
61+ if (isFilepath) {
62+ const letter = convertToLetter(letterIndex);
63+
64+ filepathLetters.set(letter, originalNodeVal);
65+
66+ withLetterKeys = withLetterKeys.replace(
67+ new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
68+ `{{${letter}}}`,
69+ );
70+
71+ letterIndex++;
72+ } else {
73+ requiredContextProviders.add(originalNodeVal);
74+ }
75+ }
76+ }
77+
78+ // Then, resolve the filepaths to their actual content and add to template data
79+ // Fallback to simple error string if file read fails
80+ const templateData = { ...inputData };
81+
82+ for (const [letter, filepath] of filepathLetters.entries()) {
83+ try {
84+ const uri = await getUriFromPath(filepath);
85+ if (uri) {
86+ const fileContents = await readFile(uri);
87+ templateData[letter] = fileContents;
88+ } else {
89+ throw new Error(`File not found: ${filepath}`);
90+ }
91+ } catch (e) {
92+ console.error(`Error reading file in prompt file ${filepath}:`, e);
93+ templateData[letter] = `[Error reading file "${filepath}"]`;
94+ }
95+ }
96+
97+ return { withLetterKeys, templateData, requiredContextProviders };
98+}
99+
100+export async function resolveHelperPromises(
101+ renderedString: string,
102+ promises: { [key: string]: Promise<string> },
103+): Promise<string> {
104+ await Promise.all(Object.values(promises));
105+
106+ for (const id in promises) {
107+ renderedString = renderedString.replace(`__${id}__`, await promises[id]);
108+ }
109+
110+ return renderedString;
111+}
added core/util/handlebars/renderTemplatedString.ts +35 −0
@@ -0,0 +1,35 @@
1+import {
2+ prepareTemplatedFilepaths,
3+ registerHelpers,
4+ resolveHelperPromises,
5+ type HandlebarsType,
6+} from "./handlebarUtils";
7+
8+export async function renderTemplatedString(
9+ handlebars: HandlebarsType,
10+ template: string,
11+ inputData: Record<string, string>,
12+ availableHelpers: Array<[string, Handlebars.HelperDelegate]>,
13+ readFile: (filepath: string) => Promise<string>,
14+ getUriFromPath: (path: string) => Promise<string | undefined>,
15+): Promise<string> {
16+ const helperPromises = availableHelpers
17+ ? registerHelpers(handlebars, availableHelpers)
18+ : {};
19+
20+ const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
21+
22+ const { withLetterKeys, templateData } = await prepareTemplatedFilepaths(
23+ handlebars,
24+ template,
25+ inputData,
26+ ctxProviderNames,
27+ readFile,
28+ getUriFromPath,
29+ );
30+
31+ const templateFn = handlebars.compile(withLetterKeys);
32+ const renderedString = templateFn(templateData);
33+
34+ return resolveHelperPromises(renderedString, helperPromises);
35+}
modified core/util/paths.ts +36 −0
@@ -1,6 +1,7 @@
11 import * as fs from "fs";
22 import * as os from "os";
33 import * as path from "path";
4+import * as URI from "uri-js";
45 import * as YAML from "yaml";
56
67 import { ConfigYaml, DevEventName } from "@continuedev/config-yaml";
@@ -466,3 +467,38 @@
466467 }
467468 return diffsPath;
468469 }
470+
471+export const isFileWithinFolder = (
472+ fileUri: string,
473+ folderPath: string,
474+): boolean => {
475+ try {
476+ if (!fileUri || !folderPath) {
477+ return false;
478+ }
479+
480+ const fileUriParsed = URI.parse(fileUri);
481+ const fileScheme = fileUriParsed.scheme || "file";
482+ let filePath = fileUriParsed.path || "";
483+ filePath = decodeURIComponent(filePath);
484+
485+ let folderWithScheme = folderPath;
486+ if (!folderPath.includes("://")) {
487+ folderWithScheme = `${fileScheme}://${folderPath.startsWith("/") ? "" : "/"}${folderPath}`;
488+ }
489+ const folderUriParsed = URI.parse(folderWithScheme);
490+
491+ let folderPathClean = folderUriParsed.path || "";
492+ folderPathClean = decodeURIComponent(folderPathClean);
493+
494+ filePath = filePath.replace(/\/$/, "");
495+ folderPathClean = folderPathClean.replace(/\/$/, "");
496+
497+ return (
498+ filePath === folderPathClean || filePath.startsWith(`${folderPathClean}/`)
499+ );
500+ } catch (error) {
501+ console.error("Error in isFileWithinFolder:", error);
502+ return false;
503+ }
504+};
modified core/util/posthog.ts +19 −0
@@ -4,6 +4,7 @@
44 import { IdeInfo } from "../index.js";
55
66 import type { PostHog as PostHogType } from "posthog-node";
7+import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
78
89 export enum PosthogFeatureFlag {
910 AutocompleteTimeout = "autocomplete-timeout",
@@ -37,6 +38,24 @@
3738 static os: string | undefined = undefined;
3839 static ideInfo: IdeInfo | undefined = undefined;
3940
41+ /**
42+ * Convenience method for capturing errors in a single event
43+ */
44+ static async captureError(errorName: string, error: unknown) {
45+ if (!(error instanceof Error)) {
46+ return;
47+ }
48+ await Telemetry.capture(
49+ "extension_error_caught",
50+ {
51+ errorName,
52+ message: error.message,
53+ stack: extractMinimalStackTraceInfo(error.stack),
54+ },
55+ false,
56+ );
57+ }
58+
4059 static async capture(
4160 event: string,
4261 properties: { [key: string]: any },
modified core/util/shellPath.ts +8 −10
@@ -1,11 +1,8 @@
1-import { execSync } from "child_process";
2-
3-/**
4- * Gets the PATH env var from the user's login shell on non-Windows platforms.
5- * Windows is not implemented primarily because it is not needed at the moment.
6- * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined
7- */
8-export function getEnvPathFromUserShell(): string | undefined {
1+import { exec } from "child_process";
2+import { promisify } from "util";
3+
4+const execAsync = promisify(exec);
5+export async function getEnvPathFromUserShell(): Promise<string | undefined> {
96 if (process.platform === "win32") {
107 console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
118 return undefined;
@@ -16,9 +13,10 @@
1613 }
1714
1815 try {
19- const command = `${process.env.SHELL} -l -c 'echo $PATH'`;
16+ // Source common profile files
17+ const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`;
2018
21- const stdout = execSync(command, {
19+ const { stdout } = await execAsync(command, {
2220 encoding: "utf8",
2321 });
2422

Next files