Elffuss BraidHub

kikocis/continue public

Resolve merge conflicts by keeping ours and discarding theirs (old syntax)
Changesetb3279474e667f9f759536e9e7ee8b70693312e2106f9b2bc74dc376bac5a8088
AuthorBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-07-10 13:58 -07:00
CommitterBrian 'bdougie' Douglas <brian@opensauced.pizza> · 2025-07-10 13:58 -07:00
Parents10a59ce026d2, bd1a49d2f4cb

Browse the files at this changeset

56 files changed

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 .vscode/launch.json +0 −1
@@ -19,7 +19,6 @@
1919 "pauseForSourceMap": false,
2020 "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
2121 "preLaunchTask": "vscode-extension:build",
22- "postDebugTask": "Terminate All Tasks",
2322 "env": {
2423 // "CONTROL_PLANE_ENV": "local",
2524 "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
modified .vscode/tasks.json +0 −13
@@ -223,19 +223,6 @@
223223 ],
224224 "type": "shell",
225225 "problemMatcher": []
226- },
227- {
228- "label": "Terminate All Tasks",
229- "command": "${input:terminate}",
230- "type": "shell"
231- }
232- ],
233- "inputs": [
234- {
235- "id": "terminate",
236- "type": "command",
237- "command": "workbench.action.tasks.terminate",
238- "args": "terminateAll"
239226 }
240227 ]
241228 }
modified binary/.gitignore +1 −0
@@ -3,3 +3,4 @@
33 data
44 out
55 tmp
6+tree-sitter
modified binary/build.js +20 −0
@@ -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);
@@ -142,6 +143,25 @@
142143 );
143144 });
144145
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+
145165 const filesToCopy = [
146166 "../core/vendor/tree-sitter.wasm",
147167 "../core/llm/llamaTokenizerWorkerPool.mjs",
modified binary/package-lock.json +2 −0
@@ -121,6 +121,8 @@
121121 "@babel/preset-env": "^7.24.7",
122122 "@biomejs/biome": "1.6.4",
123123 "@google/generative-ai": "^0.11.4",
124+ "@shikijs/colorized-brackets": "^3.7.0",
125+ "@shikijs/transformers": "^3.7.0",
124126 "@types/diff": "^7.0.1",
125127 "@types/follow-redirects": "^1.14.4",
126128 "@types/jest": "^29.5.12",
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",
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/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 }
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/indexing/docs/DocsService.ts +87 −11
@@ -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:
@@ -395,6 +406,21 @@
395406 siteIndexingConfig: SiteIndexingConfig,
396407 ): Promise<boolean> {
397408 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+
398424 const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
399425
400426 if (cacheHit) {
@@ -429,7 +455,8 @@
429455 siteIndexingConfig: SiteIndexingConfig,
430456 forceReindex: boolean = false,
431457 ): Promise<void> {
432- const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
458+ const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
459+ siteIndexingConfig;
433460
434461 // First, if indexing is already in process, don't attempt
435462 // This queue is necessary because indexAndAdd is invoked circularly by config edits
@@ -685,7 +712,9 @@
685712 await this.deleteIndexes(startUrl);
686713 }
687714
688- const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
715+ const favicon =
716+ faviconUrl ||
717+ (await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
689718
690719 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
691720 return;
@@ -718,10 +747,6 @@
718747 void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
719748 }
720749
721- this.messenger?.send("refreshSubmenuItems", {
722- providers: ["docs"],
723- });
724-
725750 removeFromFailedGlobalContext(siteIndexingConfig);
726751 } catch (e) {
727752 console.error(
@@ -766,14 +791,22 @@
766791 const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
767792
768793 // Try to get a favicon for the site
769- 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;
770803
771804 // Add the cached embeddings to our database
772805 await this.add({
773806 favicon,
774807 siteIndexingConfig: {
775808 startUrl,
776- title: siteEmbeddings.title || new URL(startUrl).hostname,
809+ title,
777810 },
778811 chunks: siteEmbeddings.chunks,
779812 embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
@@ -910,6 +943,10 @@
910943 );
911944
912945 if (cacheHit) {
946+ // If cache hit, refresh the submenu items for docs
947+ this.messenger?.send("refreshSubmenuItems", {
948+ providers: ["docs"],
949+ });
913950 // If cache hit, retry the search once
914951 return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
915952 }
@@ -987,8 +1024,7 @@
9871024 const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
9881025
9891026 // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
990- // TODO if only favicon and title change, only update, don't embed
991- // 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
9921028 const addedDocs: SiteIndexingConfig[] = [];
9931029 const changedDocs: SiteIndexingConfig[] = [];
9941030 for (const doc of newConfigDocs) {
@@ -999,12 +1035,26 @@
9991035 (d) => d.startUrl === doc.startUrl,
10001036 );
10011037
1038+ // TODO: Changes to the docs config made while Continue isn't running won't be caught
10021039 if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
1003- 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+ }
10041051 } else {
10051052 if (forceReindex) {
10061053 changedDocs.push(doc);
10071054 } 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);
10081058 // if get's here, not changed, no update needed, mark as complete
10091059 this.handleStatusUpdate({
10101060 type: "docs",
@@ -1036,6 +1086,10 @@
10361086 console.error("Error syncing docs index on config update", e);
10371087 } finally {
10381088 this.isSyncing = false;
1089+ // Refresh the submenu items for docs
1090+ this.messenger?.send("refreshSubmenuItems", {
1091+ providers: ["docs"],
1092+ });
10391093 }
10401094 }
10411095
@@ -1182,6 +1236,27 @@
11821236 );
11831237 }
11841238
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+
11851260 private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
11861261 // Handles the case where a user has manually added the doc to config.json
11871262 // so it already exists in the file
@@ -1286,5 +1361,6 @@
12861361 this.messenger?.send("refreshSubmenuItems", {
12871362 providers: ["docs"],
12881363 });
1364+ this.statuses.delete(startUrl);
12891365 }
12901366 }
modified core/llm/autodetect.ts +1 −0
@@ -46,6 +46,7 @@
4646 const PROVIDER_HANDLES_TEMPLATING: string[] = [
4747 "lmstudio",
4848 "openai",
49+ "nvidia",
4950 "ollama",
5051 "together",
5152 "novita",
modified core/llm/defaultSystemMessages.ts +1 −1
@@ -51,7 +51,7 @@
5151 You are in chat mode.
5252
5353 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 consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
54+ If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
5555
5656 ${CODEBLOCK_FORMATTING_INSTRUCTIONS}
5757 ${EDIT_CODE_INSTRUCTIONS}
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/rules/getSystemMessageWithRules.ts +4 −0
@@ -324,6 +324,10 @@
324324 return applicableRules;
325325 };
326326
327+export function getRuleId(rule: RuleWithSource): string {
328+ return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
329+}
330+
327331 export const getSystemMessageWithRules = ({
328332 baseSystemMessage,
329333 userMessage,
modified core/nextEdit/context/aggregateEdits.ts +7 −6
@@ -482,12 +482,13 @@
482482 return;
483483 }
484484
485- const diff = createDiff(
486- beforeContent,
487- afterContent,
488- filePath,
489- DiffFormatType.Unified,
490- ); // Used for checks, not for final output
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
491492
492493 // Skip diffs with too many changed lines
493494 const changedLineCount = this.countChangedLines(diff);
modified core/nextEdit/context/diffFormatting.ts +23 −8
@@ -12,15 +12,29 @@
1212 afterContent: string;
1313 };
1414
15-export const createDiff = (
16- beforeContent: string,
17- afterContent: string,
18- filePath: string,
19- diffType: DiffFormatType,
20-) => {
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) => {
2130 switch (diffType) {
2231 case DiffFormatType.Unified:
23- return createUnifiedDiff(beforeContent, afterContent, filePath);
32+ return createUnifiedDiff(
33+ beforeContent,
34+ afterContent,
35+ filePath,
36+ contextLines,
37+ );
2438 case DiffFormatType.TokenLineDiff:
2539 return createTokenLineDiff(beforeContent, afterContent, filePath);
2640 }
@@ -31,6 +45,7 @@
3145 beforeContent: string,
3246 afterContent: string,
3347 filePath: string,
48+ contextLines: number,
3449 ) => {
3550 const normalizedBefore = beforeContent.endsWith("\n")
3651 ? beforeContent
@@ -45,7 +60,7 @@
4560 normalizedAfter,
4661 "before",
4762 "after",
48- { context: 3 },
63+ { context: contextLines },
4964 );
5065
5166 return patch;
modified core/nextEdit/context/processNextEditData.ts +24 −23
@@ -2,7 +2,7 @@
22 import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
33 import { GetLspDefinitionsFunction } from "../../autocomplete/types";
44 import { ConfigHandler } from "../../config/ConfigHandler";
5-// import { DataLogger } from "../../data/log";
5+import { DataLogger } from "../../data/log";
66 import { RecentlyEditedRange } from "../types";
77 import { getAutocompleteContext } from "./autocompleteContextFetching";
88 import { createDiff, DiffFormatType } from "./diffFormatting";
@@ -108,31 +108,32 @@
108108 );
109109 }
110110
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- // }
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+ }
127127
128128 // add current edit to history
129129 const thisEdit: prevEdit = {
130- unidiff: createDiff(
131- beforeContent,
132- afterContent,
133- filePath,
134- DiffFormatType.Unified,
135- ),
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+ }),
136137 fileUri: filePath,
137138 workspaceUri: workspaceDir,
138139 timestamp: timestamp,
modified core/nextEdit/context/processSmallEdit.ts +7 −6
@@ -15,12 +15,13 @@
1515 ide: IDE,
1616 ) => {
1717 NextEditProvider.getInstance().addDiffToContext(
18- createDiff(
19- beforeAfterdiff.beforeContent,
20- beforeAfterdiff.afterContent,
21- beforeAfterdiff.filePath,
22- DiffFormatType.Unified,
23- ),
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+ }),
2425 );
2526
2627 // Get the current context data from the most recent message
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 docs/customize/model-providers/top-level/vertexai.mdx +30 −0
@@ -114,3 +114,33 @@
114114 Vertex AI currently does not offer any reranking models.
115115
116116 [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
117+
118+## Express mode
119+
120+You can use VertexAI in [express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) by only providing an API Key. Only some Gemini models are supported in express mode for now.
121+
122+<Tabs groupId="config-example">
123+ <TabItem value="yaml" label="YAML">
124+ ```yaml title="config.yaml"
125+ models:
126+ - name: Gemini 2.5 Flash - VertexAI
127+ provider: vertexai
128+ model: gemini-2.5-flash
129+ apiKey: ${{ secrets.GOOGLE_CLOUD_API_KEY }}
130+ ```
131+ </TabItem>
132+ <TabItem value="json" label="JSON">
133+ ```json title="config.json"
134+ {
135+ "models": [
136+ {
137+ "title": "Gemini 2.5 Flash - VertexAI",
138+ "provider": "vertexai",
139+ "model": "gemini-2.5-flash",
140+ "apiKey": "[YOUR_GOOGLE_CLOUD_API_KEY]",
141+ }
142+ ]
143+ }
144+ ```
145+ </TabItem>
146+</Tabs>
added docs/docs/features/autocomplete/context-selection.mdx +19 −0
@@ -0,0 +1,19 @@
1+# Context Selection
2+
3+Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt:
4+
5+## File prefix/suffix
6+
7+We will always include the code from your file prior to and after the cursor position.
8+
9+## Definitions from the Language Server Protocol
10+
11+Similar to how you can use cmd/ctrl + click in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type.
12+
13+## Imported files
14+
15+Because there are often many imports, we can't include all of them. Instead, we look for symbols around your cursor that have matching imports and use that as context.
16+
17+## Recent files
18+
19+We automatically consider recently opened or edited files and include snippets that are relevant to the current completion.
added docs/docs/features/autocomplete/how-to-customize.mdx +5 −0
@@ -0,0 +1,5 @@
1+# How to Customize Autocomplete
2+
3+Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
4+
5+For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
added docs/docs/features/autocomplete/model-setup.mdx +29 −0
@@ -0,0 +1,29 @@
1+# Autocomplete Model Setup
2+
3+Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
4+
5+## Recommended Models
6+
7+### Hosted-Based (Best Performance)
8+
9+For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
10+
11+**Quick Setup:**
12+
13+1. [Add Codestral from the hub](https://hub.continue.dev/mistral/codestral)
14+2. Get your API key from the [Mistral Platform](https://console.mistral.ai/codestral)
15+3. Configure it in your Continue settings
16+
17+### Local/Offline (Privacy First)
18+
19+For a fully local autocomplete experience that doesn't send your code to external servers, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)** running on Ollama. This model provides good suggestions while keeping your code completely private.
20+
21+**Quick Setup:**
22+
23+1. Install [Ollama](https://ollama.ai/)
24+2. [Add Qwen 2.5 Coder from the hub](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)
25+3. Configure it in your Continue settings
26+
27+## Need Help?
28+
29+If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete).
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +9 −11
@@ -185,18 +185,17 @@
185185 return
186186 }
187187
188- ApplicationManager.getApplication().invokeLater {
189- WriteAction.run<Throwable> {
190- // Clear existing completions
191- hideCompletions(editor)
188+ invokeLater {
189+ // Clear existing completions
190+ hideCompletions(editor)
192191
193- val properties = InlayProperties()
194- properties.relatesToPrecedingText(true)
195- properties.disableSoftWrapping(true)
192+ val properties = InlayProperties()
193+ properties.relatesToPrecedingText(true)
194+ properties.disableSoftWrapping(true)
196195
197- val lines = completion.lines()
198- pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
199- editor.addInlayElement(lines, offset, properties)
196+ val lines = completion.lines()
197+ pendingCompletion = pendingCompletion?.copy(text = lines.joinToString("\n"))
198+ editor.addInlayElement(lines, offset, properties)
200199
201200 // val attributes = TextAttributes().apply {
202201 // backgroundColor = JBColor.GREEN
@@ -204,7 +203,6 @@
204203 // val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
205204 // key.let { editor.colorsScheme.setAttributes(it, attributes) }
206205 // editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
207- }
208206 }
209207 }
210208
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +3 −2
@@ -495,7 +495,7 @@
495495
496496 // Create the list of IndexTag objects
497497 return workspaceDirs.mapIndexed { index, directory ->
498- IndexTag(directory, branches[index], artifactId)
498+ IndexTag(artifactId, branches[index], directory)
499499 }
500500 }
501501
@@ -622,4 +622,5 @@
622622 return listOfNotNull(project.guessProjectDir()?.toUriOrNull()).toTypedArray()
623623 }
624624
625-}
No newline at the end of the file
625+}
626+
modified extensions/vscode/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 extensions/vscode/package.json +1 −1
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.59",
5+ "version": "1.1.60",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
modified extensions/vscode/src/util/editLoggingUtils.ts +28 −15
@@ -3,6 +3,9 @@
33 import { GetLspDefinitionsFunction } from "core/autocomplete/types";
44 import { ConfigHandler } from "core/config/ConfigHandler";
55 import { RecentlyEditedRange } from "core/nextEdit/types";
6+import { getContinueGlobalPath, isFileWithinFolder } from "core/util/paths";
7+import fs from "fs";
8+import { resolve } from "path";
69 import * as vscode from "vscode";
710 import { ContinueCompletionProvider } from "../autocomplete/completionProvider";
811
@@ -18,23 +21,33 @@
1821 }
1922 };
2023
21-const getWorkspaceDirInfo = async (
22- event: vscode.TextDocumentChangeEvent,
23- ide: IDE,
24-) => {
25- // gets the workspace dir uri and checks if it's the open-source continue repo
24+const isEditLoggingAllowed = async (editedFileURI: string) => {
25+ const globalContinuePath = getContinueGlobalPath();
26+ const editLogDirsPath = resolve(globalContinuePath, ".editlogdirs");
27+
28+ try {
29+ const fileContent = await fs.promises.readFile(editLogDirsPath, "utf-8");
30+ const stringItems = fileContent
31+ .split("\n")
32+ .map((line) => line.trim())
33+ .filter((line) => line.length > 0);
34+
35+ return stringItems.some((dir) => isFileWithinFolder(editedFileURI, dir));
36+ } catch (error) {
37+ return false;
38+ }
39+};
40+
41+const getWorkspaceDirUri = async (event: vscode.TextDocumentChangeEvent) => {
2642 const workspaceFolder = vscode.workspace.getWorkspaceFolder(
2743 event.document.uri,
2844 );
2945 if (!workspaceFolder) {
3046 return false;
3147 }
48+
3249 const workspaceDirUri = workspaceFolder.uri.toString();
33- const repoName = await ide.getRepoName(workspaceDirUri);
34- return {
35- workspaceDirUri: workspaceDirUri,
36- isContinueRepo: repoName === "continuedev/continue",
37- };
50+ return workspaceDirUri;
3851 };
3952
4053 export const handleTextDocumentChange = async (
@@ -52,10 +65,10 @@
5265 if (!editor) return;
5366 if (event.contentChanges.length === 0) return;
5467
55- // Ensure that loggin will only happen in the open-source continue repo
56- const workspaceDirInfo = await getWorkspaceDirInfo(event, ide);
57- if (!workspaceDirInfo) return;
58- // if (!workspaceDirInfo.isContinueRepo) return;
68+ // Ensure that logging will only happen in the open-source continue repo
69+ const workspaceDirUri = await getWorkspaceDirUri(event);
70+ if (!workspaceDirUri) return;
71+ if (!(await isEditLoggingAllowed(event.document.uri.toString()))) return;
5972
6073 const activeCursorPos = editor.selection.active;
6174 const editActions: RangeInFileWithNextEditInfo[] = changes.map((change) => ({
@@ -68,7 +81,7 @@
6881 editText: change.text,
6982 beforeCursorPos: getBeforeCursorPos(change.range, activeCursorPos),
7083 afterCursorPos: activeCursorPos as Position,
71- workspaceDir: workspaceDirInfo.workspaceDirUri,
84+ workspaceDir: workspaceDirUri,
7285 }));
7386
7487 let recentlyEditedRanges: RecentlyEditedRange[] = [];
modified gui/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 gui/public/logos/sambanova.png +0 −0

Binary content is not shown. View the file.

deleted gui/src/components/dialogs/FeedbackDialog.tsx +0 −64
@@ -1,64 +0,0 @@
1-import { usePostHog } from "posthog-js/react";
2-import { setDialogMessage } from "../../redux/slices/uiSlice";
3-import { useAppDispatch } from "../../redux/hooks";
4-
5-export default function FeedbackDialog() {
6- const posthog = usePostHog();
7- const dispatch = useAppDispatch();
8-
9- return (
10- <div className="p-4 text-center">
11- 👋 Thanks for using Continue. We are always trying to improve and love
12- hearing from users. If you're interested in speaking, enter your name and
13- email. We won't use this information for anything other than reaching out.
14- <br />
15- <br />
16- <form
17- onSubmit={(e: any) => {
18- e.preventDefault();
19- posthog?.capture("user_interest_form", {
20- name: e.target.elements[0].value,
21- email: e.target.elements[1].value,
22- });
23- dispatch(
24- setDialogMessage(
25- <div className="p-4 text-center">
26- Thanks! We'll be in touch soon.
27- </div>,
28- ),
29- );
30- }}
31- style={{
32- display: "flex",
33- flexDirection: "column",
34- gap: "10px",
35- }}
36- >
37- <input
38- style={{ padding: "10px", borderRadius: "5px" }}
39- type="text"
40- name="name"
41- placeholder="Name"
42- required
43- />
44- <input
45- style={{ padding: "10px", borderRadius: "5px" }}
46- type="email"
47- name="email"
48- placeholder="Email"
49- required
50- />
51- <button
52- style={{
53- padding: "10px",
54- borderRadius: "5px",
55- cursor: "pointer",
56- }}
57- type="submit"
58- >
59- Submit
60- </button>
61- </form>
62- </div>
63- );
64-}
modified gui/src/context/SubmenuContextProviders.tsx +241 −3
@@ -29,6 +29,14 @@
2929
3030 const MAX_LENGTH = 70;
3131
32+// Enhanced search result interface for intelligent sorting
33+interface EnhancedSearchResult
34+ extends SearchResult,
35+ Omit<ContextSubmenuItemWithProvider, "id"> {
36+ sortPriority: number;
37+ matchQuality: number;
38+}
39+
3240 interface SubtextContextProvidersContextType {
3341 getSubmenuContextItems: (
3442 providerTitle: string | undefined,
@@ -43,6 +51,91 @@
4351 const SubmenuContextProvidersContext =
4452 createContext<SubtextContextProvidersContextType>(initialContextProviders);
4553
54+// Helper functions for intelligent file sorting
55+function hasExactWordMatch(text: string, query: string): boolean {
56+ const words = text.split(/[^a-zA-Z0-9]+/);
57+ return words.some((word) => word === query);
58+}
59+
60+function isCommonDevFile(fileName: string): boolean {
61+ const commonExtensions = [
62+ ".ts",
63+ ".tsx",
64+ ".js",
65+ ".jsx",
66+ ".py",
67+ ".java",
68+ ".cpp",
69+ ".c",
70+ ".h",
71+ ".vue",
72+ ".svelte",
73+ ];
74+ const commonNames = [
75+ "index",
76+ "main",
77+ "app",
78+ "component",
79+ "service",
80+ "util",
81+ "helper",
82+ "config",
83+ "types",
84+ ];
85+
86+ const extension = fileName.substring(fileName.lastIndexOf("."));
87+ const baseName = fileName
88+ .substring(0, fileName.lastIndexOf("."))
89+ .toLowerCase();
90+
91+ return commonExtensions.includes(extension) || commonNames.includes(baseName);
92+}
93+
94+function isInCommonDirectory(filePath: string): boolean {
95+ const commonDirs = [
96+ "src/",
97+ "lib/",
98+ "components/",
99+ "utils/",
100+ "helpers/",
101+ "services/",
102+ "pages/",
103+ "views/",
104+ "hooks/",
105+ "store/",
106+ "types/",
107+ "interfaces/",
108+ "models/",
109+ "api/",
110+ ];
111+ return commonDirs.some((dir) => filePath.includes(dir));
112+}
113+
114+function matchesCamelCaseOrAbbreviation(
115+ fileName: string,
116+ query: string,
117+): boolean {
118+ // Extract capital letters for camel case matching
119+ const capitals = fileName.match(/[A-Z]/g)?.join("").toLowerCase() || "";
120+
121+ // Check if query matches the capital letters pattern
122+ if (capitals.length > 0 && capitals.includes(query)) {
123+ return true;
124+ }
125+
126+ // Check for abbreviation matches (first letters of words)
127+ const words = fileName.split(/[^a-zA-Z0-9]+/).filter((w) => w.length > 0);
128+ if (words.length > 1) {
129+ const abbreviation = words
130+ .map((word) => word[0])
131+ .join("")
132+ .toLowerCase();
133+ return abbreviation.includes(query);
134+ }
135+
136+ return false;
137+}
138+
46139 export const SubmenuContextProvidersProvider = ({
47140 children,
48141 }: {
@@ -128,6 +221,98 @@
128221 new Map<ContextProviderName, AbortController>(),
129222 ).current;
130223
224+ const calculateFileSortPriority = useCallback(
225+ (
226+ result: SearchResult & ContextSubmenuItemWithProvider,
227+ query: string,
228+ openFiles: ContextSubmenuItemWithProvider[],
229+ ): number => {
230+ const fileName = result.title.toLowerCase();
231+ const filePath = result.description.toLowerCase();
232+ const queryLower = query.toLowerCase();
233+
234+ // Priority 1: Exact filename match
235+ if (fileName === queryLower) {
236+ return 1;
237+ }
238+
239+ // Priority 2: Recently opened files
240+ if (openFiles.some((f) => f.id === result.id)) {
241+ return 2;
242+ }
243+
244+ // Priority 3: Filename starts with query
245+ if (fileName.startsWith(queryLower)) {
246+ return 3;
247+ }
248+
249+ // Priority 4: Exact word match in filename
250+ if (hasExactWordMatch(fileName, queryLower)) {
251+ return 4;
252+ }
253+
254+ // Priority 5: Common development files
255+ if (isCommonDevFile(fileName)) {
256+ return 5;
257+ }
258+
259+ // Priority 6: Files in common directories
260+ if (isInCommonDirectory(filePath)) {
261+ return 6;
262+ }
263+
264+ // Priority 7: CamelCase/abbreviation matches
265+ if (matchesCamelCaseOrAbbreviation(fileName, queryLower)) {
266+ return 7;
267+ }
268+
269+ // Priority 8: Path starts with query
270+ if (filePath.startsWith(queryLower)) {
271+ return 8;
272+ }
273+
274+ // Priority 9: Default
275+ return 9;
276+ },
277+ [],
278+ );
279+
280+ const calculateMatchQuality = useCallback(
281+ (
282+ result: SearchResult & ContextSubmenuItemWithProvider,
283+ query: string,
284+ ): number => {
285+ const fileName = result.title.toLowerCase();
286+ const queryLower = query.toLowerCase();
287+ let quality = 0;
288+
289+ // Exact match bonus
290+ if (fileName === queryLower) quality += 100;
291+
292+ // Prefix match bonus
293+ if (fileName.startsWith(queryLower)) quality += 50;
294+
295+ // Contains match bonus
296+ if (fileName.includes(queryLower)) quality += 25;
297+
298+ // Shorter filename bonus (prefer concise names)
299+ quality += Math.max(0, 50 - fileName.length);
300+
301+ // Extension preference (common dev files)
302+ if (
303+ fileName.endsWith(".ts") ||
304+ fileName.endsWith(".tsx") ||
305+ fileName.endsWith(".js") ||
306+ fileName.endsWith(".jsx")
307+ ) {
308+ quality += 10;
309+ }
310+
311+ return quality;
312+ },
313+ [],
314+ );
315+
131316 const getSubmenuContextItems = useCallback(
132317 (
133318 providerTitle: string | undefined,
@@ -168,9 +353,57 @@
168353 });
169354 }
170355 }
171- searchResults.sort((a, b) => b.score - a.score);
172356
173- // 2. Add fallback results if no search results
357+ // 2. Enhanced sorting for file provider
358+ if (
359+ providerTitle === "file" ||
360+ (!providerTitle &&
361+ searchResults.some((r) => r.providerTitle === "file"))
362+ ) {
363+ const enhancedResults: EnhancedSearchResult[] = searchResults.map(
364+ (result): EnhancedSearchResult => ({
365+ ...result,
366+ id: result.id,
367+ title: result.title,
368+ description: result.description,
369+ providerTitle: result.providerTitle,
370+ sortPriority: calculateFileSortPriority(
371+ result,
372+ query,
373+ lastOpenFilesRef.current,
374+ ),
375+ matchQuality: calculateMatchQuality(result, query),
376+ }),
377+ );
378+
379+ // Sort by multiple criteria
380+ enhancedResults.sort((a, b) => {
381+ // Primary: Sort priority (lower = better)
382+ if (a.sortPriority !== b.sortPriority) {
383+ return a.sortPriority - b.sortPriority;
384+ }
385+
386+ // Secondary: Match quality (higher = better)
387+ if (a.matchQuality !== b.matchQuality) {
388+ return b.matchQuality - a.matchQuality;
389+ }
390+
391+ // Tertiary: MiniSearch relevance score (higher = better)
392+ if (a.score !== b.score) {
393+ return b.score - a.score;
394+ }
395+
396+ // Quaternary: Path length (shorter = better)
397+ return a.description.length - b.description.length;
398+ });
399+
400+ searchResults = enhancedResults;
401+ } else {
402+ // Default sorting for non-file providers
403+ searchResults.sort((a, b) => b.score - a.score);
404+ }
405+
406+ // 3. Add fallback results if no search results
174407 if (searchResults.length === 0) {
175408 const fallbackItems = (
176409 providerTitle ? (fallbackResults[providerTitle] ?? []) : []
@@ -223,7 +456,12 @@
223456 return [];
224457 }
225458 },
226- [fallbackResults, minisearches],
459+ [
460+ fallbackResults,
461+ minisearches,
462+ calculateFileSortPriority,
463+ calculateMatchQuality,
464+ ],
227465 );
228466
229467 const loadSubmenuItems = useCallback(
modified gui/src/pages/gui/Chat.tsx +0 −20
@@ -16,7 +16,6 @@
1616 import { ErrorBoundary } from "react-error-boundary";
1717 import styled from "styled-components";
1818 import { Button, lightGray, vscBackground } from "../../components";
19-import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
2019 import { useFindWidget } from "../../components/find/FindWidget";
2120 import TimelineItem from "../../components/gui/TimelineItem";
2221 import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
@@ -37,18 +36,12 @@
3736 newSession,
3837 updateToolCallOutput,
3938 } from "../../redux/slices/sessionSlice";
40-import {
41- setDialogEntryOn,
42- setDialogMessage,
43- setShowDialog,
44-} from "../../redux/slices/uiSlice";
4539 import { streamEditThunk } from "../../redux/thunks/edit";
4640 import { loadLastSession } from "../../redux/thunks/session";
4741 import { streamResponseThunk } from "../../redux/thunks/streamResponse";
4842 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
4943
5044 import { cancelStream } from "../../redux/thunks/cancelStream";
51-import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
5245 import { EmptyChatBody } from "./EmptyChatBody";
5346 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
5447 import { ToolCallDiv } from "./ToolCallDiv";
@@ -221,19 +214,6 @@
221214 editorToClearOnSend.commands.clearContent();
222215 }
223216 }
224-
225- // Increment localstorage counter for popup
226- const currentCount = getLocalStorage("mainTextEntryCounter");
227- if (currentCount) {
228- setLocalStorage("mainTextEntryCounter", currentCount + 1);
229- if (currentCount === 300) {
230- dispatch(setDialogMessage(<FeedbackDialog />));
231- dispatch(setDialogEntryOn(false));
232- dispatch(setShowDialog(true));
233- }
234- } else {
235- setLocalStorage("mainTextEntryCounter", 1);
236- }
237217 },
238218 [
239219 history,
modified gui/src/redux/slices/uiSlice.ts +0 −11
@@ -83,12 +83,6 @@
8383 ) => {
8484 state.dialogMessage = action.payload;
8585 },
86- setDialogEntryOn: (
87- state,
88- action: PayloadAction<UIState["dialogEntryOn"]>,
89- ) => {
90- state.dialogEntryOn = action.payload;
91- },
9286 setShowDialog: (state, action: PayloadAction<UIState["showDialog"]>) => {
9387 state.showDialog = action.payload;
9488 },
@@ -98,9 +92,6 @@
9892 ) => {
9993 state.isExploreDialogOpen = action.payload;
10094 },
101- setHasDismissedExploreDialog: (state, action: PayloadAction<boolean>) => {
102- state.hasDismissedExploreDialog = action.payload;
103- },
10495 // Tools
10596 addTool: (state, action: PayloadAction<Tool>) => {
10697 state.toolSettings[action.payload.function.name] =
@@ -173,10 +164,8 @@
173164 export const {
174165 setOnboardingCard,
175166 setDialogMessage,
176- setDialogEntryOn,
177167 setShowDialog,
178168 setIsExploreDialogOpen,
179- setHasDismissedExploreDialog,
180169 toggleToolSetting,
181170 setToolPolicy,
182171 clearToolPolicy,
modified gui/src/redux/thunks/streamNormalInput.ts +5 −0
@@ -1,6 +1,7 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
22 import { LLMFullCompletionOptions, ModelDescription, Tool } from "core";
33 import { modelSupportsTools } from "core/llm/autodetect";
4+import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
45 import { ToCoreProtocol } from "core/protocol";
56 import { BuiltInToolNames } from "core/tools/builtIn";
67 import { selectActiveTools } from "../selectors/selectActiveTools";
@@ -171,6 +172,10 @@
171172 ...(!!activeTools.length && {
172173 tools: activeTools.map((tool) => tool.function.name),
173174 }),
175+ rules: appliedRules.map((rule) => ({
176+ id: getRuleId(rule),
177+ rule: rule.rule,
178+ })),
174179 },
175180 });
176181 // else if (state.session.mode === "edit") {
modified gui/src/util/localStorage.ts +0 −1
@@ -6,7 +6,6 @@
66 hasDismissedExploreDialog: boolean;
77 onboardingStatus?: OnboardingStatus;
88 hasDismissedOnboardingCard: boolean;
9- mainTextEntryCounter: number;
109 ide: "vscode" | "jetbrains";
1110 vsCodeUriScheme: string;
1211 ftc: number;
modified gui/src/util/toolCallState.test.ts +100 −0
@@ -479,4 +479,104 @@
479479 );
480480 expect(currentState.parsedArgs).toEqual({ location: "Paris, France" });
481481 });
482+
483+ it("should handle arguments streamed in full progressive chunks", () => {
484+ // Test case where model streams args progressively but includes full prefix each time
485+ // e.g. '{"query":"te' -> '{"query":"tes' -> '{"query":"test"}'
486+ const currentState: ToolCallState = {
487+ status: "generating",
488+ toolCall: {
489+ id: "call123",
490+ type: "function",
491+ function: {
492+ name: "searchFiles",
493+ arguments: '{"query":"te',
494+ },
495+ },
496+ toolCallId: "call123",
497+ parsedArgs: { query: "te" },
498+ };
499+
500+ const delta: ToolCallDelta = {
501+ function: {
502+ arguments: '{"query":"tes',
503+ },
504+ };
505+
506+ const result = addToolCallDeltaToState(delta, currentState);
507+ expect(result.toolCall.function.arguments).toBe('{"query":"tes');
508+ expect(result.parsedArgs).toEqual({ query: "tes" });
509+
510+ // Continue the streaming
511+ const nextDelta: ToolCallDelta = {
512+ function: {
513+ arguments: '{"query":"test"}',
514+ },
515+ };
516+
517+ const finalResult = addToolCallDeltaToState(nextDelta, result);
518+ expect(finalResult.toolCall.function.arguments).toBe('{"query":"test"}');
519+ expect(finalResult.parsedArgs).toEqual({ query: "test" });
520+ });
521+
522+ it("should handle when args delta is a superset of current args", () => {
523+ // Test case where model sends a subset of the current arguments
524+ // This can happen in certain LLM implementations
525+ const currentState: ToolCallState = {
526+ status: "generating",
527+ toolCall: {
528+ id: "call123",
529+ type: "function",
530+ function: {
531+ name: "searchFiles",
532+ arguments: '{"query":"test"',
533+ },
534+ },
535+ toolCallId: "call123",
536+ parsedArgs: { query: "test" },
537+ };
538+
539+ const delta: ToolCallDelta = {
540+ function: {
541+ arguments: '{"query":"test","limit":10}',
542+ },
543+ };
544+
545+ // The subset should be ignored, keeping the current state
546+ const result = addToolCallDeltaToState(delta, currentState);
547+ expect(result.toolCall.function.arguments).toBe(
548+ '{"query":"test","limit":10}',
549+ );
550+ expect(result.parsedArgs).toEqual({ query: "test", limit: 10 });
551+ });
552+
553+ it("should handle when args are complete JSON and new deltas arrive", () => {
554+ // When args are already a valid JSON object, new deltas should not modify it
555+ const currentState: ToolCallState = {
556+ status: "generating",
557+ toolCall: {
558+ id: "call123",
559+ type: "function",
560+ function: {
561+ name: "searchFiles",
562+ arguments: '{"query":"test","limit":10}',
563+ },
564+ },
565+ toolCallId: "call123",
566+ parsedArgs: { query: "test", limit: 10 },
567+ };
568+
569+ const delta: ToolCallDelta = {
570+ function: {
571+ arguments: ',"sort":"asc"}',
572+ },
573+ };
574+
575+ // The complete JSON should not be modified
576+ const result = addToolCallDeltaToState(delta, currentState);
577+ expect(result.toolCall.function.arguments).toBe(
578+ '{"query":"test","limit":10}',
579+ );
580+ expect(result.parsedArgs).toEqual({ query: "test", limit: 10 });
581+ });
482582 });
modified gui/src/util/toolCallState.ts +15 −6
@@ -34,15 +34,24 @@
3434 if (nameDelta.startsWith(currentName)) {
3535 // Case where model progresssively streams name but full name each time e.g. "readFi" -> "readFil" -> "readFile"
3636 mergedName = nameDelta;
37- } else if (currentName.startsWith(nameDelta)) {
38- // Case where model streams in full name each time e.g. readFile -> readFile -> readFile
39- // do nothing
40- } else {
41- // Case where model streams in name in parts e.g. "read" -> "File"
37+ } else if (!currentName.startsWith(nameDelta)) {
4238 mergedName = currentName + nameDelta;
4339 }
4440
45- const mergedArgs = currentArgs + argsDelta;
41+ // Similar logic for args, with an extra JSON check
42+ let mergedArgs = currentArgs;
43+ try {
44+ // If args is JSON parseable, it is complete, don't add to it
45+ JSON.parse(currentArgs);
46+ } catch (e) {
47+ if (argsDelta.startsWith(currentArgs)) {
48+ // Case where model progresssively streams args but full args each time e.g. "{"file": "file1"}" -> "{"file": "file1", "line": 1}"
49+ mergedArgs = argsDelta;
50+ } else if (!currentArgs.startsWith(argsDelta)) {
51+ // Case where model streams in args in parts e.g. "{"file": "file1"" -> ", "line": 1}"
52+ mergedArgs = currentArgs + argsDelta;
53+ }
54+ }
4655
4756 const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}");
4857
modified packages/config-yaml/src/markdown/createMarkdownRule.test.ts +8 −6
@@ -9,7 +9,7 @@
99 // Mock package identifier for testing
1010 const mockPackageId: PackageIdentifier = {
1111 uriType: "file",
12- filePath: "/path/to/file",
12+ filePath: "/path/to/folder",
1313 };
1414
1515 describe("sanitizeRuleName", () => {
@@ -85,7 +85,9 @@
8585
8686 expect(parsed.name).toBe(originalFrontmatter.name);
8787 expect(parsed.description).toBe(originalFrontmatter.description);
88- expect(parsed.globs).toEqual(originalFrontmatter.globs);
88+ expect(parsed.globs).toEqual(
89+ originalFrontmatter.globs.map((glob) => `/path/to/**/${glob}`),
90+ );
8991 expect(parsed.alwaysApply).toBe(originalFrontmatter.alwaysApply);
9092 expect(parsed.rule).toBe(originalMarkdown);
9193 });
@@ -102,7 +104,7 @@
102104 const parsed = markdownToRule(result, mockPackageId);
103105
104106 expect(parsed.description).toBe("Test description");
105- expect(parsed.globs).toEqual(["*.ts", "*.js"]);
107+ expect(parsed.globs).toEqual(["/path/to/**/*.ts", "/path/to/**/*.js"]);
106108 expect(parsed.alwaysApply).toBe(true);
107109 expect(parsed.rule).toBe("This is the rule content");
108110 });
@@ -113,7 +115,7 @@
113115 const parsed = markdownToRule(result, mockPackageId);
114116
115117 expect(parsed.description).toBeUndefined();
116- expect(parsed.globs).toBeUndefined();
118+ expect(parsed.globs).toBe("/path/to/**/*");
117119 expect(parsed.alwaysApply).toBeUndefined();
118120 expect(parsed.rule).toBe("Simple content");
119121 });
@@ -124,7 +126,7 @@
124126 });
125127
126128 const parsed = markdownToRule(result, mockPackageId);
127- expect(parsed.globs).toBe("*.py");
129+ expect(parsed.globs).toBe("/path/to/**/*.py");
128130 });
129131
130132 it("should trim description and globs", () => {
@@ -135,7 +137,7 @@
135137
136138 const parsed = markdownToRule(result, mockPackageId);
137139 expect(parsed.description).toBe("spaced description");
138- expect(parsed.globs).toBe("*.ts");
140+ expect(parsed.globs).toBe("/path/to/**/*.ts");
139141 });
140142
141143 it("should handle alwaysApply false explicitly", () => {
modified packages/config-yaml/src/markdown/markdownToRule.test.ts +98 −7
@@ -20,7 +20,7 @@
2020
2121 const result = markdownToRule(content, mockId);
2222 expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
23- expect(result.globs).toBe("**/test/**/*.kt");
23+ expect(result.globs).toBe("/path/to/**/test/**/*.kt");
2424 expect(result.name).toBe("Custom Name");
2525 });
2626
@@ -34,7 +34,7 @@
3434 This is a test rule.`;
3535
3636 const result = markdownToRule(content, mockId);
37- expect(result.globs).toBe("**/test/**/*.kt");
37+ expect(result.globs).toBe("/path/to/**/test/**/*.kt");
3838 expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
3939 expect(result.name).toBe("to/file"); // Should use last two path segments
4040 });
@@ -45,7 +45,7 @@
4545 This is a test rule without frontmatter.`;
4646
4747 const result = markdownToRule(content, mockId);
48- expect(result.globs).toBeUndefined();
48+ expect(result.globs).toBe("/path/to/**/*");
4949 expect(result.rule).toBe(content);
5050 expect(result.name).toBe("to/file"); // Should use last two path segments
5151 });
@@ -59,13 +59,104 @@
5959 This is a test rule with empty frontmatter.`;
6060
6161 const result = markdownToRule(content, mockId);
62- expect(result.globs).toBeUndefined();
62+ expect(result.globs).toBe("/path/to/**/*");
6363 expect(result.rule).toBe(
6464 "# Test Rule\n\nThis is a test rule with empty frontmatter.",
6565 );
6666 expect(result.name).toBe("to/file"); // Should use last two path segments
6767 });
6868
69+ describe("glob patterns", () => {
70+ // we want to ensure the following glob changes happen
71+ // *.ts -> path/to/**/*.ts
72+ // **/subdir/** -> path/to/**/**/subdir/** OR path/to/**/subdir/**
73+ // myfile -> path/to/**/myfile (any depth including 0)
74+ // mydir/ -> path/to/**/mydir/**
75+ // **abc** -> path/to/**abc**
76+ // *xyz* -> path/to/**/*xyz*
77+
78+ it("should match glob pattern for file extensions", () => {
79+ const content = `---
80+globs: "*.ts"
81+name: glob pattern testing
82+---
83+
84+ # Test Rule
85+
86+ This is a test rule.`;
87+
88+ const result = markdownToRule(content, mockId);
89+ expect(result.globs).toBe("/path/to/**/*.ts");
90+ });
91+
92+ it("should match glob pattern for dotfiles", () => {
93+ const content = `---
94+globs: ".gitignore"
95+name: glob pattern testing
96+---
97+
98+ # Test Rule
99+
100+ This is a test rule.`;
101+
102+ const result = markdownToRule(content, mockId);
103+ expect(result.globs).toBe("/path/to/**/.gitignore");
104+ });
105+
106+ it("should also work in root as base directory", () => {
107+ const content = `---
108+globs: "src/**/Dockerfile"
109+name: glob pattern testing
110+---
111+
112+ # Test Rule
113+
114+ This is a test rule.`;
115+
116+ const result = markdownToRule(content, {
117+ uriType: "file",
118+ filePath: "/",
119+ });
120+ expect(result.globs).toBe("/**/src/**/Dockerfile");
121+ });
122+
123+ it("should match for multiple globs", () => {
124+ const content = `---
125+globs: ["**/nested/**/deeper/**/*.rs", ".zshrc1", "**abc**", "*xyz*"]
126+name: glob pattern testing
127+---
128+
129+# Test Rule
130+
131+This is a test rule.`;
132+
133+ const result = markdownToRule(content, mockId);
134+ expect(result.globs).toEqual([
135+ "/path/to/**/nested/**/deeper/**/*.rs",
136+ "/path/to/**/.zshrc1",
137+ "/path/to/**abc**",
138+ "/path/to/**/*xyz*",
139+ ]);
140+ });
141+
142+ it("should not prepend when inside .continue", () => {
143+ const content = `---
144+globs: ".git"
145+name: glob pattern testing
146+---
147+
148+ # Test Rule
149+
150+ This is a test rule.`;
151+
152+ const result = markdownToRule(content, {
153+ uriType: "file",
154+ filePath: "/Documents/myproject/.continue/rules/rule1.md",
155+ });
156+ expect(result.globs).toBe(".git");
157+ });
158+ });
159+
69160 it("should handle frontmatter with whitespace", () => {
70161 const content = `---
71162 globs: "**/test/**/*.kt"
@@ -76,7 +167,7 @@
76167 This is a test rule.`;
77168
78169 const result = markdownToRule(content, mockId);
79- expect(result.globs).toBe("**/test/**/*.kt");
170+ expect(result.globs).toBe("/path/to/**/test/**/*.kt");
80171 expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
81172 expect(result.name).toBe("to/file"); // Should use last two path segments
82173 });
@@ -92,7 +183,7 @@
92183 This is a test rule.`;
93184
94185 const result = markdownToRule(content, mockId);
95- expect(result.globs).toBe("**/test/**/*.kt");
186+ expect(result.globs).toBe("/path/to/**/test/**/*.kt");
96187 // The result should be normalized to \n
97188 expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
98189 expect(result.name).toBe("to/file"); // Should use last two path segments
@@ -110,7 +201,7 @@
110201
111202 // Should treat as only markdown when frontmatter is malformed
112203 const result = markdownToRule(content, mockId);
113- expect(result.globs).toBeUndefined();
204+ expect(result.globs).toBe("/path/to/**/*");
114205 expect(result.rule).toBe(content);
115206 expect(result.name).toBe("to/file"); // Should use last two path segments
116207 });
modified packages/config-yaml/src/markdown/markdownToRule.ts +31 −1
@@ -1,3 +1,4 @@
1+import path from "path";
12 import * as YAML from "yaml";
23 import {
34 PackageIdentifier,
@@ -69,6 +70,35 @@
6970 return displayName;
7071 }
7172
73+function getGlobPattern(
74+ globs: RuleFrontmatter["globs"],
75+ id: PackageIdentifier,
76+) {
77+ if (id.uriType !== "file") {
78+ return globs;
79+ }
80+ let dir = path.dirname(id.filePath);
81+ if (dir.includes(".continue")) {
82+ return globs;
83+ }
84+ if (!dir.endsWith("/")) {
85+ dir = dir.concat("/");
86+ }
87+ const prependDirAndApplyGlobstar = (glob: string) => {
88+ if (glob.startsWith("**")) {
89+ return dir.concat(glob);
90+ }
91+ return dir.concat("**/", glob);
92+ };
93+ if (!globs) {
94+ return dir.concat("**/*");
95+ }
96+ if (Array.isArray(globs)) {
97+ return globs.map(prependDirAndApplyGlobstar);
98+ }
99+ return prependDirAndApplyGlobstar(globs);
100+}
101+
72102 export function markdownToRule(
73103 rule: string,
74104 id: PackageIdentifier,
@@ -78,7 +108,7 @@
78108 return {
79109 name: getRuleName(frontmatter, id),
80110 rule: markdown,
81- globs: frontmatter.globs,
111+ globs: getGlobPattern(frontmatter.globs, id),
82112 regex: frontmatter.regex,
83113 description: frontmatter.description,
84114 alwaysApply: frontmatter.alwaysApply,
modified packages/config-yaml/src/schemas/data/autocomplete/index.ts +1 −1
@@ -34,7 +34,7 @@
3434 gitRepo: z.string().optional(),
3535 completionId: z.string(),
3636 uniqueId: z.string(),
37- timestamp: z.number(),
37+ timestamp: z.string(),
3838
3939 // DEPRECATED - no more nested objects after v0.1.0, all flat values
4040 completionOptions: completionOptionsSchema.optional(),
modified packages/config-yaml/src/schemas/data/chatInteraction/index.ts +8 −0
@@ -8,4 +8,12 @@
88 completion: z.string(),
99 sessionId: z.string(),
1010 tools: z.array(z.string()).optional(),
11+ rules: z
12+ .array(
13+ z.object({
14+ id: z.string(),
15+ rule: z.string(),
16+ }),
17+ )
18+ .optional(),
1119 });
modified packages/config-yaml/src/schemas/data/chatInteraction/v0.2.0.ts +1 −0
@@ -17,6 +17,7 @@
1717 modelProvider: true,
1818 sessionId: true,
1919 tools: true,
20+ rules: true,
2021 });
2122
2223 export const chatInteractionEventSchema_0_2_0_noCode =
modified packages/config-yaml/src/schemas/data/editOutcome/v0.2.0.ts +7 −0
@@ -15,10 +15,17 @@
1515 modelTitle: true,
1616 modelProvider: true,
1717 accepted: true,
18+ previousCode: true,
19+ newCode: true,
20+ previousCodeLines: true,
21+ newCodeLines: true,
22+ lineChange: true,
1823 });
1924
2025 export const editOutcomeEventSchema_0_2_0_noCode =
2126 editOutcomeEventSchema_0_2_0.omit({
2227 prompt: true,
2328 completion: true,
29+ previousCode: true,
30+ newCode: true,
2431 });
modified packages/hub/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/hub",
3- "version": "0.0.1",
3+ "version": "0.0.4",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/hub",
9- "version": "0.0.1",
9+ "version": "0.0.4",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-yaml": "^1.0.70"
modified packages/openai-adapters/src/apis/Bedrock.ts +23 −32
@@ -1,6 +1,7 @@
11 import {
22 BedrockRuntimeClient,
33 ContentBlock,
4+ ContentBlockStart,
45 ConversationRole,
56 ConverseStreamCommand,
67 ConverseStreamCommandInput,
@@ -57,8 +58,6 @@
5758 }
5859
5960 export class BedrockApi implements BaseLlmApi {
60- private _currentToolResponse: Partial<ToolUseState> | null = null;
61-
6261 constructor(protected config: BedrockConfig) {
6362 if (config.env?.accessKeyId || config?.env?.secretAccessKey) {
6463 if (!config.env?.accessKeyId) {
@@ -455,8 +454,6 @@
455454 throw new Error("No stream received from Bedrock API");
456455 }
457456
458- this._currentToolResponse = null;
459-
460457 for await (const chunk of response.stream) {
461458 if (chunk.contentBlockDelta?.delta) {
462459 const delta: any = chunk.contentBlockDelta.delta;
@@ -479,56 +476,50 @@
479476 }
480477
481478 // Handle tool use
482- if (delta.toolUse?.input && this._currentToolResponse) {
483- if (this._currentToolResponse.input === undefined) {
484- this._currentToolResponse.input = "";
485- }
486- this._currentToolResponse.input += delta.toolUse.input;
487- continue;
479+ if (delta.toolUse) {
480+ yield chatChunkFromDelta({
481+ model: body.model,
482+ delta: {
483+ tool_calls: [
484+ {
485+ index: 0,
486+ id: delta.toolUse.toolUseId,
487+ type: "function",
488+ function: {
489+ name: delta.toolUse.name,
490+ arguments: delta.toolUse.input,
491+ },
492+ },
493+ ],
494+ },
495+ });
488496 }
489497 }
490498
491499 if (chunk.contentBlockStart?.start) {
492- const start: any = chunk.contentBlockStart.start;
493-
494- // Handle tool start
495- const toolUse = start.toolUse;
496- if (toolUse?.toolUseId && toolUse?.name) {
497- this._currentToolResponse = {
498- toolUseId: toolUse.toolUseId,
499- name: toolUse.name,
500- input: "",
501- };
502- }
503- continue;
504- }
500+ const start: ContentBlockStart = chunk.contentBlockStart.start;
505501
506- if (chunk.contentBlockStop) {
507- // End of a content block
508- if (this._currentToolResponse) {
502+ if (start.toolUse) {
509503 yield chatChunkFromDelta({
510504 model: body.model,
511505 delta: {
512506 tool_calls: [
513507 {
514508 index: 0,
515- id: this._currentToolResponse.toolUseId,
509+ id: start.toolUse.toolUseId,
516510 type: "function",
517511 function: {
518- name: this._currentToolResponse.name,
519- arguments: this._currentToolResponse.input,
512+ name: start.toolUse.name,
513+ arguments: undefined,
520514 },
521515 },
522516 ],
523517 },
524518 });
525- this._currentToolResponse = null;
526519 }
527- continue;
528520 }
529521 }
530522 } catch (error) {
531- this._currentToolResponse = null;
532523 if (error instanceof Error) {
533524 if ("code" in error) {
534525 throw new Error(
modified scripts/install-dependencies.ps1 +27 −3
@@ -76,8 +76,20 @@
7676 Write-Host "`nInstalling root-level dependencies..." -ForegroundColor White
7777 npm install
7878
79-Write-Host "`nBuilding openai-adapters..." -ForegroundColor White
80-Push-Location packages/openai-adapters
79+Write-Host "`nBuilding config-types..." -ForegroundColor White
80+Push-Location packages/config-types
81+npm install
82+npm run build
83+Pop-Location
84+
85+Write-Host "`nBuilding fetch..." -ForegroundColor White
86+Push-Location packages/fetch
87+npm install
88+npm run build
89+Pop-Location
90+
91+Write-Host "`nBuilding llm-info..." -ForegroundColor White
92+Push-Location packages/llm-info
8193 npm install
8294 npm run build
8395 Pop-Location
@@ -88,6 +100,18 @@
88100 npm run build
89101 Pop-Location
90102
103+Write-Host "`nBuilding openai-adapters..." -ForegroundColor White
104+Push-Location packages/openai-adapters
105+npm install
106+npm run build
107+Pop-Location
108+
109+Write-Host "`nBuilding hub..." -ForegroundColor White
110+Push-Location packages/hub
111+npm install
112+npm run build
113+Pop-Location
114+
91115 Write-Host "`nInstalling Core extension dependencies..." -ForegroundColor White
92116 Push-Location core
93117 npm install
@@ -127,4 +151,4 @@
127151
128152 npm install
129153
130-Pop-Location
154+Pop-Location
No newline at the end of the file
modified scripts/install-dependencies.sh +27 −3
@@ -30,8 +30,20 @@
3030 echo "Installing root-level dependencies..."
3131 npm install
3232
33-echo "Building openai-adapters..."
34-pushd packages/openai-adapters
33+echo "Building config-types..."
34+pushd packages/config-types
35+npm install
36+npm run build
37+popd
38+
39+echo "Building fetch..."
40+pushd packages/fetch
41+npm install
42+npm run build
43+popd
44+
45+echo "Building llm-info..."
46+pushd packages/llm-info
3547 npm install
3648 npm run build
3749 popd
@@ -42,6 +54,18 @@
4254 npm run build
4355 popd
4456
57+echo "Building openai-adapters..."
58+pushd packages/openai-adapters
59+npm install
60+npm run build
61+popd
62+
63+echo "Building hub..."
64+pushd packages/hub
65+npm install
66+npm run build
67+popd
68+
4569 echo "Installing Core extension dependencies..."
4670 pushd core
4771 ## This flag is set because we pull down Chromium at runtime
@@ -76,4 +100,4 @@
76100 echo "Installing docs dependencies..."
77101 pushd docs
78102 npm install
79-popd
103+popd
No newline at the end of the file
modified scripts/uninstall.js +15 −0
@@ -18,6 +18,21 @@
1818 "./binary/bin",
1919 "./binary/dist",
2020 "./binary/out",
21+ // packages
22+ "./packages/config-types/node_modules",
23+ "./packages/config-types/dist",
24+ "./packages/fetch/node_modules",
25+ "./packages/fetch/dist",
26+ "./packages/llm-info/node_modules",
27+ "./packages/llm-info/dist",
28+ "./packages/config-yaml/node_modules",
29+ "./packages/config-yaml/dist",
30+ "./packages/openai-adapters/node_modules",
31+ "./packages/openai-adapters/dist",
32+ "./packages/hub/node_modules",
33+ "./packages/hub/dist",
34+ // docs
35+ "./docs/node_modules",
2136 // root
2237 "./node_modules",
2338 ];