Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into sestinj-patch-1
Changeset75f22779f30e45abd456560e2b21a1d3d6d2c4cc79da8454eb41337336c38cc8
AuthorNate <sestinj@gmail.com> · 2025-08-23 11:14 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-23 11:14 -07:00
Parents88b8936f200c, 5d5cc08efab1

Browse the files at this changeset

137 files changed

modified .github/actions/run-jetbrains-tests/action.yml +18 −2
@@ -44,6 +44,7 @@
4444 - name: Setup FFmpeg
4545 uses: AnimMouse/setup-ffmpeg@v1
4646 with:
47+ version: 7.1
4748 token: ${{ inputs.github-token }}
4849
4950 - name: Setup Gradle
@@ -93,6 +94,13 @@
9394 path: binary/node_modules
9495 key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
9596
97+ - name: Install binary dependencies
98+ if: steps.binary-cache.outputs.cache-hit != 'true'
99+ shell: bash
100+ run: |
101+ cd binary
102+ npm ci
103+
96104 - name: Build the binaries
97105 shell: bash
98106 run: |
@@ -128,14 +136,22 @@
128136 shell: bash
129137 run: |
130138 cd extensions/intellij
131- mv video build/reports
139+ if [ -d "video" ]; then
140+ mv video build/reports
141+ else
142+ echo "No video directory found to move"
143+ fi
132144
133145 - name: Copy logs
134146 if: ${{ failure() }}
135147 shell: bash
136148 run: |
137149 cd extensions/intellij
138- mv build/idea-sandbox/system/log/ build/reports
150+ if [ -d "build/idea-sandbox/system/log/" ]; then
151+ mv build/idea-sandbox/system/log/ build/reports
152+ else
153+ echo "No log directory found to copy"
154+ fi
139155
140156 - name: Save fails report
141157 if: ${{ failure() }}
added .github/actions/track-rerun/action.yml +19 −0
@@ -0,0 +1,19 @@
1+name: Track Workflow Rerun
2+description: Track when GitHub Actions workflows are rerun (attempt > 1)
3+
4+runs:
5+ using: composite
6+ steps:
7+ # Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.)
8+ - name: Track workflow rerun
9+ if: github.run_attempt > 1
10+ shell: bash
11+ run: |
12+ echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}"
13+ echo "📊 Workflow: ${{ github.workflow }}"
14+ echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}"
15+ echo "📝 Commit: ${{ github.sha }}"
16+ echo "👤 Actor: ${{ github.actor }}"
17+ echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
18+ echo ""
19+ echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'"
modified .github/workflows/beta-release.yml +12 −3
@@ -18,19 +18,28 @@
1818 runs-on: ubuntu-latest
1919 steps:
2020 - name: Checkout
21- uses: actions/checkout@v4
21+ uses: actions/checkout@v5
2222 with:
2323 fetch-depth: 0
2424 token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
2525
2626 - name: Setup Node.js
27- uses: actions/setup-node@v3
27+ uses: actions/setup-node@v4
2828 with:
2929 node-version: 20
3030 registry-url: "https://registry.npmjs.org"
3131 always-auth: true
3232
33- - name: Install dependencies
33+ - name: Setup packages
34+ uses: ./.github/actions/setup-packages
35+
36+ - name: Setup core component
37+ uses: ./.github/actions/setup-component
38+ with:
39+ component: core
40+ include-root: true
41+
42+ - name: Install CLI dependencies
3443 working-directory: extensions/cli
3544 run: npm ci
3645 env:
modified .github/workflows/cli-pr-checks.yml +41 −6
@@ -10,11 +10,19 @@
1010 issues: write
1111
1212 jobs:
13+ track-rerun:
14+ runs-on: ubuntu-latest
15+ if: github.run_attempt > 1
16+ steps:
17+ - uses: actions/checkout@v4
18+ - name: Track workflow rerun
19+ uses: ./.github/actions/track-rerun
20+
1321 lint:
1422 runs-on: ubuntu-latest
1523 steps:
1624 - name: Checkout code
17- uses: actions/checkout@v4
25+ uses: actions/checkout@v5
1826
1927 - name: Setup Node.js
2028 uses: actions/setup-node@v4
@@ -23,10 +31,18 @@
2331 cache: "npm"
2432 cache-dependency-path: extensions/cli/package-lock.json
2533
34+ - name: Setup packages
35+ uses: ./.github/actions/setup-packages
36+ - name: Setup core component
37+ uses: ./.github/actions/setup-component
38+ with:
39+ component: core
40+ include-root: true
41+
2642 - name: Install dependencies
2743 run: |
2844 cd extensions/cli
29- npm ci
45+ npm ci --include=optional
3046
3147 - name: Run linting
3248 run: |
@@ -42,25 +58,44 @@
4258
4359 steps:
4460 - name: Checkout code
45- uses: actions/checkout@v4
61+ uses: actions/checkout@v5
4662
4763 - name: Setup Node.js ${{ matrix.node-version }}
4864 uses: actions/setup-node@v4
4965 with:
5066 node-version: ${{ matrix.node-version }}
51- cache: "npm"
52- cache-dependency-path: extensions/cli/package-lock.json
67+
68+ - name: Cache CLI node_modules
69+ uses: actions/cache@v4
70+ with:
71+ path: extensions/cli/node_modules
72+ key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }}
73+ restore-keys: |
74+ ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-
75+
76+ - name: Setup packages
77+ uses: ./.github/actions/setup-packages
78+ - name: Setup core component
79+ uses: ./.github/actions/setup-component
80+ with:
81+ component: core
82+ include-root: true
5383
5484 - name: Install dependencies
5585 run: |
5686 cd extensions/cli
57- npm ci
87+ npm ci --include=optional
5888
5989 - name: Build
6090 run: |
6191 cd extensions/cli
6292 npm run build
6393
94+ - name: Run smoke tests
95+ run: |
96+ cd extensions/cli
97+ npm run test:smoke
98+
6499 # e2e tests are failing on Windows specifically - likely due to stdout flush issues
65100 - name: Run tests
66101 if: matrix.os != 'windows-latest'
deleted .github/workflows/docs.yml +0 −32
@@ -1,32 +0,0 @@
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@v5
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 +6 −4
@@ -120,7 +120,7 @@
120120
121121 # # Set up Java environment for the next steps
122122 - name: Setup Java
123- uses: actions/setup-java@v4
123+ uses: actions/setup-java@v5
124124 with:
125125 distribution: zulu
126126 java-version: 17
@@ -189,6 +189,8 @@
189189 cd ../../gui
190190 npm ci
191191 npm run build
192+ env:
193+ NODE_OPTIONS: "--max-old-space-size=8192"
192194
193195 # Run prepackage.js script
194196 - name: Run prepackage script
@@ -433,7 +435,7 @@
433435
434436 # Set up Java environment for the next steps
435437 - name: Setup Java
436- uses: actions/setup-java@v4
438+ uses: actions/setup-java@v5
437439 with:
438440 distribution: zulu
439441 java-version: 17
@@ -486,7 +488,7 @@
486488
487489 # Set up Java environment for the next steps
488490 - name: Setup Java
489- uses: actions/setup-java@v4
491+ uses: actions/setup-java@v5
490492 with:
491493 distribution: zulu
492494 java-version: 17
@@ -517,7 +519,7 @@
517519
518520 # Set up Java environment for the next steps
519521 - name: Setup Java
520- uses: actions/setup-java@v4
522+ uses: actions/setup-java@v5
521523 with:
522524 distribution: zulu
523525 java-version: 17
modified .github/workflows/main.yaml +1 −1
@@ -9,7 +9,7 @@
99 publish_build:
1010 description: "Whether or not to publish the built extension to the VS Code marketplace"
1111 required: true
12- default: false
12+ default: "false"
1313
1414 jobs:
1515 check_release_name:
modified .github/workflows/pr-checks.yaml +8 −0
@@ -11,6 +11,14 @@
1111 - main
1212
1313 jobs:
14+ track-rerun:
15+ runs-on: ubuntu-latest
16+ if: github.run_attempt > 1
17+ steps:
18+ - uses: actions/checkout@v5
19+ - name: Track workflow rerun
20+ uses: ./.github/actions/track-rerun
21+
1422 prettier-check:
1523 runs-on: ubuntu-latest
1624 steps:
modified .github/workflows/preview.yaml +2 −2
@@ -9,7 +9,7 @@
99 publish_build:
1010 description: "Whether or not to publish the built extension to the VS Code marketplace"
1111 required: true
12- default: false
12+ default: "false"
1313
1414 jobs:
1515 check_release_name:
@@ -20,7 +20,7 @@
2020 - id: check
2121 working-directory: .
2222 run: |
23- if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
23+ if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then
2424 echo "should_run=true" >> $GITHUB_OUTPUT
2525 else
2626 echo "should_run=false" >> $GITHUB_OUTPUT
modified .github/workflows/stable-release.yml +13 −2
@@ -34,13 +34,13 @@
3434 runs-on: ubuntu-latest
3535 steps:
3636 - name: Checkout
37- uses: actions/checkout@v4
37+ uses: actions/checkout@v5
3838 with:
3939 fetch-depth: 0
4040 token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
4141
4242 - name: Setup Node.js
43- uses: actions/setup-node@v3
43+ uses: actions/setup-node@v4
4444 with:
4545 node-version: 20
4646 registry-url: "https://registry.npmjs.org"
@@ -141,6 +141,17 @@
141141 # Update version to stable (remove beta suffix)
142142 npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
143143
144+ - name: Setup packages (for direct stable release)
145+ if: ${{ inputs.release_type == 'direct-stable' }}
146+ uses: ./.github/actions/setup-packages
147+
148+ - name: Setup core component (for direct stable release)
149+ if: ${{ inputs.release_type == 'direct-stable' }}
150+ uses: ./.github/actions/setup-component
151+ with:
152+ component: core
153+ include-root: true
154+
144155 - name: Prepare package for direct stable release
145156 if: ${{ inputs.release_type == 'direct-stable' }}
146157 working-directory: extensions/cli
modified .github/workflows/submit-github-dependency-graph.yml +1 −1
@@ -14,7 +14,7 @@
1414 - name: Checkout sources
1515 uses: actions/checkout@v5
1616 - name: Setup Java
17- uses: actions/setup-java@v4
17+ uses: actions/setup-java@v5
1818 with:
1919 distribution: "temurin"
2020 java-version: 17
modified .vscode/settings.json +2 −1
@@ -42,7 +42,8 @@
4242 "extensions/vscode/e2e/_output": true,
4343 "extensions/vscode/e2e/storage": true,
4444 "extensions/vscode/e2e/vsix": true,
45- "extensions/.continue-debug": true
45+ "extensions/.continue-debug": true,
46+ "extensions/cli/dist/**": true
4647 // "sync/**": true
4748 },
4849 "editor.formatOnSave": true,
modified binary/package-lock.json +12 −6
@@ -40,7 +40,7 @@
4040 "pkg": "^5.8.1",
4141 "rimraf": "^5.0.7",
4242 "ts-jest": "^29.1.4",
43- "typescript": "^5.3.3"
43+ "typescript": "^5.6.3"
4444 }
4545 },
4646 "../core": {
@@ -59,6 +59,11 @@
5959 "@modelcontextprotocol/sdk": "^1.12.0",
6060 "@mozilla/readability": "^0.5.0",
6161 "@octokit/rest": "^20.1.1",
62+ "@sentry/cli": "^2.50.2",
63+ "@sentry/core": "^9.43.0",
64+ "@sentry/esbuild-plugin": "^4.0.2",
65+ "@sentry/node": "^9.43.0",
66+ "@sentry/vite-plugin": "^4.0.2",
6267 "@typescript-eslint/eslint-plugin": "^7.8.0",
6368 "@xenova/transformers": "2.14.0",
6469 "adf-to-md": "^1.1.0",
@@ -78,7 +83,7 @@
7883 "http-proxy-agent": "^7.0.1",
7984 "https-proxy-agent": "^7.0.3",
8085 "iconv-lite": "^0.6.3",
81- "ignore": "^5.3.1",
86+ "ignore": "^7.0.5",
8287 "is-localhost-ip": "^2.0.0",
8388 "jinja-js": "0.1.8",
8489 "js-tiktoken": "^1.0.8",
@@ -91,7 +96,7 @@
9196 "node-html-markdown": "^1.3.0",
9297 "ollama": "^0.4.6",
9398 "onnxruntime-node": "1.14.0",
94- "openai": "^4.104.0",
99+ "openai": "^5.13.1",
95100 "p-limit": "^6.1.0",
96101 "partial-json": "^0.1.7",
97102 "pg": "^8.11.3",
@@ -6758,10 +6763,11 @@
67586763 }
67596764 },
67606765 "node_modules/typescript": {
6761- "version": "5.4.5",
6762- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
6763- "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
6766+ "version": "5.9.2",
6767+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
6768+ "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
67646769 "dev": true,
6770+ "license": "Apache-2.0",
67656771 "bin": {
67666772 "tsc": "bin/tsc",
67676773 "tsserver": "bin/tsserver"
modified core/autocomplete/CompletionProvider.ts +6 −1
@@ -6,12 +6,13 @@
66 import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
77 import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
88
9+import { isSecurityConcern } from "../indexing/ignore.js";
910 import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
1011 import { CompletionStreamer } from "./generation/CompletionStreamer.js";
1112 import { postprocessCompletion } from "./postprocessing/index.js";
1213 import { shouldPrefilter } from "./prefiltering/index.js";
13-import { renderPromptWithTokenLimit } from "./templating/index.js";
1414 import { getAllSnippetsWithoutRace } from "./snippets/index.js";
15+import { renderPromptWithTokenLimit } from "./templating/index.js";
1516 import { GetLspDefinitionsFunction } from "./types.js";
1617 import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
1718 import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
@@ -150,6 +151,10 @@
150151 return undefined;
151152 }
152153
154+ if (isSecurityConcern(input.filepath)) {
155+ return undefined;
156+ }
157+
153158 const options = await this._getAutocompleteOptions(llm);
154159
155160 // Debounce
modified core/autocomplete/prefiltering/index.ts +1 −1
@@ -4,7 +4,7 @@
44 import {
55 getGlobalContinueIgArray,
66 getWorkspaceContinueIgArray,
7-} from "../../indexing/ignore";
7+} from "../../indexing/continueignore";
88 import { getConfigJsonPath } from "../../util/paths";
99 import { findUriInDirs } from "../../util/uri";
1010 import { HelperVars } from "../util/HelperVars";
modified core/commands/slash/built-in-legacy/onboard.ts +2 −5
@@ -1,11 +1,8 @@
11 import ignore from "ignore";
22
33 import type { FileType, IDE, SlashCommand } from "../../..";
4-import {
5- DEFAULT_IGNORE,
6- getGlobalContinueIgArray,
7- gitIgArrayFromFile,
8-} from "../../../indexing/ignore";
4+import { getGlobalContinueIgArray } from "../../../indexing/continueignore";
5+import { DEFAULT_IGNORE, gitIgArrayFromFile } from "../../../indexing/ignore";
96 import { renderChatMessage } from "../../../util/messageContent";
107 import {
118 findUriInDirs,
modified core/config/loadContextProviders.ts +14 −10
@@ -29,11 +29,24 @@
2929 } {
3030 const providers: IContextProvider[] = [];
3131 const errors: ConfigValidationError[] = [];
32+
33+ const defaultProviders: IContextProvider[] = [
34+ new FileContextProvider({}),
35+ new CurrentFileContextProvider({}),
36+ new DiffContextProvider({}),
37+ new TerminalContextProvider({}),
38+ new ProblemsContextProvider({}),
39+ new RulesContextProvider({}),
40+ ];
41+
3242 // Add from config
3343 if (configContext) {
3444 for (const config of configContext) {
3545 const cls = contextProviderClassFromName(config.provider) as any;
36- if (!cls) {
46+ if (
47+ !cls &&
48+ !defaultProviders.find((p) => p.description.title === config.provider)
49+ ) {
3750 errors.push({
3851 fatal: false,
3952 message: `Unknown context provider ${config.provider}`,
@@ -50,15 +63,6 @@
5063 }
5164
5265 // Add from defaults if not found in config
53- const defaultProviders: IContextProvider[] = [
54- new FileContextProvider({}),
55- new CurrentFileContextProvider({}),
56- new DiffContextProvider({}),
57- new TerminalContextProvider({}),
58- new ProblemsContextProvider({}),
59- new RulesContextProvider({}),
60- ];
61-
6266 for (const defaultProvider of defaultProviders) {
6367 if (
6468 !providers.find(
modified core/context/providers/FileContextProvider.ts +1 −0
@@ -6,6 +6,7 @@
66 ContextSubmenuItem,
77 LoadSubmenuItemsArgs,
88 } from "../../";
9+import { isSecurityConcern } from "../../indexing/ignore";
910 import { walkDirs } from "../../indexing/walkDir";
1011 import {
1112 getShortestUniqueRelativeUriPaths,
modified core/context/providers/OpenFilesContextProvider.ts +15 −1
@@ -3,6 +3,7 @@
33 ContextProviderDescription,
44 ContextProviderExtras,
55 } from "../../index.js";
6+import { isSecurityConcern } from "../../indexing/ignore.js";
67 import { getUriDescription } from "../../util/uri.js";
78 import { BaseContextProvider } from "../index.js";
89
@@ -27,10 +28,23 @@
2728
2829 return await Promise.all(
2930 openFiles.map(async (filepath: string) => {
30- const content = await ide.readFile(filepath);
3131 const { relativePathOrBasename, last2Parts, baseName } =
3232 getUriDescription(filepath, workspaceDirs);
3333
34+ if (isSecurityConcern(filepath)) {
35+ return {
36+ description: last2Parts,
37+ content:
38+ "Content redacted, this file cannot be viewed for security reasons",
39+ name: baseName,
40+ uri: {
41+ type: "file",
42+ value: filepath,
43+ },
44+ };
45+ }
46+ const content = await ide.readFile(filepath);
47+
3448 return {
3549 description: last2Parts,
3650 content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
modified core/context/providers/ProblemsContextProvider.ts +2 −1
@@ -3,6 +3,7 @@
33 ContextProviderDescription,
44 ContextProviderExtras,
55 } from "../../index.js";
6+import { isSecurityConcern } from "../../indexing/ignore.js";
67 import { getUriDescription } from "../../util/uri.js";
78 import { BaseContextProvider } from "../index.js";
89
@@ -40,7 +41,7 @@
4041 return {
4142 description: "Problems in current file",
4243 content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
43- name: `Warning in ${baseName}`,
44+ name: `Warnings in ${baseName}`,
4445 };
4546 }),
4647 );
modified core/context/providers/index.ts +2 −0
@@ -12,6 +12,7 @@
1212 import DiffContextProvider from "./DiffContextProvider";
1313 import DiscordContextProvider from "./DiscordContextProvider";
1414 import DocsContextProvider from "./DocsContextProvider";
15+import FileContextProvider from "./FileContextProvider";
1516 import FileTreeContextProvider from "./FileTreeContextProvider";
1617 import FolderContextProvider from "./FolderContextProvider";
1718 import GitCommitContextProvider from "./GitCommitContextProvider";
@@ -41,6 +42,7 @@
4142 * See this issue for details: https://github.com/continuedev/continue/issues/1365
4243 */
4344 export const Providers: (typeof BaseContextProvider)[] = [
45+ FileContextProvider,
4446 DiffContextProvider,
4547 FileTreeContextProvider,
4648 GitHubIssuesContextProvider,
modified core/context/retrieval/retrieval.ts +1 −1
@@ -37,7 +37,7 @@
3737 const nFinal =
3838 options?.nFinal ??
3939 Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
40- const useReranking = !!extras.reranker;
40+ const useReranking = options?.useReranking ?? !!extras.reranker;
4141 const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
4242
4343 const branches = (await Promise.race([
added core/indexing/continueignore.ts +26 −0
@@ -0,0 +1,26 @@
1+import fs from "fs";
2+import { IDE } from "..";
3+import { getGlobalContinueIgnorePath } from "../util/paths";
4+import { gitIgArrayFromFile } from "./ignore";
5+
6+export const getGlobalContinueIgArray = () => {
7+ const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
8+ return gitIgArrayFromFile(contents);
9+};
10+
11+export const getWorkspaceContinueIgArray = async (ide: IDE) => {
12+ const dirs = await ide.getWorkspaceDirs();
13+ return await dirs.reduce(
14+ async (accPromise, dir) => {
15+ const acc = await accPromise;
16+ try {
17+ const contents = await ide.readFile(`${dir}/.continueignore`);
18+ return [...acc, ...gitIgArrayFromFile(contents)];
19+ } catch (err) {
20+ console.error(err);
21+ return acc;
22+ }
23+ },
24+ Promise.resolve([] as string[]),
25+ );
26+};
modified core/indexing/ignore.ts +161 −44
@@ -1,11 +1,100 @@
1-import fs from "fs";
2-
31 import ignore from "ignore";
42
5-import { IDE } from "..";
6-import { getGlobalContinueIgnorePath } from "../util/paths";
3+import path from "path";
4+import { fileURLToPath } from "url";
75
8-export const DEFAULT_IGNORE_FILETYPES = [
6+// Security-focused ignore patterns - these should always be excluded for security reasons
7+export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
8+ // Environment and configuration files with secrets
9+ "*.env",
10+ "*.env.*",
11+ ".env*",
12+ "config.json",
13+ "config.yaml",
14+ "config.yml",
15+ "settings.json",
16+ "appsettings.json",
17+ "appsettings.*.json",
18+
19+ // Certificate and key files
20+ "*.key",
21+ "*.pem",
22+ "*.p12",
23+ "*.pfx",
24+ "*.crt",
25+ "*.cer",
26+ "*.jks",
27+ "*.keystore",
28+ "*.truststore",
29+
30+ // Database files that may contain sensitive data
31+ "*.db",
32+ "*.sqlite",
33+ "*.sqlite3",
34+ "*.mdb",
35+ "*.accdb",
36+
37+ // Credential and secret files
38+ "*.secret",
39+ "*.secrets",
40+ "credentials",
41+ "credentials.*",
42+ "auth.json",
43+ "token",
44+ "token.*",
45+ "*.token",
46+
47+ // Backup files that might contain sensitive data
48+ "*.bak",
49+ "*.backup",
50+ "*.old",
51+ "*.orig",
52+
53+ // Docker secrets
54+ "docker-compose.override.yml",
55+ "docker-compose.override.yaml",
56+
57+ // SSH and GPG
58+ "id_rsa",
59+ "id_dsa",
60+ "id_ecdsa",
61+ "id_ed25519",
62+ "*.ppk",
63+ "*.gpg",
64+];
65+
66+export const DEFAULT_SECURITY_IGNORE_DIRS = [
67+ // Environment and configuration directories
68+ ".env/",
69+ "env/",
70+
71+ // Cloud provider credential directories
72+ ".aws/",
73+ ".gcp/",
74+ ".azure/",
75+ ".kube/",
76+ ".docker/",
77+
78+ // Secret directories
79+ "secrets/",
80+ ".secrets/",
81+ "private/",
82+ ".private/",
83+ "certs/",
84+ "certificates/",
85+ "keys/",
86+ ".ssh/",
87+ ".gnupg/",
88+ ".gpg/",
89+
90+ // Temporary directories that might contain sensitive data
91+ "tmp/secrets/",
92+ "temp/secrets/",
93+ ".tmp/",
94+];
95+
96+// Additional non-security patterns for general indexing exclusion
97+export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [
998 "*.DS_Store",
1099 "*-lock.json",
11100 "*.lock",
@@ -46,8 +135,6 @@
46135 "*.mpeg",
47136 "*.mov",
48137 "*.mp3",
49- "*.mp4",
50- "*.mkv",
51138 "*.mkv",
52139 "*.webm",
53140 "*.jar",
@@ -56,20 +143,15 @@
56143 "*.pqt",
57144 "*.wav",
58145 "*.webp",
59- "*.db",
60- "*.sqlite",
61146 "*.wasm",
62147 "*.plist",
63148 "*.profraw",
64149 "*.gcda",
65150 "*.gcno",
66151 "go.sum",
67- "*.env",
68152 "*.gitignore",
69153 "*.gitkeep",
70154 "*.continueignore",
71- "config.json",
72- "config.yaml",
73155 "*.csv",
74156 "*.uasset",
75157 "*.pdb",
@@ -78,19 +160,13 @@
78160 "*.swp",
79161 "*.jsonl",
80162 // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
163+ // Application specific
164+ ".continue/",
81165 ];
82166
83-export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
84-export const DEFAULT_IGNORE_DIRS = [
167+export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
85168 ".git/",
86169 ".svn/",
87- ".vscode/",
88- ".idea/",
89- ".vs/",
90- "venv/",
91- ".venv/",
92- "env/",
93- ".env/",
94170 "node_modules/",
95171 "dist/",
96172 "build/",
@@ -100,7 +176,6 @@
100176 "bin/",
101177 ".pytest_cache/",
102178 ".vscode-test/",
103- ".continue/",
104179 "__pycache__/",
105180 "site-packages/",
106181 ".gradle/",
@@ -108,42 +183,84 @@
108183 ".cache/",
109184 "gems/",
110185 "vendor/",
186+
187+ ".venv/",
188+ "venv/",
189+
190+ ".vscode/",
191+ ".idea/",
192+ ".vs/",
193+];
194+
195+// Combined patterns: security + additional
196+export const DEFAULT_IGNORE_FILETYPES = [
197+ ...DEFAULT_SECURITY_IGNORE_FILETYPES,
198+ ...ADDITIONAL_INDEXING_IGNORE_FILETYPES,
199+];
200+
201+export const DEFAULT_IGNORE_DIRS = [
202+ ...DEFAULT_SECURITY_IGNORE_DIRS,
203+ ...ADDITIONAL_INDEXING_IGNORE_DIRS,
111204 ];
112205
206+// Create ignore instances
207+export const defaultSecurityIgnoreFile = ignore().add(
208+ DEFAULT_SECURITY_IGNORE_FILETYPES,
209+);
210+export const defaultSecurityIgnoreDir = ignore().add(
211+ DEFAULT_SECURITY_IGNORE_DIRS,
212+);
213+export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
113214 export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
114215
216+// String representations
217+export const DEFAULT_SECURITY_IGNORE =
218+ DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") +
219+ "\n" +
220+ DEFAULT_SECURITY_IGNORE_DIRS.join("\n");
221+
115222 export const DEFAULT_IGNORE =
116223 DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
117224
225+// Combined ignore instances
226+export const defaultFileAndFolderSecurityIgnores = ignore()
227+ .add(defaultSecurityIgnoreFile)
228+ .add(defaultSecurityIgnoreDir);
229+
118230 export const defaultIgnoreFileAndDir = ignore()
119231 .add(defaultIgnoreFile)
120232 .add(defaultIgnoreDir);
121233
234+export function isSecurityConcern(filePathOrUri: string) {
235+ if (!filePathOrUri) {
236+ return false;
237+ }
238+ let filepath = filePathOrUri;
239+ try {
240+ filepath = fileURLToPath(filePathOrUri);
241+ } catch {}
242+ if (path.isAbsolute(filepath)) {
243+ const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? "";
244+ const basename = path.basename(filepath);
245+ filepath = `${dir ? dir + "/" : ""}${basename}`;
246+ }
247+ if (!filepath) {
248+ return false;
249+ }
250+ return defaultFileAndFolderSecurityIgnores.ignores(filepath);
251+}
252+
253+export function throwIfFileIsSecurityConcern(filepath: string) {
254+ if (isSecurityConcern(filepath)) {
255+ throw new Error(
256+ `Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
257+ );
258+ }
259+}
260+
122261 export function gitIgArrayFromFile(file: string) {
123262 return file
124263 .split(/\r?\n/) // Split on new line
125264 .map((l) => l.trim()) // Remove whitespace
126265 .filter((l) => !/^#|^$/.test(l)); // Remove empty lines
127266 }
128-
129-export const getGlobalContinueIgArray = () => {
130- const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
131- return gitIgArrayFromFile(contents);
132-};
133-
134-export const getWorkspaceContinueIgArray = async (ide: IDE) => {
135- const dirs = await ide.getWorkspaceDirs();
136- return await dirs.reduce(
137- async (accPromise, dir) => {
138- const acc = await accPromise;
139- try {
140- const contents = await ide.readFile(`${dir}/.continueignore`);
141- return [...acc, ...gitIgArrayFromFile(contents)];
142- } catch (err) {
143- console.error(err);
144- return acc;
145- }
146- },
147- Promise.resolve([] as string[]),
148- );
149-};
added core/indexing/ignore.vitest.ts +257 −0
@@ -0,0 +1,257 @@
1+import { describe, expect, it } from "vitest";
2+import {
3+ DEFAULT_SECURITY_IGNORE_DIRS,
4+ DEFAULT_SECURITY_IGNORE_FILETYPES,
5+ defaultFileAndFolderSecurityIgnores,
6+ isSecurityConcern,
7+} from "./ignore";
8+
9+describe("isSecurityConcern", () => {
10+ describe("Security file types", () => {
11+ it("should detect environment files as security concerns", () => {
12+ expect(isSecurityConcern(".env")).toBe(true);
13+ expect(isSecurityConcern(".env.local")).toBe(true);
14+ expect(isSecurityConcern(".env.production")).toBe(true);
15+ expect(isSecurityConcern("config/.env")).toBe(true);
16+ expect(isSecurityConcern("/path/to/.env")).toBe(true);
17+ expect(isSecurityConcern("file:///path/to/.env")).toBe(true);
18+ });
19+
20+ it("should detect configuration files as security concerns", () => {
21+ expect(isSecurityConcern("config.json")).toBe(true);
22+ expect(isSecurityConcern("config.yaml")).toBe(true);
23+ expect(isSecurityConcern("config.yml")).toBe(true);
24+ expect(isSecurityConcern("settings.json")).toBe(true);
25+ expect(isSecurityConcern("appsettings.json")).toBe(true);
26+ expect(isSecurityConcern("appsettings.development.json")).toBe(true);
27+ expect(isSecurityConcern("appsettings.production.json")).toBe(true);
28+ });
29+
30+ it("should detect certificate and key files as security concerns", () => {
31+ expect(isSecurityConcern("private.key")).toBe(true);
32+ expect(isSecurityConcern("certificate.pem")).toBe(true);
33+ expect(isSecurityConcern("server.crt")).toBe(true);
34+ expect(isSecurityConcern("keystore.jks")).toBe(true);
35+ expect(isSecurityConcern("ssl/server.key")).toBe(true);
36+ expect(isSecurityConcern("/etc/ssl/certs/server.pem")).toBe(true);
37+ });
38+
39+ it("should detect database files as security concerns", () => {
40+ expect(isSecurityConcern("database.db")).toBe(true);
41+ expect(isSecurityConcern("users.sqlite")).toBe(true);
42+ expect(isSecurityConcern("data.sqlite3")).toBe(true);
43+ expect(isSecurityConcern("app.mdb")).toBe(true);
44+ expect(isSecurityConcern("data/users.db")).toBe(true);
45+ });
46+
47+ it("should detect credential files as security concerns", () => {
48+ expect(isSecurityConcern("app.secret")).toBe(true);
49+ expect(isSecurityConcern("api.secrets")).toBe(true);
50+ expect(isSecurityConcern("credentials")).toBe(true);
51+ expect(isSecurityConcern("credentials.json")).toBe(true);
52+ expect(isSecurityConcern("auth.json")).toBe(true);
53+ expect(isSecurityConcern("token")).toBe(true);
54+ expect(isSecurityConcern("api.token")).toBe(true);
55+ expect(isSecurityConcern("access.token")).toBe(true);
56+ });
57+
58+ it("should detect backup files as security concerns", () => {
59+ expect(isSecurityConcern("database.bak")).toBe(true);
60+ expect(isSecurityConcern("config.backup")).toBe(true);
61+ expect(isSecurityConcern("settings.old")).toBe(true);
62+ expect(isSecurityConcern("app.orig")).toBe(true);
63+ });
64+
65+ it("should detect Docker override files as security concerns", () => {
66+ expect(isSecurityConcern("docker-compose.override.yml")).toBe(true);
67+ expect(isSecurityConcern("docker-compose.override.yaml")).toBe(true);
68+ });
69+
70+ it("should detect SSH and GPG files as security concerns", () => {
71+ expect(isSecurityConcern("id_rsa")).toBe(true);
72+ expect(isSecurityConcern("id_dsa")).toBe(true);
73+ expect(isSecurityConcern("id_ecdsa")).toBe(true);
74+ expect(isSecurityConcern("id_ed25519")).toBe(true);
75+ expect(isSecurityConcern("private.ppk")).toBe(true);
76+ expect(isSecurityConcern("secret.gpg")).toBe(true);
77+ });
78+ });
79+
80+ describe("Security directories", () => {
81+ it("should detect environment directories as security concerns", () => {
82+ expect(isSecurityConcern(".env/")).toBe(true);
83+ expect(isSecurityConcern("env/")).toBe(true);
84+ expect(isSecurityConcern(".env/config")).toBe(true);
85+ });
86+
87+ it("should detect cloud provider directories as security concerns", () => {
88+ expect(isSecurityConcern(".aws/")).toBe(true);
89+ expect(isSecurityConcern(".gcp/")).toBe(true);
90+ expect(isSecurityConcern(".azure/")).toBe(true);
91+ expect(isSecurityConcern(".kube/")).toBe(true);
92+ expect(isSecurityConcern(".docker/")).toBe(true);
93+ expect(isSecurityConcern(".aws/credentials")).toBe(true);
94+ expect(isSecurityConcern(".kube/config")).toBe(true);
95+ });
96+
97+ it("should detect secret directories as security concerns", () => {
98+ expect(isSecurityConcern("secrets/")).toBe(true);
99+ expect(isSecurityConcern(".secrets/")).toBe(true);
100+ expect(isSecurityConcern("private/")).toBe(true);
101+ expect(isSecurityConcern(".private/")).toBe(true);
102+ expect(isSecurityConcern("certs/")).toBe(true);
103+ expect(isSecurityConcern("certificates/")).toBe(true);
104+ expect(isSecurityConcern("keys/")).toBe(true);
105+ expect(isSecurityConcern(".ssh/")).toBe(true);
106+ expect(isSecurityConcern(".gnupg/")).toBe(true);
107+ expect(isSecurityConcern(".gpg/")).toBe(true);
108+ });
109+
110+ it("should detect continue directory as security concern", () => {
111+ expect(isSecurityConcern(".continue/config.json")).toBe(true);
112+ });
113+
114+ it("should detect temporary secret directories as security concerns", () => {
115+ expect(isSecurityConcern("tmp/secrets/")).toBe(true);
116+ expect(isSecurityConcern("temp/secrets/")).toBe(true);
117+ expect(isSecurityConcern(".tmp/")).toBe(true);
118+ expect(isSecurityConcern("tmp/secrets/api.key")).toBe(true);
119+ });
120+ });
121+
122+ describe("Path variations", () => {
123+ it("should handle absolute paths", () => {
124+ expect(isSecurityConcern("/home/user/.env")).toBe(true);
125+ expect(isSecurityConcern("/var/www/.secrets/")).toBe(true);
126+ expect(isSecurityConcern("/etc/ssl/private.key")).toBe(true);
127+ });
128+
129+ it("should handle URI schemes", () => {
130+ expect(isSecurityConcern("file:///home/user/.env")).toBe(true);
131+ expect(isSecurityConcern("file:///var/secrets/api.key")).toBe(true);
132+ });
133+
134+ it("should handle nested paths", () => {
135+ expect(isSecurityConcern("project/config/.env")).toBe(true);
136+ expect(isSecurityConcern("src/main/resources/application.secret")).toBe(
137+ true,
138+ );
139+ expect(isSecurityConcern("backend/certs/server.key")).toBe(true);
140+ });
141+
142+ // it("should handle Windows-style paths", () => {
143+ // expect(isSecurityConcern("C:\\Users\\user\\.env")).toBe(true);
144+ // expect(isSecurityConcern("D:\\projects\\app\\secrets\\")).toBe(true);
145+ // });
146+ });
147+
148+ describe("Non-security files", () => {
149+ it("should not flag regular source code files", () => {
150+ expect(isSecurityConcern("src/main.js")).toBe(false);
151+ expect(isSecurityConcern("components/App.tsx")).toBe(false);
152+ expect(isSecurityConcern("utils/helper.py")).toBe(false);
153+ expect(isSecurityConcern("models/User.java")).toBe(false);
154+ expect(isSecurityConcern("styles/main.css")).toBe(false);
155+ });
156+
157+ it("should not flag regular configuration files", () => {
158+ expect(isSecurityConcern("package.json")).toBe(false);
159+ expect(isSecurityConcern("tsconfig.json")).toBe(false);
160+ expect(isSecurityConcern("webpack.config.js")).toBe(false);
161+ expect(isSecurityConcern("babel.config.js")).toBe(false);
162+ expect(isSecurityConcern("jest.config.js")).toBe(false);
163+ });
164+
165+ it("should not flag documentation files", () => {
166+ expect(isSecurityConcern("README.md")).toBe(false);
167+ expect(isSecurityConcern("CHANGELOG.md")).toBe(false);
168+ expect(isSecurityConcern("docs/api.md")).toBe(false);
169+ expect(isSecurityConcern("LICENSE")).toBe(false);
170+ });
171+
172+ it("should not flag regular directories", () => {
173+ expect(isSecurityConcern("src/")).toBe(false);
174+ expect(isSecurityConcern("components/")).toBe(false);
175+ expect(isSecurityConcern("utils/")).toBe(false);
176+ expect(isSecurityConcern("tests/")).toBe(false);
177+ expect(isSecurityConcern("docs/")).toBe(false);
178+ });
179+
180+ it("should not flag files with similar names but different extensions", () => {
181+ expect(isSecurityConcern("environment.js")).toBe(false);
182+ expect(isSecurityConcern("config-template.json")).toBe(false);
183+ expect(isSecurityConcern("secret-utils.js")).toBe(false);
184+ expect(isSecurityConcern("token-validator.ts")).toBe(false);
185+ });
186+ });
187+
188+ describe("Edge cases", () => {
189+ it("should handle empty strings", () => {
190+ expect(isSecurityConcern("")).toBe(false);
191+ });
192+
193+ it("should handle paths with only separators", () => {
194+ expect(isSecurityConcern("/")).toBe(false);
195+ });
196+
197+ it("should handle paths with multiple extensions", () => {
198+ expect(isSecurityConcern("backup.env.old")).toBe(true); // matches *.old
199+ expect(isSecurityConcern("config.json.bak")).toBe(true); // matches *.bak
200+ expect(isSecurityConcern("server.key.backup")).toBe(true); // matches *.backup
201+ });
202+
203+ it("should handle files in root vs subdirectories", () => {
204+ expect(isSecurityConcern(".env")).toBe(true);
205+ expect(isSecurityConcern("project/.env")).toBe(true);
206+ expect(isSecurityConcern("deeply/nested/path/.env")).toBe(true);
207+ });
208+ });
209+
210+ describe("Pattern matching consistency", () => {
211+ it("should match all defined security file patterns", () => {
212+ // Test a sample from each category to ensure patterns work
213+ DEFAULT_SECURITY_IGNORE_FILETYPES.forEach((pattern) => {
214+ // Create a test file name that should match the pattern
215+ let testFile: string;
216+ if (pattern.startsWith("*.")) {
217+ testFile = `test${pattern.substring(1)}`;
218+ } else if (pattern.includes("*")) {
219+ testFile = pattern.replace("*", "test");
220+ } else {
221+ testFile = pattern;
222+ }
223+
224+ expect(isSecurityConcern(testFile)).toBe(true);
225+ });
226+ });
227+
228+ it("should match all defined security directory patterns", () => {
229+ DEFAULT_SECURITY_IGNORE_DIRS.forEach((pattern) => {
230+ // Test the directory pattern directly
231+ expect(isSecurityConcern(pattern)).toBe(true);
232+
233+ // Test a file inside the directory
234+ const fileInDir = `${pattern}testfile.txt`;
235+ expect(isSecurityConcern(fileInDir)).toBe(true);
236+ });
237+ });
238+ });
239+
240+ describe("Integration with ignore library", () => {
241+ it("should use the same ignore instance as defaultFileAndFolderSecurityIgnores", () => {
242+ // Test that our function uses the same logic as the exported ignore instance
243+ const testFiles = [
244+ ".env",
245+ "secrets/api.key",
246+ ".aws/credentials",
247+ "regular-file.js",
248+ ];
249+
250+ testFiles.forEach((file) => {
251+ const functionResult = isSecurityConcern(file);
252+ const ignoreResult = defaultFileAndFolderSecurityIgnores.ignores(file);
253+ expect(functionResult).toBe(ignoreResult);
254+ });
255+ });
256+ });
257+});
modified core/indexing/shouldIgnore.ts +2 −1
@@ -1,7 +1,8 @@
11 import ignore from "ignore";
22 import type { FileType, IDE } from "../";
33 import { findUriInDirs, getUriPathBasename } from "../util/uri";
4-import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
4+import { getGlobalContinueIgArray } from "./continueignore";
5+import { defaultIgnoreFileAndDir } from "./ignore";
56 import { getIgnoreContext } from "./walkDir";
67
78 /*
modified core/indexing/walkDir.ts +2 −5
@@ -3,11 +3,8 @@
33 import type { FileType, IDE } from "..";
44
55 import { joinPathsToUri } from "../util/uri";
6-import {
7- defaultIgnoreFileAndDir,
8- getGlobalContinueIgArray,
9- gitIgArrayFromFile,
10-} from "./ignore";
6+import { getGlobalContinueIgArray } from "./continueignore";
7+import { defaultIgnoreFileAndDir, gitIgArrayFromFile } from "./ignore";
118
129 export interface WalkerOptions {
1310 include?: "dirs" | "files" | "both";
modified core/llm/autodetect.ts +0 −1
@@ -178,7 +178,6 @@
178178 // update core/nextEdit/templating/NextEditPromptEngine.ts as well.
179179 const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
180180 NEXT_EDIT_MODELS.MERCURY_CODER,
181- NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
182181 NEXT_EDIT_MODELS.INSTINCT,
183182 ];
184183
modified core/llm/autodetect.vitest.ts +12 −12
@@ -220,7 +220,7 @@
220220 expect(
221221 modelSupportsNextEdit(
222222 { nextEdit: false },
223- "mercury-coder-nextedit",
223+ "mercury-coder",
224224 "Mercury Coder",
225225 ),
226226 ).toBe(false);
@@ -231,7 +231,7 @@
231231 expect(
232232 modelSupportsNextEdit(
233233 { nextEdit: false },
234- "mercury-coder-nextedit",
234+ "mercury-coder",
235235 "Mercury Coder",
236236 ),
237237 ).toBe(false);
@@ -239,10 +239,10 @@
239239 });
240240
241241 describe("when capabilities.nextEdit is undefined", () => {
242- it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
243- expect(
244- modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
245- ).toBe(true);
242+ it("should return true for mercury-coder model (case insensitive)", () => {
243+ expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe(
244+ true,
245+ );
246246 });
247247
248248 it("should return true for instinct", () => {
@@ -255,7 +255,7 @@
255255 expect(
256256 modelSupportsNextEdit(
257257 undefined,
258- "provider/mercury-coder-nextedit-v2",
258+ "provider/mercury-coder-v2",
259259 undefined,
260260 ),
261261 ).toBe(true);
@@ -266,7 +266,7 @@
266266 modelSupportsNextEdit(
267267 undefined,
268268 "some-model",
269- "This is mercury-coder-nextedit model",
269+ "This is mercury-coder model",
270270 ),
271271 ).toBe(true);
272272 });
@@ -312,14 +312,14 @@
312312 });
313313
314314 it("should handle undefined title gracefully", () => {
315- expect(
316- modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
317- ).toBe(true);
315+ expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe(
316+ true,
317+ );
318318 });
319319
320320 it("should handle case sensitivity correctly", () => {
321321 expect(
322- modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
322+ modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"),
323323 ).toBe(true);
324324 });
325325
modified core/llm/constants.ts +0 −1
@@ -21,7 +21,6 @@
2121
2222 export enum NEXT_EDIT_MODELS {
2323 MERCURY_CODER = "mercury-coder",
24- MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
2524 INSTINCT = "instinct",
2625 }
2726
modified core/llm/defaultSystemMessages.ts +11 −1
@@ -46,6 +46,8 @@
4646 of changes unless the user specifically asks for code only.
4747 `;
4848
49+const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`;
50+
4951 export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
5052 <important_rules>
5153 You are in chat mode.
@@ -64,6 +66,11 @@
6466 If you need to use multiple tools, you can call multiple read only tools simultaneously.
6567
6668 ${CODEBLOCK_FORMATTING_INSTRUCTIONS}
69+
70+${BRIEF_LAZY_INSTRUCTIONS}
71+
72+However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools.
73+
6774 </important_rules>`;
6875
6976 // The note about read-only tools is for MCP servers
@@ -75,7 +82,10 @@
7582 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.
7683
7784 ${CODEBLOCK_FORMATTING_INSTRUCTIONS}
78-${EDIT_CODE_INSTRUCTIONS}
85+
86+${BRIEF_LAZY_INSTRUCTIONS}
87+
88+However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode.
7989
8090 In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
8191 </important_rules>`;
modified core/llm/llm.test.ts +1 −1
@@ -213,7 +213,7 @@
213213
214214 testLLM(
215215 new Anthropic({
216- model: "claude-3-5-sonnet-latest",
216+ model: "claude-sonnet-4-0",
217217 apiKey: process.env.ANTHROPIC_API_KEY,
218218 }),
219219 { skip: false, testToolCall: true },
modified core/llm/toolSupport.test.ts +29 −0
@@ -280,6 +280,34 @@
280280 });
281281 });
282282
283+ describe("novita", () => {
284+ const supportsFn = PROVIDER_TOOL_SUPPORT["novita"];
285+
286+ it("should return true for exact match models", () => {
287+ expect(supportsFn("deepseek/deepseek-r1-0528")).toBe(true);
288+ expect(supportsFn("deepseek/deepseek-r1-turbo")).toBe(true);
289+ expect(supportsFn("deepseek/deepseek-v3-0324")).toBe(true);
290+ expect(supportsFn("deepseek/deepseek-v3-turbo")).toBe(true);
291+ expect(supportsFn("meta-llama/llama-3.3-70b-instruct")).toBe(true);
292+ expect(supportsFn("qwen/qwen-2.5-72b-instruct")).toBe(true);
293+ expect(supportsFn("zai-org/glm-4.5")).toBe(true);
294+ expect(supportsFn("moonshotai/kimi-k2-instruct")).toBe(true);
295+ });
296+
297+ it("should return true for prefix match models", () => {
298+ expect(supportsFn("qwen/qwen3-235b-a22b-instruct-2507")).toBe(true);
299+ expect(supportsFn("openai/gpt-oss-20b")).toBe(true);
300+ expect(supportsFn("openai/gpt-oss-120b")).toBe(true);
301+ });
302+
303+ it("should return false for unsupported models", () => {
304+ expect(supportsFn("deepseek/deepseek-chat")).toBe(false);
305+ expect(supportsFn("meta-llama/llama-2-7b")).toBe(false);
306+ expect(supportsFn("qwen/qwen-2.0-7b")).toBe(false);
307+ expect(supportsFn("openai/gpt-4")).toBe(false);
308+ });
309+ });
310+
283311 describe("openrouter", () => {
284312 const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"];
285313
@@ -297,6 +325,7 @@
297325 expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
298326 expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
299327 expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
328+ expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false);
300329 });
301330
302331 it("should handle non-existent provider", () => {
modified core/llm/toolSupport.ts +32 −0
@@ -124,6 +124,7 @@
124124 "nova-pro",
125125 "nova-micro",
126126 "nova-premier",
127+ "gpt-oss",
127128 ].some((part) => model.toLowerCase().includes(part))
128129 ) {
129130 return true;
@@ -302,6 +303,7 @@
302303 "meta-llama/llama-3-70b-instruct",
303304 "arcee-ai/caller-large",
304305 "nousresearch/hermes-3-llama-3.1-70b",
306+ "moonshotai/kimi-k2",
305307 ];
306308 for (const model of specificModels) {
307309 if (model.toLowerCase() === model) {
@@ -332,6 +334,36 @@
332334 return true;
333335 }
334336
337+ return false;
338+ },
339+ novita: (model) => {
340+ const lower = model.toLowerCase();
341+
342+ // Exact match models
343+ const exactMatches = [
344+ "deepseek/deepseek-r1-0528",
345+ "deepseek/deepseek-r1-turbo",
346+ "deepseek/deepseek-v3-0324",
347+ "deepseek/deepseek-v3-turbo",
348+ "meta-llama/llama-3.3-70b-instruct",
349+ "qwen/qwen-2.5-72b-instruct",
350+ "zai-org/glm-4.5",
351+ "moonshotai/kimi-k2-instruct",
352+ ];
353+
354+ if (exactMatches.includes(lower)) {
355+ return true;
356+ }
357+
358+ // Prefix match models
359+ const prefixMatches = ["qwen/qwen3", "openai/gpt-oss"];
360+
361+ for (const prefix of prefixMatches) {
362+ if (lower.startsWith(prefix)) {
363+ return true;
364+ }
365+ }
366+
335367 return false;
336368 },
337369 };
modified core/nextEdit/NextEditProvider.ts +140 −596
@@ -1,15 +1,6 @@
1-import * as path from "path";
21 import { v4 as uuidv4 } from "uuid";
32 import { ConfigHandler } from "../config/ConfigHandler.js";
4-import {
5- ChatMessage,
6- DiffLine,
7- IDE,
8- ILLM,
9- Position,
10- Range,
11- RangeInFile,
12-} from "../index.js";
3+import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js";
134 import OpenAI from "../llm/llms/OpenAI.js";
145 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
156
@@ -18,10 +9,7 @@
189 import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
1910 import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
2011 import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
21-import {
22- getAllSnippetsWithoutRace,
23- SnippetPayload,
24-} from "../autocomplete/snippets/index.js";
12+import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
2513 import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
2614 import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
2715 import { getAst } from "../autocomplete/util/ast.js";
@@ -29,38 +17,23 @@
2917 import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
3018 import { HelperVars } from "../autocomplete/util/HelperVars.js";
3119 import { AutocompleteInput } from "../autocomplete/util/types.js";
32-import { myersDiff } from "../diff/myers.js";
20+import { isSecurityConcern } from "../indexing/ignore.js";
3321 import { modelSupportsNextEdit } from "../llm/autodetect.js";
34-import { NEXT_EDIT_MODELS } from "../llm/constants.js";
3522 import { countTokens } from "../llm/countTokens.js";
3623 import { localPathOrUriToPath } from "../util/pathToUri.js";
37-import {
38- INSTINCT_SYSTEM_PROMPT,
39- MERCURY_SYSTEM_PROMPT,
40- MODEL_WINDOW_SIZES,
41- UNIQUE_TOKEN,
42-} from "./constants.js";
4324 import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
44-import {
45- calculateFinalCursorPosition,
46- DiffGroup,
47- groupDiffLines,
48-} from "./diff/diff.js";
4925 import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
5026 import { NextEditLoggingService } from "./NextEditLoggingService.js";
5127 import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
28+import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
29+import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
5230 import {
53- renderDefaultSystemPrompt,
54- renderDefaultUserPrompt,
55- renderPrompt,
56-} from "./templating/NextEditPromptEngine.js";
57-import {
31+ ModelSpecificContext,
5832 NextEditOutcome,
5933 Prompt,
6034 PromptMetadata,
6135 RecentlyEditedRange,
6236 } from "./types.js";
63-import { isWhitespaceOnlyDeletion } from "./utils.js";
6437
6538 const autocompleteCache = AutocompleteLruCache.get();
6639
@@ -91,6 +64,9 @@
9164 private previousCompletions: NextEditOutcome[] = [];
9265 // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
9366
67+ // Model-specific provider instance.
68+ private modelProvider: BaseNextEditProvider | null = null;
69+
9470 private constructor(
9571 private readonly configHandler: ConfigHandler,
9672 private readonly ide: IDE,
@@ -285,6 +261,9 @@
285261 usingFullFileDiff: boolean;
286262 },
287263 ): Promise<NextEditOutcome | undefined> {
264+ if (isSecurityConcern(input.filepath)) {
265+ return undefined;
266+ }
288267 try {
289268 this.previousRequest = input;
290269 const {
@@ -294,28 +273,23 @@
294273 } = await this._initializeCompletionRequest(input, token);
295274 if (!helper) return undefined;
296275
276+ // Create model-specific provider based on the model name.
277+ this.modelProvider = NextEditProviderFactory.createProvider(
278+ helper.modelName,
279+ );
280+
297281 const { editableRegionStartLine, editableRegionEndLine, prompts } =
298282 await this._generatePrompts(helper, opts);
299283
300- if (this.endpointType === "default") {
301- return await this._handleDefaultEndpointCompletion(
302- helper,
303- prompts,
304- abortToken,
305- startTime,
306- editableRegionEndLine,
307- );
308- } else {
309- return await this._handleFineTunedEndpointCompletion(
310- helper,
311- prompts,
312- abortToken,
313- startTime,
314- editableRegionStartLine,
315- editableRegionEndLine,
316- opts,
317- );
318- }
284+ return await this._handleCompletion(
285+ helper,
286+ prompts,
287+ abortToken,
288+ startTime,
289+ editableRegionStartLine,
290+ editableRegionEndLine,
291+ opts,
292+ );
319293 } catch (e: any) {
320294 this.onError(e);
321295 } finally {
@@ -331,7 +305,7 @@
331305 startTime: number;
332306 helper: HelperVars | undefined;
333307 }> {
334- // Create abort signal if not given.
308+ // Create abort signal if not given
335309 if (!token) {
336310 const controller = this.loggingService.createAbortController(
337311 input.completionId,
@@ -341,7 +315,7 @@
341315 const startTime = Date.now();
342316 const options = await this._getAutocompleteOptions();
343317
344- // Debounce.
318+ // Debounce
345319 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
346320 return { token, startTime, helper: undefined };
347321 }
@@ -351,9 +325,7 @@
351325 return { token, startTime, helper: undefined };
352326 }
353327
354- // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
355- // For other editors, this check should be done in their respective config reloaders.
356- // This is left for a final check.
328+ // Check model capabilities
357329 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
358330 console.error(`${llm.model} is not capable of next edit.`);
359331 return { token, startTime, helper: undefined };
@@ -383,6 +355,10 @@
383355 editableRegionEndLine: number;
384356 prompts: Prompt[];
385357 }> {
358+ if (!this.modelProvider) {
359+ throw new Error("Model provider not initialized");
360+ }
361+
386362 const [snippetPayload, workspaceDirs] = await Promise.all([
387363 getAllSnippetsWithoutRace({
388364 helper,
@@ -393,56 +369,118 @@
393369 this.ide.getWorkspaceDirs(),
394370 ]);
395371
396- const modelName = helper.modelName.includes(
397- NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
398- )
399- ? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
400- : helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
401- ? NEXT_EDIT_MODELS.MERCURY_CODER
402- : NEXT_EDIT_MODELS.INSTINCT;
403-
372+ // Calculate editable region based on model and options.
404373 const { editableRegionStartLine, editableRegionEndLine } =
405- opts?.usingFullFileDiff
406- ? this._calculateOptimalEditableRegion(helper, "tokenizer")
407- : {
408- editableRegionStartLine: Math.max(
409- helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
410- 0,
411- ),
412- editableRegionEndLine: Math.min(
413- helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
414- helper.fileLines.length - 1,
415- ),
416- };
417-
418- // const editableRegionStartLine = opts?.usingFullFileDiff
419- // ? 0
420- // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
421-
422- // const editableRegionEndLine = opts?.usingFullFileDiff
423- // ? helper.fileLines.length - 1
424- // : Math.min(
425- // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
426- // helper.fileLines.length - 1,
427- // );
428-
429- const prompts: Prompt[] = [];
430-
431- if (this.endpointType === "default") {
432- prompts.push(renderDefaultSystemPrompt());
433- prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
374+ this.modelProvider.calculateEditableRegion(
375+ helper,
376+ opts?.usingFullFileDiff ?? false,
377+ );
378+
379+ // Build context for model-specific prompt generation.
380+ const context: ModelSpecificContext = {
381+ helper,
382+ snippetPayload,
383+ editableRegionStartLine,
384+ editableRegionEndLine,
385+ diffContext: this.diffContext,
386+ autocompleteContext: this.autocompleteContext,
387+ historyDiff: createDiff({
388+ beforeContent:
389+ DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
390+ localPathOrUriToPath(helper.filepath),
391+ ) ?? "",
392+ afterContent: helper.fileContents,
393+ filePath: helper.filepath,
394+ diffType: DiffFormatType.Unified,
395+ contextLines: 3,
396+ }),
397+ };
398+
399+ const prompts = await this.modelProvider.generatePrompts(context);
400+
401+ this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
402+
403+ return { editableRegionStartLine, editableRegionEndLine, prompts };
404+ }
405+
406+ private async _handleCompletion(
407+ helper: HelperVars,
408+ prompts: Prompt[],
409+ token: AbortSignal,
410+ startTime: number,
411+ editableRegionStartLine: number,
412+ editableRegionEndLine: number,
413+ opts?: {
414+ withChain: boolean;
415+ usingFullFileDiff: boolean;
416+ },
417+ ): Promise<NextEditOutcome | undefined> {
418+ if (!this.modelProvider) {
419+ throw new Error("Model provider not initialized");
420+ }
421+
422+ const llm = await this._prepareLlm();
423+ if (!llm) return undefined;
424+
425+ // Inject unique token if needed (for Mercury models).
426+ if (this.modelProvider.shouldInjectUniqueToken()) {
427+ const uniqueToken = this.modelProvider.getUniqueToken();
428+ if (uniqueToken) {
429+ const lastPrompt = prompts[prompts.length - 1];
430+ if (lastPrompt && typeof lastPrompt.content === "string") {
431+ lastPrompt.content += uniqueToken;
432+ }
433+ }
434+ }
435+
436+ // Send prompts to LLM (using only user prompt for fine-tuned models).
437+ const msg: ChatMessage = await llm.chat([prompts[1]], token, {
438+ stream: false,
439+ });
440+
441+ if (typeof msg.content !== "string") {
442+ return undefined;
443+ }
444+
445+ // Extract completion using model-specific logic.
446+ const nextCompletion = this.modelProvider.extractCompletion(msg.content);
447+
448+ let outcome: NextEditOutcome | undefined;
449+
450+ // Handle based on diff type.
451+ if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
452+ outcome = await this.modelProvider.handlePartialFileDiff(
453+ helper,
454+ editableRegionStartLine,
455+ editableRegionEndLine,
456+ startTime,
457+ llm,
458+ nextCompletion,
459+ this.promptMetadata!,
460+ this.ide,
461+ );
434462 } else {
435- prompts.push(
436- ...(await this._generateFineTunedPrompts(
437- helper,
438- snippetPayload,
439- editableRegionStartLine,
440- editableRegionEndLine,
441- )),
463+ outcome = await this.modelProvider.handleFullFileDiff(
464+ helper,
465+ editableRegionStartLine,
466+ editableRegionEndLine,
467+ startTime,
468+ llm,
469+ nextCompletion,
470+ this.promptMetadata!,
471+ this.ide,
442472 );
443473 }
444474
445- return { editableRegionStartLine, editableRegionEndLine, prompts };
475+ if (outcome) {
476+ // Handle NextEditProvider-specific state
477+ this.previousCompletions.push(outcome);
478+
479+ // Mark as displayed for JetBrains
480+ await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
481+ }
482+
483+ return outcome;
446484 }
447485
448486 private _calculateOptimalEditableRegion(
@@ -536,500 +574,6 @@
536574 };
537575 }
538576
539- private async _generateFineTunedPrompts(
540- helper: HelperVars,
541- snippetPayload: SnippetPayload,
542- editableRegionStartLine: number,
543- editableRegionEndLine: number,
544- ): Promise<Prompt[]> {
545- const historyDiff = createDiff({
546- beforeContent:
547- DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
548- localPathOrUriToPath(helper.filepath),
549- ) ?? "",
550- afterContent: helper.fileContents,
551- filePath: helper.filepath,
552- diffType: DiffFormatType.Unified,
553- contextLines: 3,
554- });
555-
556- const modelName = helper.modelName;
557- let ctx: any;
558-
559- if (
560- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
561- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
562- ) {
563- ctx = {
564- recentlyViewedCodeSnippets:
565- snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
566- filepath: snip.filepath,
567- content: snip.content,
568- })) ?? [],
569- currentFileContent: helper.fileContents,
570- editableRegionStartLine,
571- editableRegionEndLine,
572- editDiffHistory: this.diffContext,
573- currentFilePath: helper.filepath,
574- };
575- } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
576- // Calculate the window around the cursor position (25 lines above and below).
577- const windowStart = Math.max(0, helper.pos.line - 25);
578- const windowEnd = Math.min(
579- helper.fileLines.length - 1,
580- helper.pos.line + 25,
581- );
582-
583- // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
584- // const actualEditableStart = Math.max(
585- // 0,
586- // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
587- // );
588- // const actualEditableEnd = Math.min(
589- // helper.fileLines.length - 1,
590- // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
591- // );
592-
593- // Ensure editable region boundaries are within the window.
594- const adjustedEditableStart = Math.max(
595- windowStart,
596- editableRegionStartLine,
597- );
598- const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
599- ctx = {
600- contextSnippets: this.autocompleteContext,
601- currentFileContent: helper.fileContents,
602- windowStart,
603- windowEnd,
604- editableRegionStartLine: adjustedEditableStart,
605- editableRegionEndLine: adjustedEditableEnd,
606- editDiffHistory: this.diffContext,
607- currentFilePath: helper.filepath,
608- languageShorthand: helper.lang.name,
609- };
610- } else {
611- ctx = {};
612- }
613-
614- const promptMetadata = await renderPrompt(helper, ctx);
615- this.promptMetadata = promptMetadata;
616-
617- const systemPrompt: Prompt = {
618- role: "system",
619- content:
620- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
621- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
622- ? MERCURY_SYSTEM_PROMPT
623- : INSTINCT_SYSTEM_PROMPT,
624- };
625-
626- return [systemPrompt, promptMetadata.prompt];
627- }
628-
629- private async _handleDefaultEndpointCompletion(
630- helper: HelperVars,
631- prompts: Prompt[],
632- token: AbortSignal,
633- startTime: number,
634- editableRegionEndLine: number,
635- ): Promise<NextEditOutcome | undefined> {
636- const llm = await this._prepareLlm();
637- if (!llm) return undefined;
638-
639- const msg: ChatMessage = await llm.chat(prompts, token);
640-
641- if (typeof msg.content === "string") {
642- const nextCompletion = JSON.parse(msg.content).newCode;
643- const finalCursorPos: Position = {
644- line: editableRegionEndLine,
645- character: 0,
646- };
647-
648- const outcomeNext = await this._createNextEditOutcome({
649- helper,
650- startTime,
651- llm,
652- promptContent: prompts.join("\n"),
653- completion: nextCompletion,
654- finalCursorPosition: finalCursorPos,
655- editableRegionStartLine: 0,
656- editableRegionEndLine: 0,
657- userEdits: "",
658- userExcerpts: "",
659- originalEditableRange: "",
660- diffLines: [],
661- });
662-
663- // Mark as displayed for JetBrains extension
664- await this._markDisplayedIfJetBrains(
665- helper.input.completionId,
666- outcomeNext,
667- );
668-
669- return outcomeNext;
670- }
671-
672- return undefined;
673- }
674-
675- private async _handleFineTunedEndpointCompletion(
676- helper: HelperVars,
677- prompts: Prompt[],
678- token: AbortSignal,
679- startTime: number,
680- editableRegionStartLine: number,
681- editableRegionEndLine: number,
682- opts?: {
683- withChain: boolean;
684- usingFullFileDiff: boolean;
685- },
686- ): Promise<NextEditOutcome | undefined> {
687- const llm = await this._prepareLlm();
688- if (!llm) return undefined;
689-
690- // Check for mercury models, and inject unique token for next edit.
691- // Capture the unique tokens in llm Inception.ts and apis Inception.ts
692- const modelName = helper.modelName;
693- if (
694- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
695- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
696- ) {
697- // Inject the unique token to the last prompt's content.
698- const lastPrompt = prompts[prompts.length - 1];
699- if (lastPrompt && typeof lastPrompt.content === "string") {
700- lastPrompt.content += UNIQUE_TOKEN;
701- }
702- }
703-
704- const msg: ChatMessage = await llm.chat([prompts[1]], token, {
705- stream: false,
706- });
707-
708- if (typeof msg.content !== "string") {
709- return undefined;
710- }
711-
712- // NOTE: Keep this in case there is a change in spec.
713- // const nextCompletion =
714- // msg.content
715- // .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
716- // .replace(/\n$/, "") ?? msg.content;
717- const nextCompletion = msg.content.slice(
718- msg.content.indexOf("\`\`\`\n") + "\'\'\'\n".length,
719- msg.content.lastIndexOf("\n\n\`\`\`"),
720- );
721-
722- if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
723- return await this._handlePartialFileDiff(
724- // we could use fillFileDiff
725- helper,
726- editableRegionStartLine,
727- editableRegionEndLine,
728- startTime,
729- llm,
730- nextCompletion,
731- );
732- } else {
733- return await this._handleFullFileDiff(
734- helper,
735- editableRegionStartLine,
736- editableRegionEndLine,
737- startTime,
738- llm,
739- nextCompletion,
740- );
741- }
742- }
743-
744- private async _handlePartialFileDiff(
745- helper: HelperVars,
746- editableRegionStartLine: number,
747- editableRegionEndLine: number,
748- startTime: number,
749- llm: ILLM,
750- nextCompletion: string,
751- ): Promise<NextEditOutcome | undefined> {
752- const oldEditRangeSlice = helper.fileContents
753- .split("\n")
754- .slice(editableRegionStartLine, editableRegionEndLine + 1)
755- .join("\n");
756-
757- const finalCursorPos = calculateFinalCursorPosition(
758- helper.pos,
759- editableRegionStartLine,
760- oldEditRangeSlice,
761- nextCompletion,
762- );
763-
764- const outcomeNext = await this._createNextEditOutcome({
765- helper,
766- startTime,
767- llm,
768- promptContent: this.promptMetadata!.prompt.content,
769- completion: nextCompletion,
770- finalCursorPosition: finalCursorPos,
771- editableRegionStartLine,
772- editableRegionEndLine,
773- userEdits: this.promptMetadata!.userEdits,
774- userExcerpts: this.promptMetadata!.userExcerpts,
775- originalEditableRange: oldEditRangeSlice,
776- diffLines: [],
777- });
778-
779- this.previousCompletions.push(outcomeNext);
780-
781- // Mark as displayed for JetBrains extension
782- await this._markDisplayedIfJetBrains(
783- helper.input.completionId,
784- outcomeNext,
785- );
786-
787- return outcomeNext;
788- }
789-
790- private async _handleFullFileDiff(
791- helper: HelperVars,
792- editableRegionStartLine: number,
793- editableRegionEndLine: number,
794- startTime: number,
795- llm: ILLM,
796- nextCompletion: string,
797- ): Promise<NextEditOutcome | undefined> {
798- const fileSlice = helper.fileLines
799- .slice(editableRegionStartLine, editableRegionEndLine + 1)
800- .join("\n");
801- const diffLines = myersDiff(fileSlice, nextCompletion);
802- const diffGroups = groupDiffLines(
803- diffLines,
804- editableRegionStartLine,
805- 5,
806- ).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
807- const currentLine = helper.pos.line;
808- const prefetchQueue = PrefetchQueue.getInstance();
809-
810- // Process diff groups and find the one containing the cursor
811- const cursorLocalDiffGroup = await this._processDiffGroups(
812- diffGroups,
813- currentLine,
814- helper,
815- startTime,
816- llm,
817- prefetchQueue,
818- );
819-
820- // Handle the diff group containing the cursor if found
821- if (cursorLocalDiffGroup) {
822- return await this._createOutcomeFromDiffGroup(
823- cursorLocalDiffGroup,
824- helper,
825- startTime,
826- llm,
827- helper.input.completionId,
828- true,
829- );
830- // } else if (diffGroups.length > 0) {
831- // // Fallback to first diff group if cursor's group not found
832- // return await this._createOutcomeFromDiffGroup(
833- // diffGroups[0],
834- // helper,
835- // startTime,
836- // llm,
837- // helper.input.completionId,
838- // false,
839- // );
840- }
841-
842- return undefined;
843- }
844-
845- private async _processDiffGroups(
846- diffGroups: DiffGroup[],
847- currentLine: number,
848- helper: HelperVars,
849- startTime: number,
850- llm: ILLM,
851- prefetchQueue: PrefetchQueue,
852- ): Promise<DiffGroup | undefined> {
853- let cursorGroup: DiffGroup | undefined;
854-
855- console.log("diffGroups:");
856- console.log(diffGroups);
857-
858- for (const group of diffGroups) {
859- if (currentLine >= group.startLine && currentLine <= group.endLine) {
860- cursorGroup = group;
861- } else {
862- // Add non-cursor groups to prefetch queue
863- await this._addDiffGroupToPrefetchQueue(
864- group,
865- helper,
866- startTime,
867- llm,
868- prefetchQueue,
869- );
870- }
871- }
872-
873- return cursorGroup;
874- }
875-
876- private async _addDiffGroupToPrefetchQueue(
877- group: DiffGroup,
878- helper: HelperVars,
879- startTime: number,
880- llm: ILLM,
881- prefetchQueue: PrefetchQueue,
882- ): Promise<void> {
883- const groupContent = group.lines
884- .filter((l) => l.type !== "old")
885- .map((l) => l.line)
886- .join("\n");
887-
888- // Create a range for this diff group
889- const rangeInFile: RangeInFile = {
890- filepath: helper.filepath,
891- range: {
892- start: { line: group.startLine, character: 0 },
893- end: {
894- line: group.endLine,
895- character: group.lines[group.lines.length - 1].line.length,
896- },
897- },
898- };
899-
900- const originalContent = group.lines
901- .filter((l) => l.type !== "new")
902- .map((l) => l.line)
903- .join("\n");
904-
905- // Build outcome for this diff group
906- const groupOutcome = await this._createNextEditOutcome({
907- helper,
908- startTime,
909- llm,
910- promptContent: this.promptMetadata!.prompt.content,
911- completion: groupContent,
912- finalCursorPosition: {
913- line: group.endLine,
914- character: group.lines[group.lines.length - 1].line.length,
915- },
916- editableRegionStartLine: group.startLine,
917- editableRegionEndLine: group.endLine,
918- userEdits: this.promptMetadata!.userEdits,
919- userExcerpts: this.promptMetadata!.userExcerpts,
920- originalEditableRange: originalContent,
921- cursorPosition: { line: group.startLine, character: 0 },
922- completionId: uuidv4(), // Generate a new ID for this prefetched item
923- diffLines: group.lines,
924- });
925-
926- // Add to prefetch queue
927- prefetchQueue.enqueueProcessed({
928- location: rangeInFile,
929- outcome: groupOutcome,
930- });
931- }
932-
933- private async _createOutcomeFromDiffGroup(
934- diffGroup: DiffGroup,
935- helper: HelperVars,
936- startTime: number,
937- llm: ILLM,
938- completionId: string,
939- isCurrentCursorGroup: boolean,
940- ): Promise<NextEditOutcome> {
941- const groupContent = diffGroup.lines
942- .filter((l) => l.type !== "old")
943- .map((line) => line.line)
944- .join("\n");
945-
946- const originalContent = diffGroup.lines
947- .filter((l) => l.type !== "new")
948- .map((l) => l.line)
949- .join("\n");
950-
951- // Use the actual cursor position if this is the group containing the cursor
952- // Otherwise use the start of the diff group
953- const cursorPos = isCurrentCursorGroup
954- ? helper.pos
955- : { line: diffGroup.startLine, character: 0 };
956-
957- const finalCursorPos = calculateFinalCursorPosition(
958- cursorPos,
959- diffGroup.startLine,
960- originalContent,
961- groupContent,
962- );
963-
964- const outcomeNext = await this._createNextEditOutcome({
965- helper,
966- startTime,
967- llm,
968- promptContent: this.promptMetadata!.prompt.content,
969- completion: groupContent,
970- finalCursorPosition: finalCursorPos,
971- editableRegionStartLine: diffGroup.startLine,
972- editableRegionEndLine: diffGroup.endLine,
973- userEdits: this.promptMetadata!.userEdits,
974- userExcerpts: this.promptMetadata!.userExcerpts,
975- originalEditableRange: originalContent,
976- cursorPosition: cursorPos,
977- completionId,
978- diffLines: diffGroup.lines,
979- });
980-
981- this.previousCompletions.push(outcomeNext);
982-
983- // Mark as displayed for JetBrains
984- await this._markDisplayedIfJetBrains(completionId, outcomeNext);
985-
986- return outcomeNext;
987- }
988-
989- private async _createNextEditOutcome(outcomeCtx: {
990- helper: HelperVars;
991- startTime: number;
992- llm: ILLM;
993- promptContent: string;
994- completion: string;
995- finalCursorPosition: Position;
996- editableRegionStartLine: number;
997- editableRegionEndLine: number;
998- userEdits: string;
999- userExcerpts: string;
1000- originalEditableRange: string;
1001- cursorPosition?: Position;
1002- completionId?: string;
1003- diffLines: DiffLine[];
1004- }): Promise<NextEditOutcome> {
1005- return {
1006- elapsed: Date.now() - outcomeCtx.startTime,
1007- modelProvider: outcomeCtx.llm.underlyingProviderName,
1008- modelName: outcomeCtx.llm.model + ":zetaDataset",
1009- completionOptions: null,
1010- completionId:
1011- outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
1012- gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
1013- uniqueId: await this.ide.getUniqueId(),
1014- timestamp: Date.now(),
1015- fileUri: outcomeCtx.helper.filepath,
1016- workspaceDirUri:
1017- outcomeCtx.helper.workspaceUris[0] ??
1018- path.dirname(outcomeCtx.helper.filepath),
1019- prompt: outcomeCtx.promptContent,
1020- userEdits: outcomeCtx.userEdits ?? "",
1021- userExcerpts: outcomeCtx.userExcerpts ?? "",
1022- originalEditableRange: outcomeCtx.originalEditableRange ?? "",
1023- completion: outcomeCtx.completion,
1024- cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
1025- finalCursorPosition: outcomeCtx.finalCursorPosition,
1026- editableRegionStartLine: outcomeCtx.editableRegionStartLine,
1027- editableRegionEndLine: outcomeCtx.editableRegionEndLine,
1028- diffLines: outcomeCtx.diffLines,
1029- ...outcomeCtx.helper.options,
1030- };
1031- }
1032-
1033577 private async _markDisplayedIfJetBrains(
1034578 completionId: string,
1035579 outcome: NextEditOutcome,
added core/nextEdit/NextEditProviderFactory.ts +16 −0
@@ -0,0 +1,16 @@
1+import { NEXT_EDIT_MODELS } from "../llm/constants.js";
2+import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
3+import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
4+import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
5+
6+export class NextEditProviderFactory {
7+ static createProvider(modelName: string): BaseNextEditProvider {
8+ if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
9+ return new MercuryCoderProvider();
10+ } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
11+ return new InstinctProvider();
12+ } else {
13+ throw new Error(`Unsupported model: ${modelName}`);
14+ }
15+ }
16+}
modified core/nextEdit/constants.ts +0 −4
@@ -12,10 +12,6 @@
1212 topMargin: 0,
1313 bottomMargin: 5,
1414 }, // mercury coder uses full file diff, so this should be unnecessary
15- "mercury-coder-nextedit": {
16- topMargin: 0,
17- bottomMargin: 5,
18- }, // mercury coder nextedit uses full file diff, so this should be unnecessary
1915 instinct: { topMargin: 1, bottomMargin: 5 },
2016 };
2117
modified core/nextEdit/context/autocompleteContextFetching.ts +5 −0
@@ -11,6 +11,7 @@
1111 } from "../../autocomplete/util/types";
1212 import { ConfigHandler } from "../../config/ConfigHandler";
1313 import { IDE, ILLM } from "../../index";
14+import { isSecurityConcern } from "../../indexing/ignore";
1415 import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
1516
1617 /**
@@ -61,6 +62,10 @@
6162 throw new Error("No config available");
6263 }
6364
65+ if (isSecurityConcern(input.filepath)) {
66+ throw new Error("File is a security concern, autocomplete disabled");
67+ }
68+
6469 // Use provided autocomplete model or fall back to configured autocomplete model
6570 let finalModel: ILLM;
6671 let modelNameForTemplating: string;
added core/nextEdit/providers/BaseNextEditProvider.ts +415 −0
@@ -0,0 +1,415 @@
1+import * as path from "path";
2+import { v4 as uuidv4 } from "uuid";
3+
4+import { HelperVars } from "../../autocomplete/util/HelperVars.js";
5+import { myersDiff } from "../../diff/myers.js";
6+import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js";
7+import { countTokens } from "../../llm/countTokens.js";
8+import {
9+ calculateFinalCursorPosition,
10+ DiffGroup,
11+ groupDiffLines,
12+} from "../diff/diff.js";
13+import { PrefetchQueue } from "../NextEditPrefetchQueue.js";
14+import {
15+ ModelSpecificContext,
16+ NextEditOutcome,
17+ Prompt,
18+ PromptMetadata,
19+} from "../types.js";
20+import { isWhitespaceOnlyDeletion } from "../utils.js";
21+
22+export abstract class BaseNextEditProvider {
23+ protected readonly modelName: string;
24+
25+ constructor(modelName: string) {
26+ this.modelName = modelName;
27+ }
28+
29+ // Leave methods as abstract when you must have the models implement their own versions.
30+ abstract getSystemPrompt(): string;
31+ abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>;
32+ abstract extractCompletion(message: string): string;
33+ abstract buildPromptContext(context: ModelSpecificContext): any;
34+ abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata;
35+ abstract getWindowSize(): { topMargin: number; bottomMargin: number };
36+ abstract calculateEditableRegion(
37+ helper: HelperVars,
38+ usingFullFileDiff: boolean,
39+ ): {
40+ editableRegionStartLine: number;
41+ editableRegionEndLine: number;
42+ };
43+
44+ // Methods that can be used as default fallback.
45+ public async handlePartialFileDiff(
46+ helper: HelperVars,
47+ editableRegionStartLine: number,
48+ editableRegionEndLine: number,
49+ startTime: number,
50+ llm: ILLM,
51+ nextCompletion: string,
52+ promptMetadata: PromptMetadata,
53+ ide: IDE,
54+ ): Promise<NextEditOutcome> {
55+ const oldEditRangeSlice = helper.fileContents
56+ .split("\n")
57+ .slice(editableRegionStartLine, editableRegionEndLine + 1)
58+ .join("\n");
59+
60+ const finalCursorPos = calculateFinalCursorPosition(
61+ helper.pos,
62+ editableRegionStartLine,
63+ oldEditRangeSlice,
64+ nextCompletion,
65+ );
66+
67+ const outcome = await this.createNextEditOutcome({
68+ helper,
69+ startTime,
70+ llm,
71+ promptContent: promptMetadata.prompt.content,
72+ completion: nextCompletion,
73+ finalCursorPosition: finalCursorPos,
74+ editableRegionStartLine,
75+ editableRegionEndLine,
76+ userEdits: promptMetadata.userEdits,
77+ userExcerpts: promptMetadata.userExcerpts,
78+ originalEditableRange: oldEditRangeSlice,
79+ diffLines: [],
80+ ide,
81+ });
82+
83+ return outcome;
84+ }
85+
86+ public async handleFullFileDiff(
87+ helper: HelperVars,
88+ editableRegionStartLine: number,
89+ editableRegionEndLine: number,
90+ startTime: number,
91+ llm: ILLM,
92+ nextCompletion: string,
93+ promptMetadata: PromptMetadata,
94+ ide: IDE,
95+ ): Promise<NextEditOutcome | undefined> {
96+ const fileSlice = helper.fileLines
97+ .slice(editableRegionStartLine, editableRegionEndLine + 1)
98+ .join("\n");
99+
100+ const diffLines = myersDiff(fileSlice, nextCompletion);
101+ const diffGroups = groupDiffLines(
102+ diffLines,
103+ editableRegionStartLine,
104+ 5,
105+ ).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
106+ const currentLine = helper.pos.line;
107+ const prefetchQueue = PrefetchQueue.getInstance();
108+
109+ const cursorLocalDiffGroup = await this.processDiffGroups(
110+ diffGroups,
111+ currentLine,
112+ helper,
113+ startTime,
114+ llm,
115+ prefetchQueue,
116+ promptMetadata,
117+ ide,
118+ );
119+
120+ if (cursorLocalDiffGroup) {
121+ return await this.createOutcomeFromDiffGroup(
122+ cursorLocalDiffGroup,
123+ helper,
124+ startTime,
125+ llm,
126+ helper.input.completionId,
127+ true,
128+ promptMetadata,
129+ ide,
130+ );
131+ }
132+
133+ return undefined;
134+ }
135+
136+ /**
137+ * Process diff groups and find the one containing the cursor.
138+ */
139+ private async processDiffGroups(
140+ diffGroups: DiffGroup[],
141+ currentLine: number,
142+ helper: HelperVars,
143+ startTime: number,
144+ llm: ILLM,
145+ prefetchQueue: PrefetchQueue,
146+ promptMetadata: PromptMetadata,
147+ ide: IDE,
148+ ): Promise<DiffGroup | undefined> {
149+ let cursorGroup: DiffGroup | undefined;
150+
151+ for (const group of diffGroups) {
152+ if (currentLine >= group.startLine && currentLine <= group.endLine) {
153+ cursorGroup = group;
154+ } else {
155+ await this.addDiffGroupToPrefetchQueue(
156+ group,
157+ helper,
158+ startTime,
159+ llm,
160+ prefetchQueue,
161+ promptMetadata,
162+ ide,
163+ );
164+ }
165+ }
166+
167+ return cursorGroup;
168+ }
169+
170+ private async addDiffGroupToPrefetchQueue(
171+ group: DiffGroup,
172+ helper: HelperVars,
173+ startTime: number,
174+ llm: ILLM,
175+ prefetchQueue: PrefetchQueue,
176+ promptMetadata: PromptMetadata,
177+ ide: IDE,
178+ ): Promise<void> {
179+ // Extract lines that are not old.
180+ const groupContent = group.lines
181+ .filter((l) => l.type !== "old")
182+ .map((l) => l.line)
183+ .join("\n");
184+
185+ const rangeInFile: RangeInFile = {
186+ filepath: helper.filepath,
187+ range: {
188+ start: { line: group.startLine, character: 0 },
189+ end: {
190+ line: group.endLine,
191+ character: group.lines[group.lines.length - 1].line.length,
192+ },
193+ },
194+ };
195+
196+ // Extract lines that are not new.
197+ const originalContent = group.lines
198+ .filter((l) => l.type !== "new")
199+ .map((l) => l.line)
200+ .join("\n");
201+
202+ const groupOutcome = await this.createNextEditOutcome({
203+ helper,
204+ startTime,
205+ llm,
206+ promptContent: promptMetadata.prompt.content,
207+ completion: groupContent,
208+ finalCursorPosition: {
209+ line: group.endLine,
210+ character: group.lines[group.lines.length - 1].line.length,
211+ },
212+ editableRegionStartLine: group.startLine,
213+ editableRegionEndLine: group.endLine,
214+ userEdits: promptMetadata.userEdits,
215+ userExcerpts: promptMetadata.userExcerpts,
216+ originalEditableRange: originalContent,
217+ cursorPosition: { line: group.startLine, character: 0 },
218+ completionId: uuidv4(), // Generate a new ID for this prefetched item.
219+ diffLines: group.lines,
220+ ide,
221+ });
222+
223+ prefetchQueue.enqueueProcessed({
224+ location: rangeInFile,
225+ outcome: groupOutcome,
226+ });
227+ }
228+
229+ private async createOutcomeFromDiffGroup(
230+ diffGroup: DiffGroup,
231+ helper: HelperVars,
232+ startTime: number,
233+ llm: ILLM,
234+ completionId: string,
235+ isCurrentCursorGroup: boolean,
236+ promptMetadata: PromptMetadata,
237+ ide: IDE,
238+ ): Promise<NextEditOutcome> {
239+ const groupContent = diffGroup.lines
240+ .filter((l) => l.type !== "old")
241+ .map((l) => l.line)
242+ .join("\n");
243+
244+ const originalContent = diffGroup.lines
245+ .filter((l) => l.type !== "new")
246+ .map((l) => l.line)
247+ .join("\n");
248+
249+ const cursorPos = isCurrentCursorGroup
250+ ? helper.pos
251+ : { line: diffGroup.startLine, character: 0 };
252+
253+ const finalCursorPos = calculateFinalCursorPosition(
254+ cursorPos,
255+ diffGroup.startLine,
256+ originalContent,
257+ groupContent,
258+ );
259+
260+ const outcomeNext = await this.createNextEditOutcome({
261+ helper,
262+ startTime,
263+ llm,
264+ promptContent: promptMetadata.prompt.content,
265+ completion: groupContent,
266+ finalCursorPosition: finalCursorPos,
267+ editableRegionStartLine: diffGroup.startLine,
268+ editableRegionEndLine: diffGroup.endLine,
269+ userEdits: promptMetadata.userEdits,
270+ userExcerpts: promptMetadata.userExcerpts,
271+ originalEditableRange: originalContent,
272+ cursorPosition: cursorPos,
273+ completionId,
274+ diffLines: diffGroup.lines,
275+ ide,
276+ });
277+
278+ return outcomeNext;
279+ }
280+
281+ protected async createNextEditOutcome(outcomeCtx: {
282+ helper: HelperVars;
283+ startTime: number;
284+ llm: ILLM;
285+ promptContent: string;
286+ completion: string;
287+ finalCursorPosition: Position;
288+ editableRegionStartLine: number;
289+ editableRegionEndLine: number;
290+ userEdits: string;
291+ userExcerpts: string;
292+ originalEditableRange: string;
293+ cursorPosition?: Position;
294+ completionId?: string;
295+ diffLines: DiffLine[];
296+ ide: IDE;
297+ }): Promise<NextEditOutcome> {
298+ return {
299+ elapsed: Date.now() - outcomeCtx.startTime,
300+ modelProvider: outcomeCtx.llm.underlyingProviderName,
301+ modelName: outcomeCtx.llm.model + ":zetaDataset",
302+ completionOptions: null,
303+ completionId:
304+ outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
305+ gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
306+ uniqueId: await outcomeCtx.ide.getUniqueId(),
307+ timestamp: Date.now(),
308+ fileUri: outcomeCtx.helper.filepath,
309+ workspaceDirUri:
310+ outcomeCtx.helper.workspaceUris[0] ??
311+ path.dirname(outcomeCtx.helper.filepath),
312+ prompt: outcomeCtx.promptContent,
313+ userEdits: outcomeCtx.userEdits ?? "",
314+ userExcerpts: outcomeCtx.userExcerpts ?? "",
315+ originalEditableRange: outcomeCtx.originalEditableRange ?? "",
316+ completion: outcomeCtx.completion,
317+ cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
318+ finalCursorPosition: outcomeCtx.finalCursorPosition,
319+ editableRegionStartLine: outcomeCtx.editableRegionStartLine,
320+ editableRegionEndLine: outcomeCtx.editableRegionEndLine,
321+ diffLines: outcomeCtx.diffLines,
322+ ...outcomeCtx.helper.options,
323+ };
324+ }
325+
326+ // Shared utility for calculating editable regions.
327+ protected calculateOptimalEditableRegion(
328+ helper: HelperVars,
329+ maxTokens: number = 512,
330+ heuristic: "fourChars" | "tokenizer" = "tokenizer",
331+ ): {
332+ editableRegionStartLine: number;
333+ editableRegionEndLine: number;
334+ } {
335+ const cursorLine = helper.pos.line;
336+ const fileLines = helper.fileLines;
337+
338+ let editableRegionStartLine = cursorLine;
339+ let editableRegionEndLine = cursorLine;
340+
341+ let currentContent = fileLines[cursorLine];
342+ let totalTokens =
343+ heuristic === "tokenizer"
344+ ? countTokens(currentContent, helper.modelName)
345+ : Math.ceil(currentContent.length / 4);
346+
347+ let addingAbove = true;
348+
349+ while (totalTokens < maxTokens) {
350+ let addedLine = false;
351+
352+ if (addingAbove) {
353+ if (editableRegionStartLine > 0) {
354+ editableRegionStartLine--;
355+ const lineContent = fileLines[editableRegionStartLine];
356+ const lineTokens =
357+ heuristic === "tokenizer"
358+ ? countTokens(lineContent, helper.modelName)
359+ : Math.ceil(lineContent.length / 4);
360+
361+ totalTokens += lineTokens;
362+ addedLine = true;
363+ }
364+ } else {
365+ if (editableRegionEndLine < fileLines.length - 1) {
366+ editableRegionEndLine++;
367+ const lineContent = fileLines[editableRegionEndLine];
368+ const lineTokens =
369+ heuristic === "tokenizer"
370+ ? countTokens(lineContent, helper.modelName)
371+ : Math.ceil(lineContent.length / 4);
372+
373+ totalTokens += lineTokens;
374+ addedLine = true;
375+ }
376+ }
377+
378+ if (!addedLine) {
379+ if (
380+ editableRegionStartLine === 0 &&
381+ editableRegionEndLine === fileLines.length - 1
382+ ) {
383+ break;
384+ }
385+ addingAbove = !addingAbove;
386+ continue;
387+ }
388+
389+ if (totalTokens > maxTokens) {
390+ if (addingAbove) {
391+ editableRegionStartLine++;
392+ } else {
393+ editableRegionEndLine--;
394+ }
395+ break;
396+ }
397+
398+ addingAbove = !addingAbove;
399+ }
400+
401+ return {
402+ editableRegionStartLine,
403+ editableRegionEndLine,
404+ };
405+ }
406+
407+ // Optional methods with defaults.
408+ shouldInjectUniqueToken(): boolean {
409+ return false;
410+ }
411+
412+ getUniqueToken(): string | null {
413+ return null;
414+ }
415+}
added core/nextEdit/providers/InstinctNextEditProvider.ts +155 −0
@@ -0,0 +1,155 @@
1+import { HelperVars } from "../../autocomplete/util/HelperVars.js";
2+import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
3+import { INSTINCT_SYSTEM_PROMPT } from "../constants.js";
4+import {
5+ contextSnippetsBlock,
6+ currentFileContentBlock,
7+ editHistoryBlock,
8+} from "../templating/instinct.js";
9+import {
10+ NEXT_EDIT_MODEL_TEMPLATES,
11+ PromptTemplateRenderer,
12+} from "../templating/NextEditPromptEngine.js";
13+import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
14+import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
15+
16+export class InstinctProvider extends BaseNextEditProvider {
17+ private templateRenderer: PromptTemplateRenderer;
18+
19+ constructor() {
20+ super(NEXT_EDIT_MODELS.INSTINCT);
21+
22+ const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT];
23+ this.templateRenderer = new PromptTemplateRenderer(template.template);
24+ }
25+
26+ getSystemPrompt(): string {
27+ return INSTINCT_SYSTEM_PROMPT;
28+ }
29+
30+ getWindowSize() {
31+ return { topMargin: 1, bottomMargin: 5 };
32+ }
33+
34+ shouldInjectUniqueToken(): boolean {
35+ return false; // Instinct doesn't use unique tokens.
36+ }
37+
38+ extractCompletion(message: string): string {
39+ return message; // Instinct returns the completion directly.
40+ }
41+
42+ buildPromptContext(context: ModelSpecificContext): any {
43+ // Calculate the window around the cursor position (25 lines above and below).
44+ const windowStart = Math.max(0, context.helper.pos.line - 25);
45+ const windowEnd = Math.min(
46+ context.helper.fileLines.length - 1,
47+ context.helper.pos.line + 25,
48+ );
49+
50+ // Ensure editable region boundaries are within the window.
51+ const adjustedEditableStart = Math.max(
52+ windowStart,
53+ context.editableRegionStartLine,
54+ );
55+ const adjustedEditableEnd = Math.min(
56+ windowEnd,
57+ context.editableRegionEndLine,
58+ );
59+
60+ return {
61+ contextSnippets: context.autocompleteContext,
62+ currentFileContent: context.helper.fileContents,
63+ windowStart,
64+ windowEnd,
65+ editableRegionStartLine: adjustedEditableStart,
66+ editableRegionEndLine: adjustedEditableEnd,
67+ editDiffHistory: context.diffContext,
68+ currentFilePath: context.helper.filepath,
69+ languageShorthand: context.helper.lang.name,
70+ };
71+ }
72+
73+ async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
74+ const promptCtx = this.buildPromptContext(context);
75+
76+ const templateVars = {
77+ contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
78+ currentFileContent: currentFileContentBlock(
79+ promptCtx.currentFileContent,
80+ promptCtx.windowStart,
81+ promptCtx.windowEnd,
82+ promptCtx.editableRegionStartLine,
83+ promptCtx.editableRegionEndLine,
84+ context.helper.pos,
85+ ),
86+ editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
87+ currentFilePath: promptCtx.currentFilePath,
88+ languageShorthand: promptCtx.languageShorthand,
89+ };
90+
91+ const userPromptContent = this.templateRenderer.render(templateVars);
92+
93+ return [
94+ {
95+ role: "system",
96+ content: this.getSystemPrompt(),
97+ },
98+ {
99+ role: "user",
100+ content: userPromptContent,
101+ },
102+ ];
103+ }
104+
105+ buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
106+ const promptCtx = this.buildPromptContext(context);
107+
108+ const templateVars = {
109+ contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
110+ currentFileContent: currentFileContentBlock(
111+ promptCtx.currentFileContent,
112+ promptCtx.windowStart,
113+ promptCtx.windowEnd,
114+ promptCtx.editableRegionStartLine,
115+ promptCtx.editableRegionEndLine,
116+ context.helper.pos,
117+ ),
118+ editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
119+ currentFilePath: promptCtx.currentFilePath,
120+ languageShorthand: promptCtx.languageShorthand,
121+ };
122+
123+ const userPromptContent = this.templateRenderer.render(templateVars);
124+
125+ return {
126+ prompt: {
127+ role: "user",
128+ content: userPromptContent,
129+ },
130+ userEdits: promptCtx.editDiffHistory.join("\n"),
131+ userExcerpts: templateVars.currentFileContent,
132+ };
133+ }
134+
135+ calculateEditableRegion(
136+ helper: HelperVars,
137+ usingFullFileDiff: boolean,
138+ ): {
139+ editableRegionStartLine: number;
140+ editableRegionEndLine: number;
141+ } {
142+ if (usingFullFileDiff) {
143+ return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
144+ } else {
145+ const { topMargin, bottomMargin } = this.getWindowSize();
146+ return {
147+ editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
148+ editableRegionEndLine: Math.min(
149+ helper.pos.line + bottomMargin,
150+ helper.fileLines.length - 1,
151+ ),
152+ };
153+ }
154+ }
155+}
added core/nextEdit/providers/MercuryCoderNextEditProvider.ts +145 −0
@@ -0,0 +1,145 @@
1+import { HelperVars } from "../../autocomplete/util/HelperVars.js";
2+import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
3+import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js";
4+import {
5+ currentFileContentBlock,
6+ editHistoryBlock,
7+ recentlyViewedCodeSnippetsBlock,
8+} from "../templating/mercuryCoderNextEdit.js";
9+import {
10+ NEXT_EDIT_MODEL_TEMPLATES,
11+ PromptTemplateRenderer,
12+} from "../templating/NextEditPromptEngine.js";
13+import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
14+import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
15+
16+export class MercuryCoderProvider extends BaseNextEditProvider {
17+ private templateRenderer: PromptTemplateRenderer;
18+
19+ constructor() {
20+ super(NEXT_EDIT_MODELS.MERCURY_CODER);
21+
22+ const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER];
23+ this.templateRenderer = new PromptTemplateRenderer(template.template);
24+ }
25+
26+ getSystemPrompt(): string {
27+ return MERCURY_SYSTEM_PROMPT;
28+ }
29+
30+ getWindowSize() {
31+ return { topMargin: 0, bottomMargin: 5 };
32+ }
33+
34+ shouldInjectUniqueToken(): boolean {
35+ return true;
36+ }
37+
38+ getUniqueToken(): string {
39+ return UNIQUE_TOKEN;
40+ }
41+
42+ extractCompletion(message: string): string {
43+ // Extract the code between the markdown code blocks.
44+ return message.slice(
45+ message.indexOf("```\n") + "```\n".length,
46+ message.lastIndexOf("\n\n```"),
47+ );
48+ }
49+
50+ buildPromptContext(context: ModelSpecificContext): any {
51+ return {
52+ recentlyViewedCodeSnippets:
53+ context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
54+ filepath: snip.filepath,
55+ content: snip.content,
56+ })) ?? [],
57+ currentFileContent: context.helper.fileContents,
58+ editableRegionStartLine: context.editableRegionStartLine,
59+ editableRegionEndLine: context.editableRegionEndLine,
60+ editDiffHistory: context.diffContext,
61+ currentFilePath: context.helper.filepath,
62+ };
63+ }
64+
65+ async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
66+ const promptCtx = this.buildPromptContext(context);
67+
68+ const templateVars = {
69+ recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
70+ promptCtx.recentlyViewedCodeSnippets,
71+ ),
72+ currentFileContent: currentFileContentBlock(
73+ promptCtx.currentFileContent,
74+ promptCtx.editableRegionStartLine,
75+ promptCtx.editableRegionEndLine,
76+ context.helper.pos,
77+ ),
78+ editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
79+ currentFilePath: promptCtx.currentFilePath,
80+ };
81+
82+ const userPromptContent = this.templateRenderer.render(templateVars);
83+
84+ return [
85+ {
86+ role: "system",
87+ content: this.getSystemPrompt(),
88+ },
89+ {
90+ role: "user",
91+ content: userPromptContent,
92+ },
93+ ];
94+ }
95+
96+ buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
97+ const promptCtx = this.buildPromptContext(context);
98+
99+ const templateVars = {
100+ recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
101+ promptCtx.recentlyViewedCodeSnippets,
102+ ),
103+ currentFileContent: currentFileContentBlock(
104+ promptCtx.currentFileContent,
105+ promptCtx.editableRegionStartLine,
106+ promptCtx.editableRegionEndLine,
107+ context.helper.pos,
108+ ),
109+ editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
110+ currentFilePath: promptCtx.currentFilePath,
111+ };
112+
113+ const userPromptContent = this.templateRenderer.render(templateVars);
114+
115+ return {
116+ prompt: {
117+ role: "user",
118+ content: userPromptContent,
119+ },
120+ userEdits: promptCtx.editDiffHistory.join("\n"),
121+ userExcerpts: templateVars.currentFileContent,
122+ };
123+ }
124+
125+ calculateEditableRegion(
126+ helper: HelperVars,
127+ usingFullFileDiff: boolean,
128+ ): {
129+ editableRegionStartLine: number;
130+ editableRegionEndLine: number;
131+ } {
132+ if (usingFullFileDiff) {
133+ return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
134+ } else {
135+ const { topMargin, bottomMargin } = this.getWindowSize();
136+ return {
137+ editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
138+ editableRegionEndLine: Math.min(
139+ helper.pos.line + bottomMargin,
140+ helper.fileLines.length - 1,
141+ ),
142+ };
143+ }
144+ }
145+}
modified core/nextEdit/templating/NextEditPromptEngine.ts +21 −259
@@ -1,7 +1,4 @@
11 import Handlebars from "handlebars";
2-import { Position } from "../..";
3-import { SnippetPayload } from "../../autocomplete/snippets";
4-import { HelperVars } from "../../autocomplete/util/HelperVars";
52 import { NEXT_EDIT_MODELS } from "../../llm/constants";
63 import {
74 INSTINCT_USER_PROMPT_PREFIX,
@@ -12,274 +9,39 @@
129 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1310 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
1411 } from "../constants";
15-import {
16- InstinctTemplateVars,
17- MercuryTemplateVars,
18- NextEditTemplate,
19- PromptMetadata,
20- SystemPrompt,
21- TemplateVars,
22- UserPrompt,
23-} from "../types";
24-import {
25- contextSnippetsBlock,
26- currentFileContentBlock as instinctCurrentFileContentBlock,
27- editHistoryBlock as instinctEditHistoryBlock,
28-} from "./instinct";
29-import {
30- currentFileContentBlock,
31- editHistoryBlock,
32- recentlyViewedCodeSnippetsBlock,
33-} from "./mercuryCoderNextEdit";
34-import {
35- insertCursorToken,
36- insertEditableRegionTokensWithStaticRange,
37-} from "./utils";
38-
39-type TemplateRenderer = (vars: TemplateVars) => string;
40-
41-const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
12+import { NextEditTemplate, TemplateVars } from "../types";
13+
14+// Keep the template registry
15+export const NEXT_EDIT_MODEL_TEMPLATES: Record<
16+ NEXT_EDIT_MODELS,
17+ NextEditTemplate
18+> = {
4219 "mercury-coder": {
4320 template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
4421 },
45- "mercury-coder-nextedit": {
46- template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
47- },
4822 instinct: {
4923 template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
5024 },
5125 };
5226
53-function templateRendererOfModel(
54- modelName: NEXT_EDIT_MODELS,
55-): TemplateRenderer {
56- let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
57- if (!template) {
58- throw new Error(`Model ${modelName} is not supported for next edit.`);
59- }
60-
61- const compiledTemplate = Handlebars.compile(template.template);
62-
63- return (vars: TemplateVars): string => {
64- return compiledTemplate(vars);
65- };
66-}
67-
68-export async function renderPrompt(
69- helper: HelperVars,
70- ctx: any,
71-): Promise<PromptMetadata> {
72- let modelName = helper.modelName as NEXT_EDIT_MODELS;
27+// Export a utility for providers to use
28+export class PromptTemplateRenderer {
29+ private compiledTemplate: HandlebarsTemplateDelegate;
7330
74- // Validate that the modelName is actually a supported model.
75- if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
76- // Check if modelName includes any known model name as substring.
77- const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
78- modelName.includes(key),
79- );
80-
81- if (matchingModel) {
82- modelName = matchingModel as NEXT_EDIT_MODELS;
83- } else {
84- throw new Error(
85- `${helper.modelName} is not yet supported for next edit.`,
86- );
87- }
31+ constructor(template: string) {
32+ this.compiledTemplate = Handlebars.compile(template);
8833 }
8934
90- const renderer = templateRendererOfModel(modelName);
91- let userEdits = "";
92- let editedCodeWithTokens = "";
93- let tv: TemplateVars;
94-
95- switch (modelName) {
96- case NEXT_EDIT_MODELS.MERCURY_CODER: {
97- userEdits = ctx.editDiffHistory;
98-
99- // editedCodeWithTokens = insertTokens(
100- // helper.fileContents.split("\n"),
101- // helper.pos,
102- // MERCURY_CURSOR,
103- // );
104-
105- const mercuryCtx: MercuryTemplateVars = {
106- recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
107- ctx.recentlyViewedCodeSnippets,
108- ),
109- currentFileContent: currentFileContentBlock(
110- ctx.currentFileContent,
111- ctx.editableRegionStartLine,
112- ctx.editableRegionEndLine,
113- helper.pos,
114- ),
115- editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
116- currentFilePath: ctx.currentFilePath,
117- };
118-
119- tv = mercuryCtx;
120-
121- editedCodeWithTokens = mercuryCtx.currentFileContent;
122-
123- break;
124- }
125- case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: {
126- userEdits = ctx.editDiffHistory;
127-
128- // editedCodeWithTokens = insertTokens(
129- // helper.fileContents.split("\n"),
130- // helper.pos,
131- // MERCURY_CURSOR,
132- // );
133-
134- const mercuryCtx: MercuryTemplateVars = {
135- recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
136- ctx.recentlyViewedCodeSnippets,
137- ),
138- currentFileContent: currentFileContentBlock(
139- ctx.currentFileContent,
140- ctx.editableRegionStartLine,
141- ctx.editableRegionEndLine,
142- helper.pos,
143- ),
144- editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
145- currentFilePath: ctx.currentFilePath,
146- };
147-
148- tv = mercuryCtx;
149-
150- editedCodeWithTokens = mercuryCtx.currentFileContent;
151-
152- break;
153- }
154- case NEXT_EDIT_MODELS.INSTINCT: {
155- userEdits = ctx.editDiffHistory;
156-
157- // editedCodeWithTokens = insertTokens(
158- // helper.fileContents.split("\n"),
159- // helper.pos,
160- // INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
161- // );
162-
163- const instinctCtx: InstinctTemplateVars = {
164- contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
165- currentFileContent: instinctCurrentFileContentBlock(
166- ctx.currentFileContent,
167- ctx.windowStart,
168- ctx.windowEnd,
169- ctx.editableRegionStartLine,
170- ctx.editableRegionEndLine,
171- helper.pos,
172- ),
173- editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
174- currentFilePath: ctx.currentFilePath,
175- languageShorthand: ctx.languageShorthand,
176- };
177-
178- tv = instinctCtx;
179-
180- editedCodeWithTokens = instinctCtx.currentFileContent;
181-
182- break;
183- }
184- default:
185- tv = {};
186- break;
35+ render(vars: TemplateVars): string {
36+ return this.compiledTemplate(vars);
18737 }
188-
189- return {
190- prompt: {
191- role: "user",
192- content: renderer(tv),
193- },
194- userEdits,
195- userExcerpts: editedCodeWithTokens,
196- };
197-}
198-
199-export function renderDefaultSystemPrompt(): SystemPrompt {
200- return {
201- role: "system",
202- content: [
203- /* Identity forming */
204- "You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
205- "You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
206- "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.",
207- /* Action crash course */
208- "An action is a change in code state that preserves the well-formedness of the code.",
209- "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.",
210- /* Input description */
211- // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
212- // "language is the language the code is written in.",
213- // "originalCode is the code state before the junior has taken some edit action.",
214- // "editedCode is the code state after the junior has taken some edit action.",
215- // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
216- // "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.",
217- '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; }.',
218- "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
219- "recentlyEditedRange is the code that the junior has recently edited.",
220- "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
221- "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.",
222- "The junior might want to add new code, delete existing code, or replace different parts of code.",
223- "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
224- /* Output description */
225- 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
226- /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
227- /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
228- "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.",
229- // "actionType is the type of action the junior has taken.",
230- "newCode is what the full code looks like after applying your nextEditContent.",
231- // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
232- "Given the above definition of an action, you should prioritize fixing the following:",
233- "- Patterns and repetition in code.",
234- "- Static errors that the compiler of the language may return.",
235- "- The junior's code style.",
236- "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
237- "If the junior has added some code, there's a good chance that the next edit will also be additions.",
238- "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.",
239- "Careful of language intricacies.",
240- // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
241- "Do not reply in markdown.",
242- "Do not hallucinate.",
243- ].join(" "),
244- };
24538 }
24639
247-export function renderDefaultUserPrompt(
248- // originalCode: string,
249- // editedCode: string,
250- snippets: SnippetPayload,
251- helper: HelperVars,
252-): UserPrompt {
253- const userEdit = {
254- language: helper.lang,
255- rootPathSnippets: snippets.rootPathSnippets,
256- importDefinitionSnippets: snippets.importDefinitionSnippets,
257- ideSnippets: snippets.ideSnippets,
258- recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
259- diffSnippets: snippets.diffSnippets,
260- clipboardSnippets: snippets.clipboardSnippets,
261- recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
262- };
263-
264- return {
265- role: "user",
266- 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?`,
267- };
268-}
269-
270-function insertTokens(
271- lines: string[],
272- cursorPos: Position,
273- cursorToken: string,
274- editableRegionStart?: number,
275- editableRegionEnd?: number,
276-) {
277- const a = insertCursorToken(lines, cursorPos, cursorToken);
278- const b = insertEditableRegionTokensWithStaticRange(
279- a,
280- cursorPos,
281- editableRegionStart,
282- editableRegionEnd,
283- );
284- return b.join("\n");
40+// Keep for backward compatibility or remove if not needed
41+export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string {
42+ const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
43+ if (!template) {
44+ throw new Error(`Model ${modelName} is not supported for next edit.`);
45+ }
46+ return template.template;
28547 }
modified core/nextEdit/templating/NextEditPromptEngine.vitest.ts +81 −212
@@ -1,243 +1,112 @@
1-import { beforeEach, describe, expect, it } from "vitest";
2-import { Position } from "../..";
3-import { SnippetPayload } from "../../autocomplete/snippets";
4-import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
5-import { HelperVars } from "../../autocomplete/util/HelperVars";
1+import { describe, expect, it } from "vitest";
62 import { NEXT_EDIT_MODELS } from "../../llm/constants";
73 import {
8- INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
94 INSTINCT_USER_PROMPT_PREFIX,
105 MERCURY_CURRENT_FILE_CONTENT_CLOSE,
116 MERCURY_CURRENT_FILE_CONTENT_OPEN,
12- MERCURY_CURSOR,
137 MERCURY_EDIT_DIFF_HISTORY_CLOSE,
148 MERCURY_EDIT_DIFF_HISTORY_OPEN,
159 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
1610 MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
17- MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
18- MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
1911 } from "../constants";
2012 import {
21- renderDefaultSystemPrompt,
22- renderDefaultUserPrompt,
23- renderPrompt,
13+ NEXT_EDIT_MODEL_TEMPLATES,
14+ PromptTemplateRenderer,
15+ getTemplateForModel,
2416 } from "./NextEditPromptEngine";
2517
2618 describe("NextEditPromptEngine", () => {
27- describe("renderPrompt", () => {
28- let mercuryHelper: HelperVars;
29- let instinctHelper: HelperVars;
30- let testHelper: HelperVars;
31- let unsupportedHelper: HelperVars;
32- let ctx: any;
33-
34- beforeEach(() => {
35- mercuryHelper = {
36- modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS,
37- fileContents: "function test() {\n const a = 1;\n return a;\n}",
38- pos: { line: 1, character: 12 } as Position,
39- lang: { name: "typescript" },
40- } as HelperVars;
41- instinctHelper = {
42- modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
43- fileContents: "function test() {\n const a = 1;\n return a;\n}",
44- pos: { line: 1, character: 12 } as Position,
45- lang: { name: "typescript" },
46- } as HelperVars;
47- unsupportedHelper = {
48- modelName: "mistral/codestral" as NEXT_EDIT_MODELS,
49- fileContents: "function test() {\n const a = 1;\n return a;\n}",
50- pos: { line: 1, character: 12 } as Position,
51- lang: { name: "typescript" },
52- } as HelperVars;
53-
54- ctx = {
55- recentlyViewedCodeSnippets: [
56- { filepath: "/path/to/file1.ts", content: "const b = 2;" },
57- ],
58- currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
59- editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
60- editableRegionStartLine: 0,
61- editableRegionEndLine: 3,
62- userEdits: "Added constant a",
63- languageShorthand: "ts",
64- userExcerpts: "const a = 1;",
65- };
19+ describe("NEXT_EDIT_MODEL_TEMPLATES", () => {
20+ it("should contain templates for all supported models", () => {
21+ expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
22+ NEXT_EDIT_MODELS.MERCURY_CODER,
23+ );
24+ expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
25+ NEXT_EDIT_MODELS.INSTINCT,
26+ );
6627 });
6728
68- it("should render mercury-coder prompt correctly", async () => {
69- const result = await renderPrompt(mercuryHelper, ctx);
70-
71- expect(result).toHaveProperty("prompt");
72- expect(result.prompt.role).toBe("user");
73-
74- const content = result.prompt.content;
75- expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
76- expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
77- expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN);
78- expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE);
79- expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
80- expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
81- expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
82- expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
83-
84- expect(result.userEdits).toBe(ctx.editDiffHistory);
85- expect(result.userExcerpts).toContain(MERCURY_CURSOR);
29+ it("mercury-coder template should contain expected tokens", () => {
30+ const template =
31+ NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
32+
33+ expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
34+ expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
35+ expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
36+ expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
37+ expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
38+ expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
39+ expect(template).toContain("{{{recentlyViewedCodeSnippets}}}");
40+ expect(template).toContain("{{{currentFileContent}}}");
41+ expect(template).toContain("{{{editDiffHistory}}}");
8642 });
8743
88- it("should render instinct prompt correctly", async () => {
89- // Create proper instinct context structure matching NextEditProvider.ts
90- const instinctCtx = {
91- contextSnippets:
92- "+++++ /path/to/context.ts\nconst contextVar = 'test';",
93- currentFileContent: instinctHelper.fileContents,
94- windowStart: 0, // Math.max(0, helper.pos.line - 25)
95- windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
96- editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
97- editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
98- editDiffHistory: [
99- "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
100- ], // unified diff
101- currentFilePath: "/path/to/file.ts",
102- languageShorthand: "ts",
103- };
104-
105- const result = await renderPrompt(instinctHelper, instinctCtx);
106- console.log(result);
107-
108- expect(result).toHaveProperty("prompt");
109- expect(result.prompt.role).toBe("user");
110- expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
111- expect(result.prompt.content).toContain("### Context:");
112- expect(result.prompt.content).toContain("### User Edits:");
113- expect(result.prompt.content).toContain("### User Excerpt:");
114-
115- expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
116- expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
44+ it("instinct template should contain expected tokens", () => {
45+ const template =
46+ NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template;
47+
48+ expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX);
49+ expect(template).toContain("### Context:");
50+ expect(template).toContain("### User Edits:");
51+ expect(template).toContain("### User Excerpt:");
52+ expect(template).toContain("{{{contextSnippets}}}");
53+ expect(template).toContain("{{{currentFileContent}}}");
54+ expect(template).toContain("{{{editDiffHistory}}}");
55+ expect(template).toContain("{{{currentFilePath}}}");
11756 });
57+ });
11858
119- it("should throw error for unsupported model name", async () => {
120- await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
121- "mistral/codestral is not yet supported for next edit.",
122- );
59+ describe("PromptTemplateRenderer", () => {
60+ it("should render a template with provided variables", () => {
61+ const template = "Hello {{{name}}}, you have {{{count}}} messages";
62+ const renderer = new PromptTemplateRenderer(template);
63+
64+ const result = renderer.render({
65+ name: "Alice",
66+ count: "5",
67+ });
68+
69+ expect(result).toBe("Hello Alice, you have 5 messages");
12370 });
124- });
12571
126- describe("renderDefaultSystemPrompt", () => {
127- it("should return a system prompt with expected role and content", () => {
128- const result = renderDefaultSystemPrompt();
72+ it("should handle missing variables gracefully", () => {
73+ const template = "Hello {{{name}}}";
74+ const renderer = new PromptTemplateRenderer(template);
12975
130- expect(result.role).toBe("system");
131- expect(result.content).toContain("You are an expert polyglot developer");
132- expect(result.content).toContain("Do not hallucinate.");
76+ const result = renderer.render({});
77+
78+ expect(result).toBe("Hello ");
13379 });
134- });
13580
136- describe("renderDefaultUserPrompt", () => {
137- it("should render a user prompt with the correct structure", () => {
138- const snippets: SnippetPayload = {
139- rootPathSnippets: [
140- {
141- type: AutocompleteSnippetType.Code,
142- filepath: "",
143- content: "root path",
144- },
145- ],
146- importDefinitionSnippets: [
147- {
148- type: AutocompleteSnippetType.Code,
149- filepath: "",
150- content: "import def",
151- },
152- ],
153- ideSnippets: [
154- {
155- type: AutocompleteSnippetType.Code,
156- filepath: "",
157- content: "ide snippets",
158- },
159- ],
160- recentlyEditedRangeSnippets: [
161- {
162- type: AutocompleteSnippetType.Code,
163- filepath: "",
164- content: "recent edits",
165- },
166- ],
167- diffSnippets: [
168- {
169- type: AutocompleteSnippetType.Diff,
170- content: "diff snippets",
171- },
172- ],
173- clipboardSnippets: [
174- {
175- type: AutocompleteSnippetType.Clipboard,
176- content: "clipboard",
177- copiedAt: new Date().toISOString(),
178- },
179- ],
180- recentlyVisitedRangesSnippets: [
181- {
182- type: AutocompleteSnippetType.Code,
183- filepath: "",
184- content: "visited ranges",
185- },
186- ],
187- recentlyOpenedFileSnippets: [
188- {
189- type: AutocompleteSnippetType.Code,
190- filepath: "",
191- content: "recently opened files",
192- },
193- ],
194- staticSnippet: [
195- {
196- type: AutocompleteSnippetType.Static,
197- filepath: "",
198- content: "static content",
199- },
200- ],
201- };
202-
203- const helper: HelperVars = {
204- lang: { name: "typescript" },
205- } as HelperVars;
206-
207- const result = renderDefaultUserPrompt(snippets, helper);
208-
209- expect(result.role).toBe("user");
210- expect(result.content).toContain("Your junior made the following edit:");
211- expect(result.content).toContain("typescript");
212- expect(result.content).toContain("root path");
81+ it("should render complex templates correctly", () => {
82+ const template =
83+ NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
84+ const renderer = new PromptTemplateRenderer(template);
85+
86+ const result = renderer.render({
87+ recentlyViewedCodeSnippets: "snippet1",
88+ currentFileContent: "file content",
89+ editDiffHistory: "diff history",
90+ });
91+
92+ expect(result).toContain("snippet1");
93+ expect(result).toContain("file content");
94+ expect(result).toContain("diff history");
21395 });
21496 });
21597
216- describe("insertTokens", () => {
217- it("should correctly insert cursor and editable region tokens", () => {
218- const mercuryHelper = {
219- modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
220- fileContents: "function test() {\n const a = 1;\n return a;\n}",
221- pos: { line: 1, character: 12 } as Position,
222- lang: { name: "typescript" },
223- } as HelperVars;
224-
225- const ctx = {
226- recentlyViewedCodeSnippets: [
227- { filepath: "/path/to/file1.ts", content: "const b = 2;" },
228- ],
229- currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
230- editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
231- editableRegionStartLine: 0,
232- editableRegionEndLine: 3,
233- userEdits: "Added constant a",
234- languageShorthand: "ts",
235- userExcerpts: "const a = 1;",
236- };
237-
238- return renderPrompt(mercuryHelper, ctx).then((result) => {
239- expect(result.userExcerpts).toContain(MERCURY_CURSOR);
240- });
98+ describe("getTemplateForModel", () => {
99+ it("should return the correct template for a supported model", () => {
100+ const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER);
101+ expect(template).toBe(
102+ NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template,
103+ );
104+ });
105+
106+ it("should throw an error for an unsupported model", () => {
107+ expect(() =>
108+ getTemplateForModel("unsupported" as NEXT_EDIT_MODELS),
109+ ).toThrow("Model unsupported is not supported for next edit.");
241110 });
242111 });
243112 });
modified core/nextEdit/types.ts +35 −0
@@ -5,7 +5,9 @@
55 RangeInFile,
66 TabAutocompleteOptions,
77 } from "../";
8+import { SnippetPayload } from "../autocomplete/snippets";
89 import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
10+import { HelperVars } from "../autocomplete/util/HelperVars";
911
1012 export type RecentlyEditedRange = RangeInFile & {
1113 timestamp: number;
@@ -104,3 +106,36 @@
104106 editDiffHistory: string; // could be a singe large unified diff
105107 currentFilePath: string;
106108 }
109+
110+/**
111+ * Context object containing all necessary information for model-specific operations.
112+ */
113+export interface ModelSpecificContext {
114+ helper: HelperVars;
115+ snippetPayload: SnippetPayload;
116+ editableRegionStartLine: number;
117+ editableRegionEndLine: number;
118+ diffContext: string[];
119+ autocompleteContext: string;
120+ historyDiff?: string;
121+ workspaceDirs?: string[];
122+}
123+
124+/**
125+ * Configuration for editable region calculation.
126+ */
127+export interface EditableRegionConfig {
128+ usingFullFileDiff?: boolean;
129+ maxTokens?: number;
130+ topMargin?: number;
131+ bottomMargin?: number;
132+}
133+
134+/**
135+ * Configuration for prompt generation.
136+ */
137+export interface PromptConfig {
138+ includeHistory?: boolean;
139+ includeRecentEdits?: boolean;
140+ maxContextSnippets?: number;
141+}
modified core/nextEdit/utils.ts +9 −0
@@ -1,4 +1,5 @@
11 import { DiffLine } from "..";
2+import { NEXT_EDIT_MODELS } from "../llm/constants";
23
34 export function isNextEditTest(): boolean {
45 const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
@@ -21,3 +22,11 @@
2122 (diff.line.trim() === "" || /^\s+$/.test(diff.line)),
2223 );
2324 }
25+
26+export function convertNextEditModelNameToEnum(
27+ modelName: string,
28+): NEXT_EDIT_MODELS | undefined {
29+ const nextEditModels = Object.values(NEXT_EDIT_MODELS);
30+
31+ return nextEditModels.find((model) => modelName.includes(model));
32+}
modified core/nextEdit/utils.vitest.ts +38 −1
@@ -1,6 +1,11 @@
11 import { describe, expect, test, vi } from "vitest";
22 import { DiffLine } from "..";
3-import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
3+import { NEXT_EDIT_MODELS } from "../llm/constants";
4+import {
5+ convertNextEditModelNameToEnum,
6+ isNextEditTest,
7+ isWhitespaceOnlyDeletion,
8+} from "./utils";
49
510 describe("isNextEditTest", () => {
611 test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
@@ -57,3 +62,35 @@
5762 expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
5863 });
5964 });
65+
66+describe("convertNextEditModelNameToEnum", () => {
67+ test("returns correct enum for exact matches", () => {
68+ Object.values(NEXT_EDIT_MODELS).forEach((model) => {
69+ expect(convertNextEditModelNameToEnum(model)).toBe(model);
70+ });
71+ });
72+
73+ test("returns correct enum when model name is contained in a longer string", () => {
74+ expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe(
75+ NEXT_EDIT_MODELS.MERCURY_CODER,
76+ );
77+ expect(convertNextEditModelNameToEnum("blah/instinct")).toBe(
78+ NEXT_EDIT_MODELS.INSTINCT,
79+ );
80+ });
81+
82+ test("returns undefined for non-matching model names", () => {
83+ expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined();
84+ expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined();
85+ expect(convertNextEditModelNameToEnum("")).toBeUndefined();
86+ });
87+
88+ test("returns first match when multiple models could match", () => {
89+ const modelName = "model-that-contains-multiple-matches";
90+ const result = convertNextEditModelNameToEnum(modelName);
91+
92+ if (result !== undefined) {
93+ expect(Object.values(NEXT_EDIT_MODELS)).toContain(result);
94+ }
95+ });
96+});
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 +3 −2
@@ -36,6 +36,8 @@
3636 "@types/tar": "^6.1.13",
3737 "@types/uuid": "^9.0.7",
3838 "@types/win-ca": "^3.5.4",
39+ "@typescript-eslint/eslint-plugin": "^8.40.0",
40+ "@typescript-eslint/parser": "^8.40.0",
3941 "cross-env": "^7.0.3",
4042 "esbuild": "0.17.19",
4143 "eslint": "^8",
@@ -66,7 +68,6 @@
6668 "@sentry/esbuild-plugin": "^4.0.2",
6769 "@sentry/node": "^9.43.0",
6870 "@sentry/vite-plugin": "^4.0.2",
69- "@typescript-eslint/eslint-plugin": "^7.8.0",
7071 "@xenova/transformers": "2.14.0",
7172 "adf-to-md": "^1.1.0",
7273 "async-mutex": "^0.5.0",
@@ -85,7 +86,7 @@
8586 "http-proxy-agent": "^7.0.1",
8687 "https-proxy-agent": "^7.0.3",
8788 "iconv-lite": "^0.6.3",
88- "ignore": "^5.3.1",
89+ "ignore": "^7.0.5",
8990 "is-localhost-ip": "^2.0.0",
9091 "jinja-js": "0.1.8",
9192 "js-tiktoken": "^1.0.8",
modified core/tools/definitions/readCurrentlyOpenFile.ts +1 −1
@@ -13,7 +13,7 @@
1313 function: {
1414 name: BuiltInToolNames.ReadCurrentlyOpenFile,
1515 description:
16- "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this",
16+ "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.",
1717 parameters: {
1818 type: "object",
1919 properties: {},
modified core/tools/implementations/lsTool.ts +3 −0
@@ -1,3 +1,5 @@
1+import ignore from "ignore";
2+
13 import { ToolImpl } from ".";
24 import { walkDir } from "../../indexing/walkDir";
35 import { resolveRelativePathInDir } from "../../util/ideUtils";
@@ -27,6 +29,7 @@
2729 returnRelativeUrisPaths: true,
2830 include: "both",
2931 recursive: args?.recursive ?? false,
32+ overrideDefaultIgnores: ignore(), // Show all directories including dist/, build/, etc.
3033 });
3134
3235 const lines = entries.slice(0, MAX_LS_TOOL_LINES);
modified core/tools/implementations/readCurrentlyOpenFile.ts +3 −1
@@ -1,12 +1,14 @@
11 import { getUriDescription } from "../../util/uri";
22
33 import { ToolImpl } from ".";
4+import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
45 import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
56
6-export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
7+export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => {
78 const result = await extras.ide.getCurrentFile();
89
910 if (result) {
11+ throwIfFileIsSecurityConcern(result.path);
1012 await throwIfFileExceedsHalfOfContext(
1113 result.path,
1214 result.contents,
modified core/tools/implementations/readFile.ts +2 −0
@@ -2,11 +2,13 @@
22 import { getUriPathBasename } from "../../util/uri";
33
44 import { ToolImpl } from ".";
5+import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
56 import { getStringArg } from "../parseArgs";
67 import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
78
89 export const readFileImpl: ToolImpl = async (args, extras) => {
910 const filepath = getStringArg(args, "filepath");
11+ throwIfFileIsSecurityConcern(filepath);
1012
1113 const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
1214 if (!firstUriMatch) {
modified docs/customization/models.mdx +4 −4
@@ -18,11 +18,11 @@
1818
1919 | Model role | Best open models | Best closed models | Notes |
2020 |:------------|:------------------|:-------------------|:--------|
21-| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models |
22-| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
23-| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models |
21+| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Qwen2.5-Coder (32B), Devstral (27B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), GPT-4, [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro), DeepSeek models | Closed models are slightly better than open models |
22+| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B), DeepSeek Chat | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
23+| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder, Mercury Coder Small, DeepSeek Coder | Closed models are slightly better than open models |
2424 | Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role |
25-| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role |
25+| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, text-embedding-3-large, text-embedding-004 | Open embeddings models are emerging but closed models still perform better |
2626 | Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role |
2727 | Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models |
2828
modified docs/customize/model-providers/top-level/azure.mdx +1 −1
@@ -92,7 +92,7 @@
9292
9393 ## How to Configure Azure AI Foundry Embeddings Models
9494
95-We recommend configuring **text-embedding-3-large** as your embeddings model.
95+For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
9696
9797 <Tabs>
9898 <Tab title="YAML">
modified docs/customize/model-providers/top-level/deepseek.mdx +1 −1
@@ -41,7 +41,7 @@
4141
4242 ## How to Set Up DeepSeek Autocomplete Models
4343
44-We recommend configuring **DeepSeek Coder** as your autocomplete model.
44+For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models).
4545
4646 <Tabs>
4747 <Tab title="YAML">
modified docs/customize/model-providers/top-level/gemini.mdx +1 −1
@@ -48,7 +48,7 @@
4848
4949 ## How to Configure Gemini Embeddings Models
5050
51-We recommend configuring **text-embedding-004** as your embeddings model.
51+For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
5252
5353 <Tabs>
5454 <Tab title="YAML">
modified docs/customize/model-providers/top-level/ollama.mdx +2 −2
@@ -65,7 +65,7 @@
6565
6666 ## How to Set Up Ollama Embeddings Models
6767
68-We recommend configuring **Nomic Embed Text** as your embeddings model.
68+For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
6969
7070 <Tabs>
7171 <Tab title="YAML">
@@ -123,7 +123,7 @@
123123 ]
124124 }
125125 ```
126- </Tab>
126+ </Tab>
127127 </Tabs>
128128
129129 ## How to Configure Model Capabilities in Ollama
modified docs/docs.json +8 −0
@@ -364,6 +364,10 @@
364364 "source": "/hub/blocks",
365365 "destination": "/hub/blocks/intro"
366366 },
367+ {
368+ "source": "/hub/agents/intro",
369+ "destination": "/hub/assistants/intro"
370+ },
367371 {
368372 "source": "/customize",
369373 "destination": "/customization/overview"
@@ -1099,6 +1103,10 @@
10991103 {
11001104 "source": "/customize/model-providers",
11011105 "destination": "/customize/model-providers/overview"
1106+ },
1107+ {
1108+ "source": "/features/edit/next-edit",
1109+ "destination": "/features/autocomplete/next-edit"
11021110 }
11031111 ]
11041112 }
modified docs/features/agent/model-setup.mdx +1 −16
@@ -27,22 +27,7 @@
2727 - **Better reliability** - Models that struggle with native tools often perform better with system message tools
2828 - **Seamless switching** - Change between providers without modifying your workflow
2929
30-### What Models Are Recommended for Agent Mode
31-
32-For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
33-
34-**Premium Models:**
35-
36-- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
37-- **GPT-4** models (OpenAI) - Excellent native tool support
38-- **DeepSeek** models - Strong performance with competitive pricing
39-
40-**Local Models:**
41-While more limited in capabilities, these models can work with system message tools:
42-
43-- Qwen2.5-Coder 32B - Best local option for Agent mode
44-- Devstral 27B - Good for code-specific tasks
45-- Smaller models (7B-13B) - May struggle with complex tool interactions
30+For recommended Agent models, please refer to our [Model Recommendations page](/customization/models).
4631
4732 ### How to Configure Agent Mode
4833
modified docs/features/autocomplete/model-setup.mdx +2 −40
@@ -10,49 +10,11 @@
1010 For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models).
1111 </Info>
1212
13-## Recommended Models for Autocomplete in Continue
14-
15-### Hosted (Best Performance)
16-
17-For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
18-
19-This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
20-
21-**Codestral Quick Setup:**
22-
23-1. Get your API key from [Mistral AI](https://console.mistral.ai)
24-2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
25-3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
26-4. Click `Reload config` in the assistant selector in the Continue IDE extension
27-
28-### Hosted (Best Speed/Quality Tradeoff)
29-
30-For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception.
31-
32-This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
33-
34-**Mercury Coder Small Quick Setup:**
35-
36-1. Get your API key from [Inception](https://platform.inceptionlabs.ai/)
37-2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
38-3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
39-4. Click `Reload config` in the assistant selector in the Continue IDE extension
40-
41-### Local (Offline / Privacy First)
42-
43-For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
44-
45-This model provides good suggestions while keeping your code completely private.
46-
47-**Quick Setup:**
48-
49-1. Install [Ollama](https://ollama.ai/)
50-2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
51-3. Click `Reload config` in the assistant selector in the Continue IDE extension
13+For model recommendations, please refer to our [Model Recommendations page](/customization/models).
5214
5315 ## Next Edit Model
5416
55-For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/edit/next-edit) models:
17+For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models:
5618
5719 **Supported Next Edit model:**
5820
modified docs/features/chat/model-setup.mdx +1 −10
@@ -7,16 +7,7 @@
77 For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models).
88 </Info>
99
10-## What Models Are Recommended for Chat?
11-
12-Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
13-
14-Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
15-
16-1. Get your API key from [Anthropic](https://console.anthropic.com/)
17-2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
18-3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
19-4. Click `Reload config` in the assistant selector in the Continue IDE extension
10+For model recommendations, please refer to our [Model Recommendations page](/customization/models).
2011
2112 ### What Other Hosted Models Are Available?
2213
modified docs/features/edit/how-it-works.mdx +1 −1
@@ -14,7 +14,7 @@
1414 If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes.
1515
1616 <Info>
17-**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/edit/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
17+**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
1818 </Info>
1919
2020 If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs).
modified docs/features/edit/model-setup.mdx +1 −4
@@ -16,10 +16,7 @@
1616
1717 We also recommend setting up an Apply model for the best Edit experience.
1818
19-**Recommended Apply models:**
20-
21-- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
22-- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
19+For recommended Apply models, please refer to our [Model Recommendations page](/customization/models).
2320
2421 ## How to Determine Model Compatibility
2522
modified docs/guides/ollama-guide.mdx +115 −38
@@ -14,7 +14,7 @@
1414
1515 ## How to Install Ollama - Step-by-Step
1616
17-### Step 1: How to Install Ollama
17+### Step 1: Install Ollama
1818
1919 Choose the installation method for your operating system:
2020
@@ -29,7 +29,7 @@
2929 # Download from ollama.ai
3030 ```
3131
32-### Step 2: How to Start Ollama
32+### Step 2: Start Ollama Service
3333
3434 After installation, start the Ollama service:
3535
@@ -40,12 +40,17 @@
4040 # Verify it's running
4141 curl http://localhost:11434
4242 # Should return "Ollama is running"
43+
44+# Check Ollama version
45+ollama --version
4346 ```
4447
45-### Step 3: How to Download Models
48+### Step 3: Download Models
4649
4750 <Warning>
48-**Important**: Always use `ollama pull` instead of `ollama run` to download models. The `run` command starts an interactive session which isn't needed for Continue.
51+ **Important**: Always use `ollama pull` instead of `ollama run` to download
52+ models. The `run` command starts an interactive session which isn't needed for
53+ Continue.
4954 </Warning>
5055
5156 Download models using the exact tag specified:
@@ -62,12 +67,15 @@
6267 ```
6368
6469 **Common Model Tags:**
70+
6571 - `:latest` - Default version (used if no tag specified)
6672 - `:32b`, `:7b`, `:1.5b` - Parameter count versions
6773 - `:instruct`, `:base` - Model variants
6874
6975 <Note>
70-If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be a different size.
76+ If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it
77+ with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be
78+ a different size.
7179 </Note>
7280
7381 ## How to Configure Ollama with Continue
@@ -76,10 +84,9 @@
7684
7785 ### Method 1: Using Hub Model Blocks in Local config.yaml
7886
79-The easiest way is to use pre-configured model blocks from the Continue Hub in your local configuration:
87+The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
8088
81-```yaml
82-# ~/.continue/assistants/My Local Assistant.yaml
89+```yaml title="~/.continue/assistants/My Local Assistant.yaml"
8390 name: My Local Assistant
8491 version: 0.0.1
8592 schema: v1
@@ -90,20 +97,20 @@
9097 ```
9198
9299 <Warning>
93-**Important**: Hub blocks only provide configuration - you still need to pull the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue to use `model: deepseek-r1:32b`, but the actual model must be installed:
94-```bash
95-# Check what the hub block expects (view on hub.continue.dev)
96-# Then pull that exact model tag locally
97-ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block
98-```
99-If the model isn't installed, Ollama will return: `404 model "deepseek-r1:32b" not found, try pulling it first`
100+ **Important**: Hub blocks only provide configuration - you still need to pull
101+ the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue
102+ to use `model: deepseek-r1:32b`, but the actual model must be installed:
103+ ```bash # Check what the hub block expects (view on hub.continue.dev) # Then
104+ pull that exact model tag locally ollama pull deepseek-r1:32b # Required for
105+ ollama/deepseek-r1-32b hub block ``` If the model isn't installed, Ollama will
106+ return: `404 model "deepseek-r1:32b" not found, try pulling it first`
100107 </Warning>
101108
102109 ### Method 2: Using Autodetect
103110
104111 Continue can automatically detect available Ollama models. You can configure this in your YAML:
105112
106-```yaml
113+```yaml title="~/.continue/config.yaml"
107114 models:
108115 - name: Autodetect
109116 provider: ollama
@@ -112,6 +119,8 @@
112119 - chat
113120 - edit
114121 - apply
122+ - rerank
123+ - autocomplete
115124 ```
116125
117126 Or use it through the GUI:
@@ -122,7 +131,12 @@
122131 4. Select your desired model from the detected list
123132
124133 <Note>
125-The Autodetect feature scans your local Ollama installation and lists all available models. When set to `AUTODETECT`, Continue will dynamically populate the model list based on what's installed locally via `ollama list`. This is useful for quickly switching between models without manual configuration.
134+ The Autodetect feature scans your local Ollama installation and lists all
135+ available models. When set to `AUTODETECT`, Continue will dynamically populate
136+ the model list based on what's installed locally via `ollama list`. This is
137+ useful for quickly switching between models without manual configuration. For
138+ any roles not covered by the detected models, you may need to manually
139+ configure them.
126140 </Note>
127141
128142 You can update `apiBase` with the IP address of a remote machine serving Ollama.
@@ -135,12 +149,12 @@
135149 models:
136150 - name: DeepSeek R1 32B
137151 provider: ollama
138- model: deepseek-r1:32b # Must match exactly what `ollama list` shows
152+ model: deepseek-r1:32b # Must match exactly what `ollama list` shows
139153 apiBase: http://localhost:11434
140154 roles:
141155 - chat
142156 - edit
143- capabilities: # Add if not auto-detected
157+ capabilities: # Add if not auto-detected
144158 - tool_use
145159 - name: Qwen2.5-Coder 1.5B
146160 provider: ollama
@@ -161,14 +175,16 @@
161175 provider: ollama
162176 model: deepseek-r1:latest
163177 capabilities:
164- - tool_use # Add this to enable tools
178+ - tool_use # Add this to enable tools
165179 ```
166180
167181 <Warning>
168-**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not supported" or "does not support tools" even with capabilities configured. This is a known limitation where the model's actual tool support differs from its advertised capabilities.
182+ **Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not
183+ supported" or "does not support tools" even with capabilities configured. This
184+ is a known limitation where the model's actual tool support differs from its
185+ advertised capabilities.
169186 </Warning>
170187
171-
172188 #### If Agent Mode Shows "Not Supported"
173189
174190 1. First, add `capabilities: [tool_use]` to your model config
@@ -181,29 +197,70 @@
181197
182198 For optimal performance, consider these advanced configuration options:
183199
184-- Memory optimization: Adjust `num_ctx` for context window size
185-- GPU acceleration: Use `num_gpu` to control GPU layers
186-- Custom model parameters: Temperature, top_p, top_k settings
187-- Performance tuning: Batch size and threading options
200+```yaml
201+models:
202+ - name: Optimized DeepSeek
203+ provider: ollama
204+ model: deepseek-r1:32b
205+ contextLength: 8192 # Adjust context window (default varies by model)
206+ completionOptions:
207+ temperature: 0.7 # Controls randomness (0.0-1.0)
208+ top_p: 0.9 # Nucleus sampling threshold
209+ top_k: 40 # Top-k sampling
210+ num_predict: 2048 # Max tokens to generate
211+ # Ollama-specific options (set via environment or modelfile)
212+ # num_gpu: 35 # Number of GPU layers to offload
213+ # num_thread: 8 # CPU threads to use
214+```
215+
216+For GPU acceleration and memory tuning, create an Ollama Modelfile:
217+
218+```
219+# Create custom model with optimizations
220+FROM deepseek-r1:32b
221+PARAMETER num_gpu 35
222+PARAMETER num_thread 8
223+PARAMETER num_ctx 4096
224+```
188225
189226 ## What Are the Best Practices for Ollama
190227
191228 ### How to Choose the Right Model
192229
193-Choose models based on your specific needs:
230+Choose models based on your specific needs (see [recommended models](/customization/models#recommended-models) for more options):
231+
232+1. **Code Generation**:
233+
234+ - `qwen2.5-coder:7b` - Excellent for code completion
235+ - `codellama:13b` - Strong general coding support
236+ - `deepseek-coder:6.7b` - Fast and efficient
237+
238+2. **Chat & Reasoning**:
239+
240+ - `llama3.1:8b` - Latest Llama with tool support
241+ - `mistral:7b` - Fast and versatile
242+ - `deepseek-r1:32b` - Advanced reasoning capabilities
194243
195-1. **Code Generation**: Use CodeLlama or Mistral
196-2. **Chat**: Llama2 or Mistral
197-3. **Specialized Tasks**: Domain-specific models
244+3. **Autocomplete**:
245+
246+ - `qwen2.5-coder:1.5b` - Lightweight and fast
247+ - `starcoder2:3b` - Optimized for code completion
248+
249+4. **Memory Requirements**:
250+ - 1.5B-3B models: ~4GB RAM
251+ - 7B models: ~8GB RAM
252+ - 13B models: ~16GB RAM
253+ - 32B models: ~32GB RAM
198254
199255 ### How to Optimize Performance
200256
201257 To get the best performance from Ollama:
202258
203-- Monitor system resources
204-- Adjust context window size
205-- Use appropriate model sizes
206-- Enable GPU acceleration when available
259+- Monitor system resources with `ollama ps` to see memory usage
260+- Adjust context window size based on available RAM
261+- Use appropriate model sizes for your hardware
262+- Enable GPU acceleration when available (NVIDIA CUDA or AMD ROCm)
263+- Use `ollama logs` to debug performance issues
207264
208265 ## How to Troubleshoot Ollama Issues
209266
@@ -214,7 +271,8 @@
214271 This error occurs when the model isn't installed locally:
215272
216273 **Problem**: Using a hub block or config that references a model not yet pulled
217-**Solution**:
274+**Solution**:
275+
218276 ```bash
219277 # Check what models you have
220278 ollama list
@@ -227,6 +285,7 @@
227285
228286 **Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b`
229287 **Solution**: Always pull with the exact tag:
288+
230289 ```bash
231290 # Wrong - pulls :latest
232291 ollama pull deepseek-r1
@@ -239,6 +298,7 @@
239298
240299 **Problem**: Model doesn't support tools/function calling
241300 **Solutions**:
301+
242302 1. Add `capabilities: [tool_use]` to your model config
243303 2. If still not working, the model may not actually support tools
244304 3. Switch to a model with confirmed tool support (Llama 3.1, Mistral)
@@ -247,6 +307,7 @@
247307
248308 **Problem**: Unclear how to use hub models locally
249309 **Solution**: Create a local assistant file:
310+
250311 ```yaml
251312 # ~/.continue/assistants/Local.yaml
252313 name: Local Assistant
@@ -269,13 +330,29 @@
269330 - Model too large: Check available memory with `ollama ps`
270331 - GPU issues: Verify CUDA/ROCm installation for GPU acceleration
271332 - Slow generation: Adjust `num_gpu` layers in model configuration
333+- Check system diagnostics: `ollama ps` for active models and memory usage
272334
273335 ## What Are Example Workflows with Ollama
274336
275337 ### How to Use Ollama for Code Generation
276338
277-```
278-# Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass
339+```python
340+# Example: Generate a FastAPI endpoint
341+from fastapi import FastAPI, HTTPException
342+from pydantic import BaseModel
343+
344+app = FastAPI()
345+
346+class User(BaseModel):
347+ name: str
348+ email: str
349+ age: int
350+
351+@app.post("/users/")
352+async def create_user(user: User):
353+ # Continue will help complete this implementation
354+ # Use Cmd+I (Mac) or Ctrl+I (Windows/Linux) to generate code
355+ pass
279356 ```
280357
281358 ### How to Use Ollama for Code Review
@@ -293,4 +370,4 @@
293370
294371 ---
295372
296-_This guide is based on Ollama v0.1.x and Continue v0.8.x. Please check for updates regularly._
373+_This guide is based on Ollama v0.11.x and Continue v1.1.x. Please check for updates regularly._
added extensions/cli/BUILD.md +74 −0
@@ -0,0 +1,74 @@
1+# Build Process Documentation
2+
3+## Overview
4+
5+The Continue CLI uses esbuild to bundle the application along with local packages (`@continuedev/config-yaml` and `@continuedev/openai-adapters`) into a single distributable file. This ensures that users who install the CLI from npm don't need to worry about local file references.
6+
7+## Build Steps
8+
9+1. **Install dependencies**: `npm install`
10+2. **Build**: `npm run build`
11+ - This first builds the local packages
12+ - Then bundles everything with esbuild
13+
14+## How it Works
15+
16+### Bundling Strategy
17+
18+The `build.mjs` script uses esbuild to:
19+
20+- Bundle all TypeScript/JavaScript code into a single ES module
21+- Include local packages (`@continuedev/config-yaml`, `@continuedev/openai-adapters`) directly in the bundle
22+- Keep problematic or native dependencies external (e.g., `@sentry/profiling-node`, `winston`, `express`)
23+- Create a wrapper script (`dist/cn.js`) with the proper shebang for CLI execution
24+
25+### Key Features
26+
27+- **Local Package Bundling**: Local packages are bundled directly, avoiding `file:` reference issues
28+- **Stub for Optional Dependencies**: `react-devtools-core` is stubbed to prevent runtime errors
29+- **CommonJS Compatibility**: Adds `createRequire` to support packages that use dynamic requires
30+- **Source Maps**: Generates source maps for debugging
31+- **Metadata**: Creates `dist/meta.json` with bundle analysis information
32+
33+## Testing
34+
35+### Smoke Tests
36+
37+Run smoke tests to verify the build:
38+
39+```bash
40+npm run test:smoke
41+```
42+
43+The smoke tests verify:
44+
45+- Bundle files exist
46+- CLI commands work (--version, --help)
47+- Bundle size is reasonable (<20MB)
48+- Local packages are properly bundled
49+- No missing runtime dependencies
50+
51+## Troubleshooting
52+
53+### Common Issues
54+
55+1. **Module not found errors**: Check if the module needs to be added to the external list in `build.mjs`
56+2. **Native module issues**: Native modules should be marked as external
57+3. **Bundle too large**: Review bundled packages in `dist/meta.json` and consider marking large packages as external
58+
59+### Analyzing the Bundle
60+
61+After building, check `dist/meta.json` to see:
62+
63+- What packages were bundled
64+- Bundle size breakdown
65+- Input/output file mappings
66+
67+## Publishing
68+
69+When publishing to npm:
70+
71+1. The bundled files in `dist/` are included
72+2. Users install via `npm install -g @continuedev/cli`
73+3. The `cn` command becomes available globally
74+4. No local file references or missing dependencies
added extensions/cli/build.mjs +97 −0
@@ -0,0 +1,97 @@
1+#!/usr/bin/env node
2+
3+import * as esbuild from "esbuild";
4+import { chmodSync, writeFileSync } from "fs";
5+import { dirname, resolve } from "path";
6+import { fileURLToPath } from "url";
7+
8+const __dirname = dirname(fileURLToPath(import.meta.url));
9+
10+// List of packages to mark as external (ONLY native modules that cannot be bundled)
11+// Note: Everything else will be bundled to create a self-contained CLI
12+// Users should not need to install any additional dependencies
13+const external = [
14+ "@sentry/profiling-node", // Contains native profiler bindings (optional)
15+ "fsevents", // macOS native file watcher (optional dependency)
16+];
17+
18+console.log("Building CLI with esbuild...");
19+
20+// Plugin to handle optional react-devtools-core
21+const optionalDevtoolsPlugin = {
22+ name: "optional-devtools",
23+ setup(build) {
24+ build.onResolve({ filter: /^react-devtools-core$/ }, () => {
25+ // Return path to our stub instead of marking as external
26+ return { path: resolve(__dirname, "stubs/react-devtools-core.js") };
27+ });
28+ },
29+};
30+
31+try {
32+ const result = await esbuild.build({
33+ entryPoints: ["src/index.ts"],
34+ bundle: true,
35+ platform: "node",
36+ target: "node18",
37+ format: "esm",
38+ outfile: "dist/index.js",
39+ external,
40+ sourcemap: true,
41+ minify: true, // Minify for smaller bundle size
42+ metafile: true,
43+ plugins: [optionalDevtoolsPlugin],
44+
45+ // Handle .js extensions in imports
46+ resolveExtensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
47+
48+ // Handle TypeScript paths and local packages
49+ alias: {
50+ "@continuedev/config-yaml": resolve(
51+ __dirname,
52+ "../../packages/config-yaml/dist/index.js",
53+ ),
54+ "@continuedev/openai-adapters": resolve(
55+ __dirname,
56+ "../../packages/openai-adapters/dist/index.js",
57+ ),
58+ "@continuedev/config-types": resolve(
59+ __dirname,
60+ "../../packages/config-types/dist/index.js",
61+ ),
62+ core: resolve(__dirname, "../../core"),
63+ "@continuedev/fetch": resolve(
64+ __dirname,
65+ "../../packages/fetch/dist/index.js",
66+ ),
67+ "@continuedev/llm-info": resolve(
68+ __dirname,
69+ "../../packages/llm-info/dist/index.js",
70+ ),
71+ },
72+
73+ // Add banner to create require for CommonJS packages
74+ banner: {
75+ js: `import { createRequire } from 'module';
76+const require = createRequire(import.meta.url);`,
77+ },
78+ });
79+
80+ // Write metafile for analysis
81+ writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
82+
83+ // Create wrapper script with shebang
84+ writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
85+
86+ // Make the wrapper script executable
87+ chmodSync("dist/cn.js", 0o755);
88+
89+ // Calculate bundle size
90+ const bundleSize = result.metafile.outputs["dist/index.js"].bytes;
91+ console.log(
92+ `✓ Build complete! Bundle size: ${(bundleSize / 1024 / 1024).toFixed(2)} MB`,
93+ );
94+} catch (error) {
95+ console.error("Build failed:", error);
96+ process.exit(1);
97+}
modified extensions/cli/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/cli/package.json +18 −11
@@ -6,15 +6,20 @@
66 "types": "dist/index.d.ts",
77 "type": "module",
88 "bin": {
9- "cn": "dist/index.js"
9+ "cn": "dist/cn.js"
1010 },
1111 "scripts": {
1212 "test": "vitest run",
1313 "test:watch": "vitest watch",
1414 "test:ui": "vitest --ui",
1515 "test:e2e": "vitest run --config vitest.e2e.config.ts",
16- "build": "tsc -p tsconfig.build.json",
17- "start": "node dist/index.js",
16+ "test:smoke": "node smoke-test.mjs",
17+ "build:tsc": "tsc -p tsconfig.build.json",
18+ "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && cd ../extensions/cli && npm i",
19+ "build:validate": "node validate-aliases.mjs",
20+ "build:bundle": "node build.mjs",
21+ "build": "npm run build:validate && npm run build:bundle",
22+ "start": "node dist/cn.js",
1823 "dev": "tsx src/index.ts",
1924 "repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
2025 "repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
@@ -39,8 +44,11 @@
3944 },
4045 "homepage": "https://continue.dev",
4146 "dependencies": {
42- "@continuedev/config-yaml": "^1.0.96",
43- "@continuedev/openai-adapters": "^1.4.1",
47+ "@sentry/profiling-node": "^9.43.0"
48+ },
49+ "devDependencies": {
50+ "@continuedev/config-yaml": "file:../../packages/config-yaml",
51+ "@continuedev/openai-adapters": "file:../../packages/openai-adapters",
4452 "@continuedev/sdk": "^0.0.13",
4553 "@modelcontextprotocol/sdk": "^1.17.2",
4654 "@opentelemetry/api": "^1.9.0",
@@ -52,13 +60,13 @@
5260 "@opentelemetry/sdk-node": "^0.203.0",
5361 "@opentelemetry/semantic-conventions": "^1.36.0",
5462 "@sentry/node": "^9.43.0",
55- "@sentry/profiling-node": "^9.43.0",
5663 "@types/express": "^5.0.3",
5764 "@types/react": "^19.1.8",
5865 "@types/turndown": "^5.0.5",
5966 "@workos-inc/node": "^7.45.0",
6067 "chalk": "^5.4.1",
6168 "commander": "^14.0.0",
69+ "core": "file:../../core",
6270 "date-fns": "^4.1.0",
6371 "diff": "^7.0.0",
6472 "dotenv": "^16.5.0",
@@ -66,6 +74,7 @@
6674 "glob": "^11.0.3",
6775 "gpt-tokenizer": "^3.0.1",
6876 "gradient-string": "^3.0.0",
77+ "ignore": "^7.0.5",
6978 "ignore-walk": "^7.0.0",
7079 "ink": "^6.1.0",
7180 "jszip": "^3.10.1",
@@ -83,9 +92,7 @@
8392 "typescript": "^5.8.3",
8493 "uuid": "^9.0.1",
8594 "winston": "^3.17.0",
86- "yaml": "^2.8.0"
87- },
88- "devDependencies": {
95+ "yaml": "^2.8.0",
8996 "@semantic-release/changelog": "^6.0.3",
9097 "@semantic-release/git": "^10.0.1",
9198 "@semantic-release/github": "^11.0.3",
@@ -93,7 +100,6 @@
93100 "@testing-library/react": "^16.3.0",
94101 "@types/date-fns": "^2.5.3",
95102 "@types/diff": "^7.0.2",
96- "@types/express": "^5.0.3",
97103 "@types/glob": "^8.1.0",
98104 "@types/ignore-walk": "^4.0.3",
99105 "@types/ink-testing-library": "^1.0.4",
@@ -102,17 +108,18 @@
102108 "@types/readline-sync": "^1.4.8",
103109 "@types/shell-quote": "^1.7.5",
104110 "@types/supertest": "^6.0.3",
111+ "@types/uuid": "^10.0.0",
105112 "@typescript-eslint/eslint-plugin": "^8.39.0",
106113 "@typescript-eslint/parser": "^8.39.0",
107114 "@vitest/ui": "^3.2.4",
108115 "conventional-changelog-conventionalcommits": "^9.1.0",
109116 "cross-env": "^7.0.3",
117+ "esbuild": "^0.25.9",
110118 "eslint": "^9.32.0",
111119 "eslint-import-resolver-typescript": "^4.4.4",
112120 "eslint-plugin-import": "^2.32.0",
113121 "eslint-plugin-unused-imports": "^4.1.4",
114122 "execa": "^9.6.0",
115- "express": "^5.1.0",
116123 "happy-dom": "^18.0.1",
117124 "ink-testing-library": "^4.0.0",
118125 "jsdom": "^26.1.0",
added extensions/cli/smoke-test.mjs +230 −0
@@ -0,0 +1,230 @@
1+#!/usr/bin/env node
2+
3+import { execSync } from "child_process";
4+import { existsSync, readFileSync } from "fs";
5+import { resolve, dirname } from "path";
6+import { fileURLToPath } from "url";
7+
8+const __dirname = dirname(fileURLToPath(import.meta.url));
9+
10+// Colors for output
11+const colors = {
12+ green: "\x1b[32m",
13+ red: "\x1b[31m",
14+ yellow: "\x1b[33m",
15+ reset: "\x1b[0m",
16+};
17+
18+let testsPassed = 0;
19+let testsFailed = 0;
20+
21+function runTest(name, testFn) {
22+ process.stdout.write(`Testing ${name}... `);
23+ try {
24+ testFn();
25+ console.log(`${colors.green}✓${colors.reset}`);
26+ testsPassed++;
27+ } catch (error) {
28+ console.log(`${colors.red}✗${colors.reset}`);
29+ console.error(` Error: ${error.message}`);
30+ testsFailed++;
31+ }
32+}
33+
34+function execCommand(command, options = {}) {
35+ return execSync(command, {
36+ cwd: __dirname,
37+ encoding: "utf8",
38+ stdio: "pipe",
39+ ...options,
40+ });
41+}
42+
43+console.log("🧪 Running smoke tests for bundled CLI...\n");
44+
45+// Test 1: Check if bundle exists
46+runTest("Bundle file exists", () => {
47+ if (!existsSync(resolve(__dirname, "dist/index.js"))) {
48+ throw new Error("dist/index.js not found");
49+ }
50+ if (!existsSync(resolve(__dirname, "dist/cn.js"))) {
51+ throw new Error("dist/cn.js not found");
52+ }
53+});
54+
55+// Test 2: Check if wrapper script is executable
56+runTest("Wrapper script has shebang", () => {
57+ const content = readFileSync(resolve(__dirname, "dist/cn.js"), "utf8");
58+ if (!content.startsWith("#!/usr/bin/env node")) {
59+ throw new Error("Wrapper script missing shebang");
60+ }
61+});
62+
63+// Cross-platform command execution helper
64+function getCLICommand(args = "") {
65+ const isWindows = process.platform === "win32";
66+ if (isWindows) {
67+ return `node dist/cn.js ${args}`;
68+ } else {
69+ return `./dist/cn.js ${args}`;
70+ }
71+}
72+
73+// Test 3: Version command works
74+runTest("Version command", () => {
75+ const output = execCommand(getCLICommand("--version"));
76+ const packageJson = JSON.parse(
77+ readFileSync(resolve(__dirname, "package.json"), "utf8"),
78+ );
79+ if (!output.includes(packageJson.version)) {
80+ throw new Error(
81+ `Version mismatch. Expected ${packageJson.version}, got: ${output}`,
82+ );
83+ }
84+});
85+
86+// Test 4: Help command works
87+runTest("Help command", () => {
88+ const output = execCommand(getCLICommand("--help"));
89+ if (!output.includes("Continue CLI") || !output.includes("--version")) {
90+ throw new Error("Help output missing expected content");
91+ }
92+});
93+
94+// Test 5: Check bundle size
95+runTest("Bundle size is reasonable", () => {
96+ const isWindows = process.platform === "win32";
97+ const command = isWindows
98+ ? `powershell -Command "(Get-Item dist/index.js).length / 1MB"`
99+ : `ls -lh dist/index.js`;
100+
101+ let sizeInMB;
102+
103+ if (isWindows) {
104+ try {
105+ const output = execCommand(command);
106+ sizeInMB = parseFloat(output.trim());
107+ } catch {
108+ // Fallback for Windows if PowerShell fails
109+ const stats = readFileSync(resolve(__dirname, "dist/index.js"));
110+ sizeInMB = stats.length / (1024 * 1024);
111+ }
112+ } else {
113+ const stats = execCommand(command);
114+ const sizeMatch = stats.match(/(\d+(?:\.\d+)?[MK])/);
115+ if (sizeMatch) {
116+ const size = sizeMatch[1];
117+ const numSize = parseFloat(size);
118+ const unit = size.slice(-1);
119+ sizeInMB = unit === "M" ? numSize : numSize / 1024;
120+ }
121+ }
122+
123+ console.log(`(${sizeInMB.toFixed(1)}M)`);
124+
125+ // This is arbitrary. We might go over at some point,
126+ // in which case you can just increase this.
127+ if (sizeInMB > 20) {
128+ throw new Error(`Bundle too large: ${sizeInMB.toFixed(1)}M`);
129+ }
130+});
131+
132+// Test 6: Check that local packages are bundled
133+runTest("Local packages are bundled", () => {
134+ const bundleContent = readFileSync(
135+ resolve(__dirname, "dist/index.js"),
136+ "utf8",
137+ );
138+
139+ // Check for code from @continuedev/config-yaml
140+ if (
141+ !bundleContent.includes("AssistantUnrolled") &&
142+ !bundleContent.includes("config-yaml")
143+ ) {
144+ throw new Error("@continuedev/config-yaml not properly bundled");
145+ }
146+
147+ // Check for code from @continuedev/openai-adapters
148+ // Since the bundle is minified, check for strings that would be present
149+ // even after minification (e.g., error messages, property names)
150+ if (
151+ !bundleContent.includes("anthropic") &&
152+ !bundleContent.includes("gemini") &&
153+ !bundleContent.includes("openai") &&
154+ !bundleContent.includes("azure") &&
155+ !bundleContent.includes("bedrock")
156+ ) {
157+ throw new Error("@continuedev/openai-adapters not properly bundled");
158+ }
159+});
160+
161+// Test 7: Test that the CLI can be invoked programmatically
162+runTest("CLI can be invoked", () => {
163+ try {
164+ // Test that the CLI runs without crashing when given no args
165+ const isWindows = process.platform === "win32";
166+ const nullDevice = isWindows ? "nul" : "/dev/null";
167+ execCommand(`${getCLICommand("--help")} > ${nullDevice} 2>&1`);
168+ } catch (error) {
169+ throw new Error(`CLI invocation failed: ${error.message}`);
170+ }
171+});
172+
173+// Test 8: Check metadata file
174+runTest("Build metadata exists", () => {
175+ if (!existsSync(resolve(__dirname, "dist/meta.json"))) {
176+ throw new Error("dist/meta.json not found");
177+ }
178+
179+ const meta = JSON.parse(
180+ readFileSync(resolve(__dirname, "dist/meta.json"), "utf8"),
181+ );
182+ if (!meta.inputs || !meta.outputs) {
183+ throw new Error("Invalid metadata structure");
184+ }
185+});
186+
187+// Test 9: Verify no missing external dependencies
188+runTest("No missing runtime dependencies", () => {
189+ // This would fail in Test 3 if dependencies were missing, but let's be explicit
190+ const output = execCommand(`${getCLICommand("--version")} 2>&1`, {
191+ env: { ...process.env, NODE_ENV: "production" },
192+ });
193+
194+ if (
195+ output.includes("Cannot find module") ||
196+ output.includes("MODULE_NOT_FOUND")
197+ ) {
198+ throw new Error("Missing module detected in output");
199+ }
200+});
201+
202+// Test 10: Test npm link scenario
203+runTest("CLI works via npm link", () => {
204+ try {
205+ // Simply test that we can execute with node directly
206+ const output = execCommand("node dist/cn.js --version 2>&1");
207+ const packageJson = JSON.parse(
208+ readFileSync(resolve(__dirname, "package.json"), "utf8"),
209+ );
210+ if (!output.includes(packageJson.version)) {
211+ throw new Error("Version not found when running via node");
212+ }
213+ } catch (error) {
214+ throw new Error(`npm link scenario failed: ${error.message}`);
215+ }
216+});
217+
218+// Summary
219+console.log("\n" + "=".repeat(50));
220+if (testsFailed === 0) {
221+ console.log(
222+ `${colors.green}✅ All ${testsPassed} tests passed!${colors.reset}`,
223+ );
224+ process.exit(0);
225+} else {
226+ console.log(
227+ `${colors.red}❌ ${testsFailed} test(s) failed, ${testsPassed} passed${colors.reset}`,
228+ );
229+ process.exit(1);
230+}
modified extensions/cli/src/asciiArt.test.ts +6 −5
@@ -27,26 +27,27 @@
2727 expect(result).toBe(CONTINUE_ASCII_ART);
2828 });
2929
30- it("should return simple text version when terminal is too narrow", () => {
30+ it("should return CN ASCII art version when terminal is too narrow", () => {
3131 // Set process.stdout.columns to simulate narrow terminal
3232 process.stdout.columns = 60;
3333
3434 const result = getDisplayableAsciiArt();
3535
36- expect(result).toContain("CONTINUE");
37- // expect(result).toContain("v0.0.0-dev");
36+ expect(result).toContain("██████╗");
37+ expect(result).toContain("(alpha)");
3838 expect(result).not.toBe(CONTINUE_ASCII_ART);
3939 // Should be much shorter than the full ASCII art
4040 expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2);
4141 });
4242
43- it("should return simple text version when terminal is below threshold", () => {
43+ it("should return CN ASCII art version when terminal is below threshold", () => {
4444 // Test the edge case at exactly 74 columns (below our threshold of 75)
4545 process.stdout.columns = 74;
4646
4747 const result = getDisplayableAsciiArt();
4848
49- expect(result).toContain("CONTINUE");
49+ expect(result).toContain("██████╗");
50+ expect(result).toContain("(alpha)");
5051 expect(result).not.toBe(CONTINUE_ASCII_ART);
5152 });
5253
modified extensions/cli/src/asciiArt.ts +13 −3
@@ -12,7 +12,17 @@
1212 ██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝
1313 ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗
1414 ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)}
15- ${d("v" + getVersion())}`;
15+ ${d("v" + getVersion() + " (alpha)")}`;
16+
17+// ASCII art for just "CN" (first two letters)
18+const CN_ASCII_ART = `
19+${mind.multiline(` ██████╗███╗ ██╗
20+ ██╔════╝████╗ ██║
21+ ██║ ██╔██╗ ██║
22+ ██║ ██║╚██╗██║
23+ ╚██████╗██║ ╚████║
24+ ╚═════╝╚═╝ ╚═══╝`)}
25+ ${d("v" + getVersion() + " (alpha)")}`;
1626
1727 // Minimum terminal width required to display ASCII art properly
1828 const MIN_WIDTH_FOR_ASCII_ART = 75;
@@ -28,8 +38,8 @@
2838 return CONTINUE_ASCII_ART;
2939 }
3040
31- // If terminal is too narrow, just show a simple version
32- return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`;
41+ // If terminal is too narrow, show just "CN" ASCII art
42+ return CN_ASCII_ART;
3343 }
3444
3545 export const CONTINUE_LOGO_ASCII_ART = `
modified extensions/cli/src/commands/chat.ts +67 −60
@@ -10,6 +10,7 @@
1010 getHistoryForLLM,
1111 } from "../compaction.js";
1212 import { processCommandFlags } from "../flags/flagProcessor.js";
13+import { safeStdout } from "../init.js";
1314 import { configureLogger } from "../logger.js";
1415 import * as logging from "../logging.js";
1516 import { sentryService } from "../sentry.js";
@@ -22,7 +23,6 @@
2223 import { posthogService } from "../telemetry/posthogService.js";
2324 import { telemetryService } from "../telemetry/telemetryService.js";
2425 import { startTUIChat } from "../ui/index.js";
25-import { safeStdout } from "../util/consoleOverride.js";
2626 import { formatAnthropicError, formatError } from "../util/formatError.js";
2727 import { logger } from "../util/logger.js";
2828 import {
@@ -159,7 +159,7 @@
159159 }
160160 }
161161
162-// Helper function to handle auto-compaction
162+// Helper function to handle auto-compaction for headless mode
163163 async function handleAutoCompaction(
164164 chatHistory: ChatCompletionMessageParam[],
165165 model: ModelConfig,
@@ -167,64 +167,71 @@
167167 isHeadless: boolean,
168168 format?: "json",
169169 ): Promise<number | null> {
170- logger.info("Auto-compacting triggered due to context limit");
171-
172- if (!isHeadless) {
173- console.info(
174- chalk.yellow(
175- "\nApproaching context limit. Auto-compacting chat history...",
176- ),
177- );
178- } else if (format === "json") {
179- safeStdout(
180- JSON.stringify({
181- status: "info",
182- message: "Auto-compacting triggered",
183- contextUsage:
184- calculateContextUsagePercentage(
185- countChatHistoryTokens(chatHistory),
186- model,
187- ) + "%",
188- }) + "\n",
189- );
190- }
191-
192- try {
193- const result = await compactChatHistory(chatHistory, model, llmApi);
194- chatHistory.length = 0;
195- chatHistory.push(...result.compactedHistory);
196- saveSession(chatHistory);
197-
198- if (!isHeadless) {
199- console.info(chalk.green("✓ Chat history auto-compacted successfully."));
200- } else if (format === "json") {
201- safeStdout(
202- JSON.stringify({
203- status: "success",
204- message: "Auto-compacted successfully",
205- historyLength: chatHistory.length,
206- }) + "\n",
207- );
208- }
209-
210- return result.compactionIndex;
211- } catch (error) {
212- const errorMsg = `Auto-compaction error: ${formatError(error)}`;
213- logger.error(errorMsg);
214-
215- if (!isHeadless) {
216- console.error(chalk.red(`Warning: ${errorMsg}`));
217- console.info(chalk.yellow("Continuing without compaction..."));
218- } else if (format === "json") {
219- safeStdout(
220- JSON.stringify({
221- status: "warning",
222- message: "Auto-compaction failed, continuing without compaction",
223- }) + "\n",
224- );
225- }
226- return null;
227- }
170+ const { handleAutoCompaction: coreAutoCompaction } = await import(
171+ "../streamChatResponse.autoCompaction.js"
172+ );
173+
174+ // Custom callbacks for headless mode console output
175+ const callbacks = {
176+ onSystemMessage: (message: string) => {
177+ if (
178+ message.includes("Auto-compacting") ||
179+ message.includes("Approaching")
180+ ) {
181+ if (!isHeadless) {
182+ console.info(chalk.yellow(`\n${message}`));
183+ } else if (format === "json") {
184+ safeStdout(
185+ JSON.stringify({
186+ status: "info",
187+ message: "Auto-compacting triggered",
188+ contextUsage:
189+ calculateContextUsagePercentage(
190+ countChatHistoryTokens(chatHistory),
191+ model,
192+ ) + "%",
193+ }) + "\n",
194+ );
195+ }
196+ } else if (message.includes("✓")) {
197+ if (!isHeadless) {
198+ console.info(chalk.green(message));
199+ } else if (format === "json") {
200+ safeStdout(
201+ JSON.stringify({
202+ status: "success",
203+ message: "Auto-compacted successfully",
204+ historyLength: chatHistory.length,
205+ }) + "\n",
206+ );
207+ }
208+ } else if (message.includes("Warning:")) {
209+ if (!isHeadless) {
210+ console.error(chalk.red(message));
211+ console.info(chalk.yellow("Continuing without compaction..."));
212+ } else if (format === "json") {
213+ safeStdout(
214+ JSON.stringify({
215+ status: "warning",
216+ message: "Auto-compaction failed, continuing without compaction",
217+ }) + "\n",
218+ );
219+ }
220+ }
221+ },
222+ };
223+
224+ const result = await coreAutoCompaction(chatHistory, model, llmApi, {
225+ isHeadless,
226+ format,
227+ callbacks,
228+ });
229+
230+ // Update the original array reference for headless mode
231+ chatHistory.length = 0;
232+ chatHistory.push(...result.chatHistory);
233+
234+ return result.compactionIndex;
228235 }
229236
230237 interface ProcessMessageOptions {
modified extensions/cli/src/commands/commands.ts +6 −1
@@ -4,9 +4,9 @@
44 export { chat } from "./chat.js";
55 export { login } from "./login.js";
66 export { logout } from "./logout.js";
7+export { listSessionsCommand } from "./ls.js";
78 export { remote } from "./remote.js";
89 export { serve } from "./serve.js";
9-export { listSessionsCommand } from "./ls.js";
1010
1111 export interface SlashCommand {
1212 name: string;
@@ -45,6 +45,11 @@
4545 description: "Check who you're currently logged in as",
4646 category: "system",
4747 },
48+ {
49+ name: "info",
50+ description: "Show session information",
51+ category: "system",
52+ },
4853 {
4954 name: "model",
5055 description: "Switch between available chat models",
added extensions/cli/src/compaction.infiniteLoop.test.ts +138 −0
@@ -0,0 +1,138 @@
1+import { ModelConfig } from "@continuedev/config-yaml";
2+import { BaseLlmApi } from "@continuedev/openai-adapters";
3+import { ChatCompletionMessageParam } from "openai/resources.mjs";
4+import { describe, it, expect, vi } from "vitest";
5+
6+import { compactChatHistory } from "./compaction.js";
7+import { streamChatResponse } from "./streamChatResponse.js";
8+
9+// Mock the dependencies
10+vi.mock("./streamChatResponse.js", () => ({
11+ streamChatResponse: vi.fn(),
12+}));
13+
14+vi.mock("./util/tokenizer.js", () => ({
15+ countChatHistoryTokens: vi.fn(),
16+ getModelContextLimit: vi.fn(),
17+}));
18+
19+describe("compaction infinite loop prevention", () => {
20+ const mockModel: ModelConfig = {
21+ name: "test-model",
22+ provider: "test",
23+ model: "test-model",
24+ defaultCompletionOptions: {
25+ maxTokens: 1000,
26+ contextLength: 4000,
27+ },
28+ } as ModelConfig;
29+
30+ const mockLlmApi = {} as BaseLlmApi;
31+
32+ it("should not loop infinitely when pruning doesn't reduce history size", async () => {
33+ const { countChatHistoryTokens, getModelContextLimit } = await import(
34+ "./util/tokenizer.js"
35+ );
36+ const mockStreamResponse = vi.mocked(streamChatResponse);
37+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
38+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
39+
40+ // Setup mocks
41+ mockGetContextLimit.mockReturnValue(4000);
42+ mockCountTokens.mockReturnValue(5000); // Always too big
43+ mockStreamResponse.mockImplementation(
44+ async (history, model, api, controller, callbacks) => {
45+ callbacks?.onContent?.("Summary");
46+ callbacks?.onContentComplete?.("Summary");
47+ return "Summary";
48+ },
49+ );
50+
51+ // History that can't be pruned further (only system message)
52+ const history: ChatCompletionMessageParam[] = [
53+ { role: "system", content: "System message" },
54+ ];
55+
56+ // This should not hang - it should break out of the loop
57+ const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
58+
59+ // Should complete successfully even though token count is still too high
60+ expect(result.compactedHistory).toBeDefined();
61+ expect(mockCountTokens).toHaveBeenCalled();
62+ });
63+
64+ it("should not loop infinitely with history ending in assistant message", async () => {
65+ const { countChatHistoryTokens, getModelContextLimit } = await import(
66+ "./util/tokenizer.js"
67+ );
68+ const mockStreamResponse = vi.mocked(streamChatResponse);
69+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
70+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
71+
72+ // Setup mocks
73+ mockGetContextLimit.mockReturnValue(4000);
74+ mockCountTokens.mockReturnValue(5000); // Always too big
75+ mockStreamResponse.mockImplementation(
76+ async (history, model, api, controller, callbacks) => {
77+ callbacks?.onContent?.("Summary");
78+ callbacks?.onContentComplete?.("Summary");
79+ return "Summary";
80+ },
81+ );
82+
83+ // History that ends with assistant - pruning won't change it
84+ const history: ChatCompletionMessageParam[] = [
85+ { role: "system", content: "System message" },
86+ { role: "user", content: "Hello" },
87+ { role: "assistant", content: "Hi there" },
88+ ];
89+
90+ // This should not hang
91+ const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
92+
93+ expect(result.compactedHistory).toBeDefined();
94+ });
95+
96+ it("should successfully prune when pruning actually reduces size", async () => {
97+ const { countChatHistoryTokens, getModelContextLimit } = await import(
98+ "./util/tokenizer.js"
99+ );
100+ const mockStreamResponse = vi.mocked(streamChatResponse);
101+ const mockCountTokens = vi.mocked(countChatHistoryTokens);
102+ const mockGetContextLimit = vi.mocked(getModelContextLimit);
103+
104+ // Setup mocks
105+ mockGetContextLimit.mockReturnValue(4000);
106+
107+ // Mock token counting to show reduction after pruning
108+ let callCount = 0;
109+ mockCountTokens.mockImplementation(() => {
110+ callCount++;
111+ if (callCount === 1) return 5000; // Initial too big
112+ if (callCount === 2) return 3000; // After pruning, fits
113+ return 2000; // Subsequent calls
114+ });
115+
116+ mockStreamResponse.mockImplementation(
117+ async (history, model, api, controller, callbacks) => {
118+ callbacks?.onContent?.("Summary");
119+ callbacks?.onContentComplete?.("Summary");
120+ return "Summary";
121+ },
122+ );
123+
124+ // History that can be successfully pruned
125+ const history: ChatCompletionMessageParam[] = [
126+ { role: "system", content: "System message" },
127+ { role: "user", content: "Hello" },
128+ { role: "assistant", content: "Hi there" },
129+ { role: "user", content: "Another question" },
130+ ];
131+
132+ const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
133+
134+ expect(result.compactedHistory).toBeDefined();
135+ // The function will call countTokens multiple times during the process
136+ expect(mockCountTokens).toHaveBeenCalled();
137+ });
138+});
added extensions/cli/src/compaction.pruneLastMessage.test.ts +185 −0
@@ -0,0 +1,185 @@
1+import { ChatCompletionMessageParam } from "openai/resources.mjs";
2+import { describe, it, expect } from "vitest";
3+
4+import { pruneLastMessage } from "./compaction.js";
5+
6+describe("pruneLastMessage", () => {
7+ it("should return empty array for empty input", () => {
8+ const result = pruneLastMessage([]);
9+ expect(result).toEqual([]);
10+ });
11+
12+ it("should remove single user message", () => {
13+ const history: ChatCompletionMessageParam[] = [
14+ { role: "user", content: "Hello" },
15+ ];
16+
17+ const result = pruneLastMessage(history);
18+ expect(result).toEqual([]);
19+ });
20+
21+ it("should return empty array for single system message", () => {
22+ const history: ChatCompletionMessageParam[] = [
23+ { role: "system", content: "System" },
24+ ];
25+
26+ const result = pruneLastMessage(history);
27+ expect(result).toEqual([]);
28+ });
29+
30+ it("should return empty array for single assistant message", () => {
31+ const history: ChatCompletionMessageParam[] = [
32+ { role: "assistant", content: "Hello" },
33+ ];
34+
35+ const result = pruneLastMessage(history);
36+ expect(result).toEqual([]);
37+ });
38+
39+ it("should return empty array for single tool message", () => {
40+ const history: ChatCompletionMessageParam[] = [
41+ { role: "tool", content: "Tool output", tool_call_id: "1" },
42+ ];
43+
44+ const result = pruneLastMessage(history);
45+ expect(result).toEqual([]);
46+ });
47+
48+ it("should remove last message when second-to-last is user", () => {
49+ const history: ChatCompletionMessageParam[] = [
50+ { role: "system", content: "System" },
51+ { role: "user", content: "Hello" },
52+ { role: "assistant", content: "Hi there" },
53+ ];
54+
55+ const result = pruneLastMessage(history);
56+ expect(result).toEqual([{ role: "system", content: "System" }]);
57+ });
58+
59+ it("should remove assistant+tool sequence when second-to-last is assistant with tool calls", () => {
60+ const history: ChatCompletionMessageParam[] = [
61+ { role: "system", content: "System" },
62+ { role: "user", content: "Run command" },
63+ {
64+ role: "assistant",
65+ content: "Running...",
66+ tool_calls: [{ id: "1" } as any],
67+ },
68+ { role: "tool", content: "Command output", tool_call_id: "1" },
69+ ];
70+
71+ const result = pruneLastMessage(history);
72+ expect(result).toEqual([
73+ { role: "system", content: "System" },
74+ { role: "user", content: "Run command" },
75+ ]);
76+ });
77+
78+ it("should prune last message when second-to-last is not user or assistant with tool calls", () => {
79+ const history: ChatCompletionMessageParam[] = [
80+ { role: "system", content: "System" },
81+ { role: "assistant", content: "Hi there" },
82+ { role: "user", content: "Another question" },
83+ ];
84+
85+ const result = pruneLastMessage(history);
86+ expect(result).toEqual([
87+ { role: "system", content: "System" },
88+ { role: "assistant", content: "Hi there" },
89+ ]);
90+ });
91+
92+ it("should handle multiple user messages by removing two at a time", () => {
93+ const history: ChatCompletionMessageParam[] = [
94+ { role: "system", content: "System" },
95+ { role: "user", content: "Question 1" },
96+ { role: "user", content: "Question 2" },
97+ ];
98+
99+ const result = pruneLastMessage(history);
100+ expect(result).toEqual([{ role: "system", content: "System" }]);
101+ });
102+
103+ it("should handle tool call sequences by removing user after tool", () => {
104+ const history: ChatCompletionMessageParam[] = [
105+ { role: "system", content: "System" },
106+ { role: "user", content: "Do something" },
107+ {
108+ role: "assistant",
109+ content: "I'll help",
110+ tool_calls: [{ id: "1" } as any],
111+ },
112+ { role: "tool", content: "Tool result", tool_call_id: "1" },
113+ { role: "user", content: "Follow up question" },
114+ ];
115+
116+ const result = pruneLastMessage(history);
117+ expect(result).toEqual([
118+ { role: "system", content: "System" },
119+ { role: "user", content: "Do something" },
120+ {
121+ role: "assistant",
122+ content: "I'll help",
123+ tool_calls: [{ id: "1" } as any],
124+ },
125+ { role: "tool", content: "Tool result", tool_call_id: "1" },
126+ ]);
127+ });
128+
129+ it("should remove both user messages when consecutive", () => {
130+ const history: ChatCompletionMessageParam[] = [
131+ { role: "user", content: "Hello" },
132+ { role: "user", content: "Another message" },
133+ ];
134+
135+ const result = pruneLastMessage(history);
136+ expect(result).toEqual([]);
137+ });
138+
139+ it("should handle complex conversation flow", () => {
140+ const history: ChatCompletionMessageParam[] = [
141+ { role: "system", content: "System" },
142+ { role: "user", content: "Request 1" },
143+ { role: "assistant", content: "Response 1" },
144+ { role: "user", content: "Request 2" },
145+ {
146+ role: "assistant",
147+ content: "Using tool",
148+ tool_calls: [{ id: "1" } as any],
149+ },
150+ { role: "tool", content: "Tool result", tool_call_id: "1" },
151+ { role: "assistant", content: "Final response" },
152+ { role: "user", content: "Follow up 1" },
153+ { role: "user", content: "Follow up 2" },
154+ ];
155+
156+ const result = pruneLastMessage(history);
157+ expect(result).toEqual([
158+ { role: "system", content: "System" },
159+ { role: "user", content: "Request 1" },
160+ { role: "assistant", content: "Response 1" },
161+ { role: "user", content: "Request 2" },
162+ {
163+ role: "assistant",
164+ content: "Using tool",
165+ tool_calls: [{ id: "1" } as any],
166+ },
167+ { role: "tool", content: "Tool result", tool_call_id: "1" },
168+ { role: "assistant", content: "Final response" },
169+ ]);
170+ });
171+
172+ it("should handle history starting with non-system message", () => {
173+ const history: ChatCompletionMessageParam[] = [
174+ { role: "user", content: "Hello" },
175+ { role: "assistant", content: "Hi" },
176+ { role: "user", content: "Follow up" },
177+ ];
178+
179+ const result = pruneLastMessage(history);
180+ expect(result).toEqual([
181+ { role: "user", content: "Hello" },
182+ { role: "assistant", content: "Hi" },
183+ ]);
184+ });
185+});
modified extensions/cli/src/compaction.ts +70 −2
@@ -5,6 +5,10 @@
55 import { streamChatResponse } from "./streamChatResponse.js";
66 import { StreamCallbacks } from "./streamChatResponse.types.js";
77 import { logger } from "./util/logger.js";
8+import {
9+ countChatHistoryTokens,
10+ getModelContextLimit,
11+} from "./util/tokenizer.js";
812
913 export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
1014
@@ -41,8 +45,39 @@
4145 "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
4246 };
4347
44- // Get the current history for compaction
45- const historyForCompaction = [...chatHistory, compactionPrompt];
48+ // Check if the history with compaction prompt is too long, prune if necessary
49+ let historyToUse = chatHistory;
50+ let historyForCompaction = [...historyToUse, compactionPrompt];
51+
52+ const contextLimit = getModelContextLimit(model);
53+ const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
54+ const reservedForOutput =
55+ maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
56+ const availableForInput = contextLimit - reservedForOutput;
57+
58+ // Check if we need to prune to fit within context
59+ while (
60+ countChatHistoryTokens(historyForCompaction) > availableForInput &&
61+ historyToUse.length > 0
62+ ) {
63+ logger.debug("Compaction history too long, pruning last message", {
64+ tokenCount: countChatHistoryTokens(historyForCompaction),
65+ availableForInput,
66+ historyLength: historyToUse.length,
67+ });
68+ const prunedHistory = pruneLastMessage(historyToUse);
69+
70+ // Break if pruning didn't change the history (prevents infinite loop)
71+ if (prunedHistory.length === historyToUse.length) {
72+ logger.warn(
73+ "Cannot prune history further while maintaining valid conversation structure",
74+ );
75+ break;
76+ }
77+
78+ historyToUse = prunedHistory;
79+ historyForCompaction = [...historyToUse, compactionPrompt];
80+ }
4681
4782 // Stream the compaction response
4883 const controller = new AbortController();
@@ -121,6 +156,39 @@
121156 * @param compactionIndex The index of the compaction message, if any
122157 * @returns The history to send to the LLM
123158 */
159+/**
160+ * Prunes chat history by removing messages from the end while ensuring
161+ * the history ends with either an assistant message or a tool result message
162+ * @param chatHistory The chat history to prune
163+ * @returns The pruned chat history ending with assistant or tool message
164+ */
165+export function pruneLastMessage(
166+ chatHistory: ChatCompletionMessageParam[],
167+): ChatCompletionMessageParam[] {
168+ if (chatHistory.length === 0) {
169+ return chatHistory;
170+ }
171+
172+ if (chatHistory.length === 1) {
173+ // Only one message - always return empty array
174+ return [];
175+ }
176+
177+ const secondToLastIndex = chatHistory.length - 2;
178+ const secondToLastMessage = chatHistory[secondToLastIndex];
179+
180+ if (
181+ secondToLastMessage.role === "assistant" &&
182+ secondToLastMessage.tool_calls?.length
183+ ) {
184+ return chatHistory.slice(0, -2);
185+ } else if (secondToLastMessage.role === "user") {
186+ return chatHistory.slice(0, -2);
187+ }
188+
189+ return chatHistory.slice(0, -1);
190+}
191+
124192 export function getHistoryForLLM(
125193 fullHistory: ChatCompletionMessageParam[],
126194 compactionIndex: number | null,
modified extensions/cli/src/configLoader.ts +2 −2
@@ -291,7 +291,7 @@
291291 apiBase: env.apiBase,
292292 rootPath:
293293 packageIdentifier.uriType === "file"
294- ? dirname(packageIdentifier.filePath)
294+ ? dirname(packageIdentifier.fileUri)
295295 : undefined,
296296 }),
297297 {
@@ -328,7 +328,7 @@
328328 apiClient: DefaultApiInterface,
329329 ): Promise<AssistantUnrolled> {
330330 return await unrollAssistantWithConfig(
331- { filePath, uriType: "file" },
331+ { fileUri: filePath, uriType: "file" },
332332 accessToken,
333333 organizationId,
334334 apiClient,
modified extensions/cli/src/freeTrialTransition.test.ts +8 −8
@@ -1,19 +1,19 @@
11 import {
2- isValidAnthropicApiKey,
32 getApiKeyValidationError,
3+ isValidAnthropicApiKey,
44 } from "./util/apiKeyValidation.js";
55
66 describe("Free Trial Transition API Key Validation", () => {
77 it("should validate API keys properly for free trial transition", () => {
88 // Valid API keys
9- expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
9+ expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true);
1010 expect(
11- isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
11+ isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"),
1212 ).toBe(true);
1313
1414 // Invalid API keys
1515 expect(isValidAnthropicApiKey("TEST-")).toBe(false);
16- expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
16+ expect(isValidAnthropicApiKey("sk-ant-")).toBe(false);
1717 expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false);
1818 expect(isValidAnthropicApiKey("")).toBe(false);
1919 expect(isValidAnthropicApiKey(null)).toBe(false);
@@ -25,14 +25,14 @@
2525 expect(getApiKeyValidationError(null)).toBe("API key is required");
2626 expect(getApiKeyValidationError(undefined)).toBe("API key is required");
2727 expect(getApiKeyValidationError("TEST-")).toBe(
28- 'API key must start with "TEST-ant-"',
28+ 'API key must start with "sk-ant-"',
2929 );
3030 expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
31- 'API key must start with "TEST-ant-"',
31+ 'API key must start with "sk-ant-"',
3232 );
33- expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
33+ expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short");
3434 expect(getApiKeyValidationError("invalid")).toBe(
35- 'API key must start with "TEST-ant-"',
35+ 'API key must start with "sk-ant-"',
3636 );
3737 });
3838 });
modified extensions/cli/src/index.ts +5 −2
@@ -1,5 +1,8 @@
11 #!/usr/bin/env node
22
3+// MUST be the first import - intercepts console/stdout/stderr before any dependencies load
4+import "./init.js";
5+
36 import { Command } from "commander";
47
58 import { chat } from "./commands/chat.js";
@@ -10,12 +13,12 @@
1013 import { remote } from "./commands/remote.js";
1114 import { serve } from "./commands/serve.js";
1215 import {
13- validateFlags,
1416 handleValidationErrors,
17+ validateFlags,
1518 } from "./flags/flagValidator.js";
19+import { configureConsoleForHeadless } from "./init.js";
1620 import { sentryService } from "./sentry.js";
1721 import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
18-import { configureConsoleForHeadless } from "./util/consoleOverride.js";
1922 import { logger } from "./util/logger.js";
2023 import { readStdinSync } from "./util/stdin.js";
2124 import { getVersion } from "./version.js";
added extensions/cli/src/init.ts +128 −0
@@ -0,0 +1,128 @@
1+/**
2+ * Early initialization that must happen before ANY other imports
3+ * This file intercepts console and stdout/stderr to prevent dependency logging
4+ */
5+
6+// Check if we're in headless mode by looking at process arguments
7+// We need to do this before any imports to catch early logging
8+const args = process.argv.slice(2);
9+const isHeadlessMode = args.includes("-p") || args.includes("--print");
10+
11+// Store original methods before ANY dependencies can use them
12+const originalStdoutWrite = process.stdout.write.bind(process.stdout);
13+const originalStderrWrite = process.stderr.write.bind(process.stderr);
14+const originalConsole = {
15+ log: console.log,
16+ info: console.info,
17+ warn: console.warn,
18+ error: console.error,
19+ debug: console.debug,
20+ trace: console.trace,
21+ table: console.table,
22+ dir: console.dir,
23+ dirxml: console.dirxml,
24+ group: console.group,
25+ groupEnd: console.groupEnd,
26+ groupCollapsed: console.groupCollapsed,
27+ time: console.time,
28+ timeEnd: console.timeEnd,
29+ timeLog: console.timeLog,
30+ clear: console.clear,
31+ count: console.count,
32+ countReset: console.countReset,
33+ assert: console.assert,
34+};
35+
36+// Track if we're inside our own code vs dependency code
37+let isHeadlessModeConfigured = false;
38+
39+// Override console methods if in headless mode
40+if (isHeadlessMode) {
41+ // Override ALL console methods to no-ops
42+ Object.keys(originalConsole).forEach((method) => {
43+ (console as any)[method] = () => {};
44+ });
45+
46+ // Override stdout/stderr to block everything by default
47+ process.stdout.write = function (
48+ chunk: any,
49+ encoding?: any,
50+ callback?: any,
51+ ): boolean {
52+ // Always return true to indicate success, but don't actually write
53+ if (typeof encoding === "function") {
54+ encoding();
55+ return true;
56+ }
57+ if (typeof callback === "function") {
58+ callback();
59+ }
60+ return true;
61+ };
62+
63+ process.stderr.write = function (
64+ chunk: any,
65+ encoding?: any,
66+ callback?: any,
67+ ): boolean {
68+ // Always return true to indicate success, but don't actually write
69+ if (typeof encoding === "function") {
70+ encoding();
71+ return true;
72+ }
73+ if (typeof callback === "function") {
74+ callback();
75+ }
76+ return true;
77+ };
78+}
79+
80+/**
81+ * Configure console for headless mode
82+ * Since init.ts already blocks everything, this just tracks state
83+ * and provides the safe output functions
84+ */
85+export function configureConsoleForHeadless(headless: boolean): void {
86+ isHeadlessModeConfigured = headless;
87+
88+ // init.ts should have already handled the blocking if in headless mode
89+ // This function now mainly exists for compatibility and state tracking
90+}
91+
92+/**
93+ * Safe stdout output that bypasses all overrides
94+ * Use this for intentional output in headless mode
95+ */
96+export function safeStdout(message: string): void {
97+ if (isHeadlessMode || isHeadlessModeConfigured) {
98+ // Use the original stdout that was saved before any overrides
99+ originalStdoutWrite(message);
100+ } else {
101+ // In non-headless mode, just use normal stdout
102+ process.stdout.write(message);
103+ }
104+}
105+
106+/**
107+ * Safe stderr output that bypasses all overrides
108+ * Use this for error messages that should always be visible
109+ */
110+export function safeStderr(message: string): void {
111+ if (isHeadlessMode || isHeadlessModeConfigured) {
112+ // Use the original stderr that was saved before any overrides
113+ originalStderrWrite(message);
114+ } else {
115+ // In non-headless mode, just use normal stderr
116+ process.stderr.write(message);
117+ }
118+}
119+
120+/**
121+ * Reset console overrides to original state
122+ * Note: This won't affect init.ts overrides which happen at module load
123+ */
124+export function resetConsoleOverrides(): void {
125+ isHeadlessModeConfigured = false;
126+ // The actual console restoration would need to happen in init.ts
127+ // This is mainly for testing purposes
128+}
added extensions/cli/src/sentry-profiling.ts +52 −0
@@ -0,0 +1,52 @@
1+/**
2+ * Optional profiling integration loader
3+ * This module handles the optional @sentry/profiling-node dependency
4+ * which contains native bindings and may not be available in all environments
5+ */
6+
7+let profilingIntegration: any = null;
8+let profilingLoadAttempted = false;
9+
10+/**
11+ * Lazy load the profiling integration
12+ */
13+async function loadProfilingIntegration() {
14+ if (profilingLoadAttempted) {
15+ return profilingIntegration;
16+ }
17+
18+ profilingLoadAttempted = true;
19+
20+ try {
21+ // Try to load the native profiling module if available
22+ const profilingModule = await import("@sentry/profiling-node");
23+ profilingIntegration = profilingModule.nodeProfilingIntegration;
24+ } catch {
25+ // Profiling module not available - this is fine, profiling is optional
26+ // The CLI will work without it, just without performance profiling
27+ }
28+
29+ return profilingIntegration;
30+}
31+
32+/**
33+ * Returns the profiling integration if available, or a no-op function
34+ * Note: This is now async to handle lazy loading
35+ */
36+export async function getProfilingIntegration() {
37+ const integration = await loadProfilingIntegration();
38+ if (integration) {
39+ return integration();
40+ }
41+ // Return empty object as a no-op integration
42+ return {};
43+}
44+
45+/**
46+ * Check if profiling is available
47+ * Note: This is now async to handle lazy loading
48+ */
49+export async function isProfilingAvailable(): Promise<boolean> {
50+ await loadProfilingIntegration();
51+ return profilingIntegration !== null;
52+}
modified extensions/cli/src/sentry.ts +16 −3
@@ -1,6 +1,9 @@
11 import * as Sentry from "@sentry/node";
2-import { nodeProfilingIntegration } from "@sentry/profiling-node";
32
3+import {
4+ getProfilingIntegration,
5+ isProfilingAvailable,
6+} from "./sentry-profiling.js";
47 import { logger } from "./util/logger.js";
58 import { getVersion } from "./version.js";
69
@@ -45,12 +48,21 @@
4548 };
4649 }
4750
48- private initialize() {
51+ private async initialize() {
4952 if (this.initialized || !this.config.dsn) {
5053 return;
5154 }
5255
5356 try {
57+ const integrations = [];
58+ const profilingIntegration = await getProfilingIntegration();
59+ if (
60+ profilingIntegration &&
61+ Object.keys(profilingIntegration).length > 0
62+ ) {
63+ integrations.push(profilingIntegration);
64+ }
65+
5466 Sentry.init({
5567 dsn: this.config.dsn,
5668 environment: this.config.environment,
@@ -58,7 +70,7 @@
5870 sampleRate: this.config.sampleRate,
5971 profilesSampleRate: this.config.profilesSampleRate,
6072 tracesSampleRate: this.config.tracesSampleRate,
61- integrations: [nodeProfilingIntegration()],
73+ integrations,
6274 beforeSend(event) {
6375 // Filter out certain error types if needed
6476 if (event.exception?.values?.[0]?.type === "AbortError") {
@@ -72,6 +84,7 @@
7284 logger.debug("Sentry initialized", {
7385 environment: this.config.environment,
7486 release: this.config.release,
87+ profilingAvailable: await isProfilingAvailable(),
7588 });
7689 } catch (error) {
7790 logger.error("Failed to initialize Sentry", error);
modified extensions/cli/src/services/FileIndexService.ts +4 −7
@@ -3,6 +3,7 @@
33 import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js";
44 import { getFileWatcher } from "../util/fileWatcher.js";
55 import { isGitRepo } from "../util/git.js";
6+import { logger } from "../util/logger.js";
67
78 import { BaseService } from "./BaseService.js";
89 import { serviceContainer } from "./ServiceContainer.js";
@@ -88,7 +89,7 @@
8889 } catch (error) {
8990 const errorMessage =
9091 error instanceof Error ? error.message : String(error);
91- console.error("Error performing full file index:", error);
92+ logger.error("Error performing full file index:", error);
9293 this.setState({ isIndexing: false, error: errorMessage });
9394 }
9495 }
@@ -103,7 +104,7 @@
103104 // and provides little value since files change less predictably
104105 const inGitRepo = isGitRepo();
105106 if (!inGitRepo) {
106- console.log("Skipping file watcher: not in a git repository");
107+ logger.debug("Skipping file watcher: not in a git repository");
107108 return;
108109 }
109110
@@ -153,13 +154,9 @@
153154 }));
154155
155156 this.setState({ files });
156-
157- console.log(
158- `File index updated: +${addedFiles.length} -${removedFiles.length} files`,
159- );
160157 }
161158 } catch (error) {
162- console.error("Error handling file system change:", error);
159+ logger.error("Error handling file system change:", error);
163160 const errorMessage =
164161 error instanceof Error ? error.message : String(error);
165162 this.setState({ error: errorMessage });
modified extensions/cli/src/services/ModelService.ts +1 −1
@@ -4,8 +4,8 @@
44 import {
55 AuthConfig,
66 getAccessToken,
7- getOrganizationId,
87 getModelName,
8+ getOrganizationId,
99 } from "../auth/workos.js";
1010 import { getLlmApi } from "../config.js";
1111 import { logger } from "../util/logger.js";
modified extensions/cli/src/session.ts +1 −1
@@ -180,7 +180,7 @@
180180 /**
181181 * Get the session file path for the current session
182182 */
183-function getSessionFilePath(): string {
183+export function getSessionFilePath(): string {
184184 const sessionId = getSessionId();
185185 const sessionDir = getSessionDir();
186186 return path.join(sessionDir, `${sessionId}.json`);
modified extensions/cli/src/slashCommands.test.ts +205 −129
@@ -1,155 +1,231 @@
1-// Import after mocking
2-import { AssistantUnrolled } from "@continuedev/config-yaml";
3-import { afterEach, beforeEach, describe, expect, vi, test } from "vitest";
4-
5-import * as workos from "./auth/workos.js";
6-import * as commands from "./commands/commands.js";
7-import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
8-import type { AuthServiceState } from "./services/types.js";
1+import type { AssistantUnrolled } from "@continuedev/config-yaml";
2+import {
3+ describe,
4+ it,
5+ expect,
6+ vi,
7+ beforeEach,
8+ type MockedFunction,
9+} from "vitest";
10+
11+import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js";
12+import type { ConfigServiceState } from "./services/types.js";
913 import { handleSlashCommands } from "./slashCommands.js";
1014
11-// The imports are already mocked via vitest.setup.ts, so we can use them directly
12-
13-// Mock console to avoid output during tests
14-const originalConsole = console;
15-const mockConsole = {
16- info: vi.fn(),
17- error: vi.fn(),
18- log: vi.fn(),
19-};
20-
21-describe("handleSlashCommands", () => {
15+// Mock the services
16+vi.mock("./services/index.js", () => ({
17+ services: {
18+ config: {
19+ getState: vi.fn(),
20+ },
21+ },
22+ reloadService: vi.fn(),
23+ SERVICE_NAMES: {
24+ AUTH: "AUTH",
25+ },
26+}));
27+
28+// Mock auth functions
29+vi.mock("./auth/workos.js", () => ({
30+ isAuthenticated: vi.fn(),
31+ isAuthenticatedConfig: vi.fn(),
32+ loadAuthConfig: vi.fn(),
33+}));
34+
35+// Mock telemetry
36+vi.mock("./telemetry/posthogService.js", () => ({
37+ posthogService: {
38+ capture: vi.fn(),
39+ },
40+}));
41+
42+// Mock commands
43+vi.mock("./commands/commands.js", () => ({
44+ getAllSlashCommands: vi.fn(() => []),
45+}));
46+
47+// Mock os and path
48+vi.mock("os", () => ({
49+ default: {
50+ homedir: vi.fn(() => "/home/test"),
51+ },
52+}));
53+
54+vi.mock("path", () => ({
55+ default: {
56+ join: vi.fn((...parts) => parts.join("/")),
57+ },
58+ join: vi.fn((...parts) => parts.join("/")),
59+}));
60+
61+// Mock session functions
62+vi.mock("./session.js", () => ({
63+ getSessionFilePath: vi.fn(
64+ () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json",
65+ ),
66+ hasSession: vi.fn(() => false),
67+}));
68+
69+describe("slashCommands", () => {
2270 const mockAssistant: AssistantUnrolled = {
2371 name: "test-assistant",
2472 version: "1.0.0",
25- prompts: [{ name: "test", prompt: "Test prompt: " }],
2673 };
2774
2875 beforeEach(() => {
29- Object.assign(console, mockConsole);
3076 vi.clearAllMocks();
31-
32- // Since the mock already returns the required value, we don't need to set it
33- // Just verify it returns what we expect
34- expect(commands.getAllSlashCommands(mockAssistant)).toEqual(
35- expect.arrayContaining([
36- expect.objectContaining({ name: "help" }),
37- expect.objectContaining({ name: "login" }),
38- ]),
39- );
40- });
41-
42- afterEach(() => {
43- Object.assign(console, originalConsole);
4477 });
4578
46- describe("Automatic Service Cascade Reloading", () => {
47- test.skip("login command should trigger automatic cascade reload via auth service", async () => {
48- const newAuthState: AuthServiceState = {
49- authConfig: { userEmail: "test@example.com" } as any,
50- isAuthenticated: true,
51- };
52-
53- (services.auth.login as any).mockResolvedValue(newAuthState);
54- (workos.isAuthenticatedConfig as any).mockReturnValue(true);
55- (reloadService as any).mockResolvedValue(undefined);
56-
57- const result = await handleSlashCommands("/login", mockAssistant);
79+ describe("handleSlashCommands", () => {
80+ it("should handle /info command when not authenticated", async () => {
81+ const { isAuthenticated } = await import("./auth/workos.js");
82+ const { services } = await import("./services/index.js");
83+
84+ (
85+ isAuthenticated as MockedFunction<typeof isAuthenticated>
86+ ).mockReturnValue(false);
87+ (
88+ services.config.getState as MockedFunction<
89+ typeof services.config.getState
90+ >
91+ ).mockReturnValue({
92+ config: null,
93+ configPath: "/test/config.yaml",
94+ } as ConfigServiceState);
95+
96+ const result = await handleSlashCommands("/info", mockAssistant);
97+
98+ expect(result).toBeDefined();
99+ expect(result?.output).toContain("Authentication:");
100+ expect(result?.output).toContain("Not logged in");
101+ expect(result?.output).toContain("Configuration:");
102+ expect(result?.output).toContain("/test/config.yaml");
103+ expect(result?.output).toContain("Session History:");
104+ expect(result?.output).toContain(".json");
105+ expect(result?.exit).toBe(false);
106+ });
58107
59- expect(result).not.toBeNull();
108+ it("should handle /info command when authenticated via environment", async () => {
109+ const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
110+ await import("./auth/workos.js");
111+ const { services } = await import("./services/index.js");
112+
113+ (
114+ isAuthenticated as MockedFunction<typeof isAuthenticated>
115+ ).mockReturnValue(true);
116+ (loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
117+ {} as AuthConfig,
118+ );
119+ (isAuthenticatedConfig as any).mockReturnValue(false);
120+ (
121+ services.config.getState as MockedFunction<
122+ typeof services.config.getState
123+ >
124+ ).mockReturnValue({
125+ config: null,
126+ configPath: undefined,
127+ } as ConfigServiceState);
128+
129+ const result = await handleSlashCommands("/info", mockAssistant);
130+
131+ expect(result).toBeDefined();
132+ expect(result?.output).toContain("Authentication:");
60133 expect(result?.output).toContain(
61- "Login successful! All services updated automatically.",
134+ "Authenticated via environment variable",
62135 );
63-
64- // Verify auth service login was called
65- expect(services.auth.login).toHaveBeenCalledTimes(1);
66-
67- // Verify automatic cascade reload was triggered - only auth service reload needed
68- expect(reloadService).toHaveBeenCalledTimes(1);
69- expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH);
70-
71- // Verify manual service reloads are NOT called
72- expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.API_CLIENT);
73- expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG);
74- });
75-
76- test.skip("login failure should not trigger any reloads", async () => {
77- const loginError = new Error("Login failed");
78- (services.auth.login as any).mockRejectedValue(loginError);
79-
80- const result = await handleSlashCommands("/login", mockAssistant);
81-
82- expect(result).not.toBeNull();
83- expect(result?.output).toContain("Login failed: Login failed");
84-
85- // Verify NO reload was triggered on failure
86- expect(reloadService).not.toHaveBeenCalled();
87- });
88- });
89-
90- describe("Other Commands (unchanged behavior)", () => {
91- test("help command should work normally", async () => {
92- const result = await handleSlashCommands("/help", mockAssistant);
93-
94- expect(result).not.toBeNull();
95- expect(result?.output).toContain("Slash commands:");
96- expect(result?.output).toContain("/help: Show help");
97- expect(result?.output).toContain("/login: Authenticate");
136+ expect(result?.output).toContain("Configuration:");
137+ expect(result?.output).toContain("Config not found");
138+ expect(result?.exit).toBe(false);
98139 });
99140
100- test.skip("logout command should exit", async () => {
101- const logoutState: AuthServiceState = {
102- authConfig: null,
103- isAuthenticated: false,
141+ it("should handle /info command when authenticated with user config", async () => {
142+ const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
143+ await import("./auth/workos.js");
144+ const { services } = await import("./services/index.js");
145+
146+ const mockAuthConfig: AuthenticatedConfig = {
147+ userId: "test-user-id",
148+ userEmail: "test@example.com",
149+ accessToken: "test-token",
150+ refreshToken: "test-refresh-token",
151+ expiresAt: Date.now() + 3600000,
152+ organizationId: "test-org-id",
104153 };
105- (services.auth.logout as any).mockResolvedValue(logoutState);
106-
107- const result = await handleSlashCommands("/logout", mockAssistant);
108-
109- expect(result).not.toBeNull();
110- expect(result?.exit).toBe(true);
111- expect(result?.output).toContain("Logged out successfully");
112- });
113-
114- test("clear command should work normally", async () => {
115- const result = await handleSlashCommands("/clear", mockAssistant);
116-
117- expect(result).not.toBeNull();
118- expect(result?.clear).toBe(true);
119- expect(result?.output).toBe("Chat history cleared");
120- });
121154
122- test("compact command should work normally", async () => {
123- const result = await handleSlashCommands("/compact", mockAssistant);
124-
125- expect(result).not.toBeNull();
126- expect(result?.compact).toBe(true);
127- });
128-
129- test("resume command should open session selector", async () => {
130- const result = await handleSlashCommands("/resume", mockAssistant);
131-
132- expect(result).not.toBeNull();
133- expect(result?.openSessionSelector).toBe(true);
134- });
135-
136- test("non-slash input should return null", async () => {
137- const result = await handleSlashCommands("regular input", mockAssistant);
138- expect(result).toBeNull();
155+ (
156+ isAuthenticated as MockedFunction<typeof isAuthenticated>
157+ ).mockReturnValue(true);
158+ (loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
159+ mockAuthConfig,
160+ );
161+ (isAuthenticatedConfig as any).mockReturnValue(true);
162+ (
163+ services.config.getState as MockedFunction<
164+ typeof services.config.getState
165+ >
166+ ).mockReturnValue({
167+ config: null,
168+ configPath: "/custom/config.yaml",
169+ } as ConfigServiceState);
170+
171+ const result = await handleSlashCommands("/info", mockAssistant);
172+
173+ expect(result).toBeDefined();
174+ expect(result?.output).toContain("Authentication:");
175+ expect(result?.output).toContain("test@example.com");
176+ expect(result?.output).toContain("(no org)");
177+ expect(result?.output).toContain("Configuration:");
178+ expect(result?.output).toContain("/custom/config.yaml");
179+ expect(result?.exit).toBe(false);
139180 });
140181
141- test("unknown slash command should return error", async () => {
142- const result = await handleSlashCommands("/unknown", mockAssistant);
143-
144- expect(result).not.toBeNull();
145- expect(result?.output).toBe("Unknown command: unknown");
182+ it("should handle config service errors gracefully", async () => {
183+ const { isAuthenticated } = await import("./auth/workos.js");
184+ const { services } = await import("./services/index.js");
185+
186+ (
187+ isAuthenticated as MockedFunction<typeof isAuthenticated>
188+ ).mockReturnValue(false);
189+ (
190+ services.config.getState as MockedFunction<
191+ typeof services.config.getState
192+ >
193+ ).mockImplementation(() => {
194+ throw new Error("Service not ready");
195+ });
196+
197+ const result = await handleSlashCommands("/info", mockAssistant);
198+
199+ expect(result).toBeDefined();
200+ expect(result?.output).toContain("Configuration service not available");
146201 });
147202
148- test("/org command should no longer exist (now merged into /config)", async () => {
149- const result = await handleSlashCommands("/org list", mockAssistant);
203+ it("should use test session directory when in test mode", async () => {
204+ const { isAuthenticated } = await import("./auth/workos.js");
205+ const { services } = await import("./services/index.js");
206+ const { getSessionFilePath } = await import("./session.js");
207+
208+ // Mock the session path for this specific test
209+ (getSessionFilePath as any).mockReturnValue(
210+ "/test-home/.continue/cli-sessions/continue-cli-test-123.json",
211+ );
150212
151- expect(result).not.toBeNull();
152- expect(result?.output).toBe("Unknown command: org");
213+ (
214+ isAuthenticated as MockedFunction<typeof isAuthenticated>
215+ ).mockReturnValue(false);
216+ (
217+ services.config.getState as MockedFunction<
218+ typeof services.config.getState
219+ >
220+ ).mockReturnValue({
221+ config: null,
222+ configPath: undefined,
223+ } as ConfigServiceState);
224+
225+ const result = await handleSlashCommands("/info", mockAssistant);
226+
227+ expect(result?.output).toContain("/test-home/.continue/cli-sessions/");
228+ expect(result?.output).toContain(".json");
153229 });
154230 });
155231 });
modified extensions/cli/src/slashCommands.ts +70 −0
@@ -8,6 +8,7 @@
88 } from "./auth/workos.js";
99 import { getAllSlashCommands } from "./commands/commands.js";
1010 import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
11+import { getSessionFilePath } from "./session.js";
1112 import { posthogService } from "./telemetry/posthogService.js";
1213 import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
1314
@@ -96,6 +97,63 @@
9697 }
9798 }
9899
100+async function handleInfo() {
101+ posthogService.capture("useSlashCommand", { name: "info" });
102+
103+ const infoLines = [];
104+
105+ // Auth info
106+ if (isAuthenticated()) {
107+ const config = loadAuthConfig();
108+ if (config && isAuthenticatedConfig(config)) {
109+ const email = config.userEmail || config.userId;
110+ const org = "(no org)"; // Organization info not available in AuthenticatedConfig
111+ infoLines.push(chalk.white("Authentication:"));
112+ infoLines.push(` Email: ${chalk.green(email)}`);
113+ infoLines.push(` Organization: ${chalk.cyan(org)}`);
114+ } else {
115+ infoLines.push(chalk.white("Authentication:"));
116+ infoLines.push(
117+ ` ${chalk.yellow("Authenticated via environment variable")}`,
118+ );
119+ }
120+ } else {
121+ infoLines.push(chalk.white("Authentication:"));
122+ infoLines.push(` ${chalk.red("Not logged in")}`);
123+ }
124+
125+ // Config info
126+ try {
127+ const configState = services.config.getState();
128+ infoLines.push("");
129+ infoLines.push(chalk.white("Configuration:"));
130+ if (configState.config) {
131+ infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
132+ } else {
133+ infoLines.push(` ${chalk.red(`Config not found`)}`);
134+ }
135+ if (configState.configPath) {
136+ infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
137+ }
138+ } catch {
139+ infoLines.push("");
140+ infoLines.push(chalk.white("Configuration:"));
141+ infoLines.push(` ${chalk.red("Configuration service not available")}`);
142+ }
143+
144+ // Session history path
145+ infoLines.push("");
146+ infoLines.push(chalk.white("Session History:"));
147+ const sessionFilePath = getSessionFilePath();
148+
149+ infoLines.push(` File: ${chalk.blue(sessionFilePath)}`);
150+
151+ return {
152+ exit: false,
153+ output: infoLines.join("\n"),
154+ };
155+}
156+
99157 const commandHandlers: Record<string, CommandHandler> = {
100158 help: handleHelp,
101159 clear: () => {
@@ -113,6 +171,7 @@
113171 login: handleLogin,
114172 logout: handleLogout,
115173 whoami: handleWhoami,
174+ info: handleInfo,
116175 model: () => ({ openModelSelector: true }),
117176 compact: () => {
118177 posthogService.capture("useSlashCommand", { name: "compact" });
@@ -163,5 +222,16 @@
163222 return { newInput };
164223 }
165224
225+ // Check if this command would match any available commands (same logic as UI)
226+ const allCommands = getAllSlashCommands(assistant);
227+ const hasMatches = allCommands.some((cmd) =>
228+ cmd.name.toLowerCase().includes(command.toLowerCase()),
229+ );
230+
231+ // If no commands match, treat this as regular text instead of an unknown command
232+ if (!hasMatches) {
233+ return null;
234+ }
235+
166236 return { output: `Unknown command: ${command}` };
167237 }
added extensions/cli/src/streamChatResponse.autoCompaction.test.ts +225 −0
@@ -0,0 +1,225 @@
1+import { ChatCompletionMessageParam } from "openai/resources.mjs";
2+import { describe, it, expect, vi, beforeEach } from "vitest";
3+
4+import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
5+
6+// Mock dependencies
7+vi.mock("./compaction.js", () => ({
8+ compactChatHistory: vi.fn(),
9+}));
10+
11+vi.mock("./session.js", () => ({
12+ saveSession: vi.fn(),
13+}));
14+
15+vi.mock("./util/tokenizer.js", () => ({
16+ shouldAutoCompact: vi.fn(),
17+ getAutoCompactMessage: vi.fn(),
18+}));
19+
20+vi.mock("./util/formatError.js", () => ({
21+ formatError: vi.fn((error) => error.message || String(error)),
22+}));
23+
24+vi.mock("./util/logger.js", () => ({
25+ logger: {
26+ info: vi.fn(),
27+ debug: vi.fn(),
28+ error: vi.fn(),
29+ warn: vi.fn(),
30+ },
31+}));
32+
33+describe("handleAutoCompaction", () => {
34+ const mockModel = {
35+ provider: "openai",
36+ name: "gpt-4",
37+ model: "gpt-4",
38+ defaultCompletionOptions: {
39+ contextLength: 8192,
40+ maxTokens: 2048,
41+ },
42+ } as any;
43+
44+ const mockLlmApi = {} as any;
45+ const mockChatHistory: ChatCompletionMessageParam[] = [
46+ { role: "system", content: "You are a helpful assistant." },
47+ { role: "user", content: "Hello" },
48+ { role: "assistant", content: "Hi there!" },
49+ ];
50+
51+ beforeEach(() => {
52+ vi.clearAllMocks();
53+ });
54+
55+ it("should return original history when auto-compaction is not needed", async () => {
56+ const { shouldAutoCompact } = await import("./util/tokenizer.js");
57+ vi.mocked(shouldAutoCompact).mockReturnValue(false);
58+
59+ const result = await handleAutoCompaction(
60+ mockChatHistory,
61+ mockModel,
62+ mockLlmApi,
63+ {},
64+ );
65+
66+ expect(result).toEqual({
67+ chatHistory: mockChatHistory,
68+ compactionIndex: null,
69+ });
70+
71+ expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
72+ });
73+
74+ it("should perform auto-compaction when context limit is approaching", async () => {
75+ const { shouldAutoCompact, getAutoCompactMessage } = await import(
76+ "./util/tokenizer.js"
77+ );
78+ const { compactChatHistory } = await import("./compaction.js");
79+ const { saveSession } = await import("./session.js");
80+
81+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
82+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
83+
84+ const mockCompactionResult = {
85+ compactedHistory: [
86+ {
87+ role: "system",
88+ content: "You are a helpful assistant.",
89+ } as ChatCompletionMessageParam,
90+ {
91+ role: "assistant",
92+ content: "[COMPACTED HISTORY]\nConversation summary...",
93+ } as ChatCompletionMessageParam,
94+ ],
95+ compactionIndex: 1,
96+ compactionContent: "Conversation summary...",
97+ };
98+
99+ vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
100+
101+ const mockCallbacks = {
102+ onSystemMessage: vi.fn(),
103+ };
104+
105+ const result = await handleAutoCompaction(
106+ mockChatHistory,
107+ mockModel,
108+ mockLlmApi,
109+ {
110+ isHeadless: false,
111+ callbacks: mockCallbacks,
112+ },
113+ );
114+
115+ expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
116+ expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel);
117+ expect(compactChatHistory).toHaveBeenCalledWith(
118+ mockChatHistory,
119+ mockModel,
120+ mockLlmApi,
121+ expect.any(Object),
122+ );
123+ expect(saveSession).toHaveBeenCalledWith(
124+ mockCompactionResult.compactedHistory,
125+ );
126+
127+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
128+ "Auto-compacting...",
129+ );
130+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
131+ "✓ Chat history auto-compacted successfully.",
132+ );
133+
134+ expect(result).toEqual({
135+ chatHistory: mockCompactionResult.compactedHistory,
136+ compactionIndex: mockCompactionResult.compactionIndex,
137+ });
138+ });
139+
140+ it("should handle compaction errors gracefully", async () => {
141+ const { shouldAutoCompact, getAutoCompactMessage } = await import(
142+ "./util/tokenizer.js"
143+ );
144+ const { compactChatHistory } = await import("./compaction.js");
145+ const { logger } = await import("./util/logger.js");
146+
147+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
148+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
149+ vi.mocked(compactChatHistory).mockRejectedValue(
150+ new Error("Compaction failed"),
151+ );
152+
153+ const mockCallbacks = {
154+ onSystemMessage: vi.fn(),
155+ };
156+
157+ const result = await handleAutoCompaction(
158+ mockChatHistory,
159+ mockModel,
160+ mockLlmApi,
161+ {
162+ isHeadless: false,
163+ callbacks: mockCallbacks,
164+ },
165+ );
166+
167+ expect(logger.error).toHaveBeenCalledWith(
168+ expect.stringContaining("Auto-compaction error"),
169+ );
170+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
171+ expect.stringContaining("Warning: Auto-compaction error"),
172+ );
173+
174+ // Should return original history on error
175+ expect(result).toEqual({
176+ chatHistory: mockChatHistory,
177+ compactionIndex: null,
178+ });
179+ });
180+
181+ it("should not call system message callback in headless mode", async () => {
182+ const { shouldAutoCompact, getAutoCompactMessage } = await import(
183+ "./util/tokenizer.js"
184+ );
185+ const { compactChatHistory } = await import("./compaction.js");
186+
187+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
188+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
189+
190+ const mockCompactionResult = {
191+ compactedHistory: [
192+ { role: "system", content: "System" } as ChatCompletionMessageParam,
193+ ],
194+ compactionIndex: 0,
195+ compactionContent: "Summary",
196+ };
197+
198+ vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
199+
200+ const mockCallbacks = {
201+ onSystemMessage: vi.fn(),
202+ };
203+
204+ await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, {
205+ isHeadless: true,
206+ callbacks: mockCallbacks,
207+ });
208+
209+ expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled();
210+ });
211+
212+ it("should handle missing model gracefully", async () => {
213+ const result = await handleAutoCompaction(
214+ mockChatHistory,
215+ null as any,
216+ mockLlmApi,
217+ {},
218+ );
219+
220+ expect(result).toEqual({
221+ chatHistory: mockChatHistory,
222+ compactionIndex: null,
223+ });
224+ });
225+});
added extensions/cli/src/streamChatResponse.autoCompaction.ts +180 −0
@@ -0,0 +1,180 @@
1+import { ModelConfig } from "@continuedev/config-yaml";
2+import { BaseLlmApi } from "@continuedev/openai-adapters";
3+import type { ChatCompletionMessageParam } from "openai/resources.mjs";
4+import React from "react";
5+
6+import { compactChatHistory } from "./compaction.js";
7+import { saveSession } from "./session.js";
8+import { DisplayMessage } from "./ui/types.js";
9+import { formatError } from "./util/formatError.js";
10+import { logger } from "./util/logger.js";
11+import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
12+
13+interface AutoCompactionCallbacks {
14+ // For streaming mode
15+ onSystemMessage?: (message: string) => void;
16+ onContent?: (content: string) => void;
17+
18+ // For TUI mode
19+ setMessages?: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
20+ setChatHistory?: React.Dispatch<
21+ React.SetStateAction<ChatCompletionMessageParam[]>
22+ >;
23+ setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>;
24+
25+ // For headless mode - no callbacks needed, just return values
26+}
27+
28+interface AutoCompactionOptions {
29+ isHeadless?: boolean;
30+ format?: "json";
31+ callbacks?: AutoCompactionCallbacks;
32+}
33+
34+/**
35+ * Notify user about compaction start
36+ */
37+function notifyCompactionStart(
38+ message: string,
39+ isHeadless: boolean,
40+ callbacks?: AutoCompactionCallbacks,
41+) {
42+ if (isHeadless) return;
43+
44+ if (callbacks?.onSystemMessage) {
45+ callbacks.onSystemMessage(message);
46+ } else if (callbacks?.setMessages) {
47+ callbacks.setMessages((prev) => [
48+ ...prev,
49+ {
50+ role: "system",
51+ content: message,
52+ messageType: "system" as const,
53+ },
54+ ]);
55+ }
56+}
57+
58+/**
59+ * Handle successful compaction state updates
60+ */
61+function handleCompactionSuccess(
62+ result: any,
63+ isHeadless: boolean,
64+ callbacks?: AutoCompactionCallbacks,
65+) {
66+ if (isHeadless) return;
67+
68+ const successMessage = "✓ Chat history auto-compacted successfully.";
69+
70+ if (callbacks?.onSystemMessage) {
71+ callbacks.onSystemMessage(successMessage);
72+ } else if (
73+ callbacks?.setMessages &&
74+ callbacks?.setChatHistory &&
75+ callbacks?.setCompactionIndex
76+ ) {
77+ callbacks.setChatHistory(result.compactedHistory);
78+ callbacks.setCompactionIndex(result.compactionIndex);
79+ callbacks.setMessages((prev) => [
80+ ...prev,
81+ {
82+ role: "system",
83+ content: successMessage,
84+ messageType: "system" as const,
85+ },
86+ ]);
87+ }
88+}
89+
90+/**
91+ * Handle compaction error notification
92+ */
93+function handleCompactionError(
94+ error: any,
95+ isHeadless: boolean,
96+ callbacks?: AutoCompactionCallbacks,
97+) {
98+ const errorMessage = `Auto-compaction error: ${formatError(error)}`;
99+ logger.error(errorMessage);
100+
101+ if (isHeadless) return;
102+
103+ const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`;
104+
105+ if (callbacks?.onSystemMessage) {
106+ callbacks.onSystemMessage(warningMessage);
107+ } else if (callbacks?.setMessages) {
108+ callbacks.setMessages((prev) => [
109+ ...prev,
110+ {
111+ role: "system",
112+ content: warningMessage,
113+ messageType: "system" as const,
114+ },
115+ ]);
116+ }
117+}
118+
119+/**
120+ * Unified auto-compaction handler for all modes (streaming, TUI, headless)
121+ * @param chatHistory Current chat history
122+ * @param model Model configuration
123+ * @param llmApi LLM API instance
124+ * @param options Configuration options for different usage contexts
125+ * @returns Updated chat history and compaction index, or original if no compaction needed
126+ */
127+export async function handleAutoCompaction(
128+ chatHistory: ChatCompletionMessageParam[],
129+ model: ModelConfig,
130+ llmApi: BaseLlmApi,
131+ options: AutoCompactionOptions = {},
132+): Promise<{
133+ chatHistory: ChatCompletionMessageParam[];
134+ compactionIndex: number | null;
135+}> {
136+ const { isHeadless = false, callbacks } = options;
137+
138+ if (!model || !shouldAutoCompact(chatHistory, model)) {
139+ return { chatHistory, compactionIndex: null };
140+ }
141+
142+ logger.info(
143+ `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`,
144+ );
145+
146+ // Notify about compaction start
147+ notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
148+
149+ try {
150+ // Compact the history
151+ const result = await compactChatHistory(
152+ chatHistory,
153+ model,
154+ llmApi,
155+ isHeadless
156+ ? undefined
157+ : {
158+ onStreamContent: callbacks?.onContent,
159+ onStreamComplete: () => {},
160+ },
161+ );
162+
163+ // Save the compacted session
164+ saveSession(result.compactedHistory);
165+
166+ // Handle success notification
167+ handleCompactionSuccess(result, isHeadless, callbacks);
168+
169+ return {
170+ chatHistory: result.compactedHistory,
171+ compactionIndex: result.compactionIndex,
172+ };
173+ } catch (error: any) {
174+ // Handle error notification
175+ handleCompactionError(error, isHeadless, callbacks);
176+
177+ // Continue without compaction on error
178+ return { chatHistory, compactionIndex: null };
179+ }
180+}
modified extensions/cli/src/streamChatResponse.ts +19 −0
@@ -15,6 +15,7 @@
1515 SERVICE_NAMES,
1616 } from "./services/index.js";
1717 import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
18+import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
1819 import {
1920 executeStreamedToolCalls,
2021 preprocessStreamedToolCalls,
@@ -513,6 +514,24 @@
513514 return finalResponse || content || fullResponse;
514515 }
515516
517+ // Check for auto-compaction after tool execution
518+ if (shouldContinue) {
519+ const { chatHistory: updatedChatHistory, compactionIndex } =
520+ await handleAutoCompaction(chatHistory, model, llmApi, {
521+ isHeadless,
522+ callbacks: {
523+ onSystemMessage: callbacks?.onSystemMessage,
524+ onContent: callbacks?.onContent,
525+ },
526+ });
527+
528+ // Only update chat history if compaction actually occurred
529+ if (compactionIndex !== null && updatedChatHistory !== chatHistory) {
530+ chatHistory.length = 0;
531+ chatHistory.push(...updatedChatHistory);
532+ }
533+ }
534+
516535 // Check if we should continue
517536 if (!shouldContinue) {
518537 break;
modified extensions/cli/src/streamChatResponse.types.ts +1 −0
@@ -15,6 +15,7 @@
1515 requestId: string,
1616 preview?: ToolCallPreview[],
1717 ) => void;
18+ onSystemMessage?: (message: string) => void;
1819 }
1920
2021 export function getDefaultCompletionOptions(
modified extensions/cli/src/test-helpers/ui-test-context.ts +1 −1
@@ -72,7 +72,7 @@
7272 responseStartTime: null,
7373 inputMode: true,
7474 attachedFiles: [],
75- handleUserMessage: vi.fn(),
75+ handleUserMessage: vi.fn().mockResolvedValue(undefined),
7676 handleInterrupt: vi.fn(),
7777 handleFileAttached: vi.fn(),
7878 resetChatHistory: vi.fn(),
modified extensions/cli/src/tools/edit.ts +3 −1
@@ -1,5 +1,7 @@
11 import * as fs from "fs";
22
3+import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
4+
35 import { telemetryService } from "../telemetry/telemetryService.js";
46 import {
57 calculateLinesOfCodeDiff,
@@ -80,7 +82,7 @@
8082 new_string,
8183 replace_all = false,
8284 } = args as EditArgs;
83-
85+ throwIfFileIsSecurityConcern(file_path);
8486 // Check if file has been read
8587 if (!readFilesSet.has(file_path)) {
8688 throw new Error(
modified extensions/cli/src/tools/multiEdit.ts +4 −0
@@ -1,6 +1,8 @@
11 import * as fs from "fs";
22 import * as path from "path";
33
4+import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
5+
46 import { telemetryService } from "../telemetry/telemetryService.js";
57 import {
68 calculateLinesOfCodeDiff,
@@ -237,6 +239,8 @@
237239 // Validate and extract arguments
238240 const { original_path, file_path, edits } = validateMultiEditArgs(args);
239241
242+ throwIfFileIsSecurityConcern(file_path);
243+
240244 // Validate each edit operation
241245 validateEdits(edits);
242246
modified extensions/cli/src/tools/readFile.ts +10 −0
@@ -1,5 +1,7 @@
11 import * as fs from "fs";
22
3+import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
4+
35 import { markFileAsRead } from "./edit.js";
46 import { formatToolArgument } from "./formatters.js";
57 import { Tool } from "./types.js";
@@ -18,6 +20,7 @@
1820 readonly: true,
1921 isBuiltIn: true,
2022 preprocess: async (args) => {
23+ throwIfFileIsSecurityConcern(args.filepath);
2124 return {
2225 args,
2326 preview: [
@@ -36,6 +39,13 @@
3639 const content = fs.readFileSync(args.filepath, "utf-8");
3740 // Mark this file as read for the edit tool
3841 markFileAsRead(args.filepath);
42+
43+ const lines = content.split("\n");
44+ if (lines.length > 5000) {
45+ const truncatedContent = lines.slice(0, 5000).join("\n");
46+ return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`;
47+ }
48+
3949 return `Content of ${args.filepath}:\n${content}`;
4050 } catch (error) {
4151 return `Error reading file: ${
modified extensions/cli/src/ui/FreeTrialTransitionUI.tsx +2 −2
@@ -9,8 +9,8 @@
99 import { listUserOrganizations } from "../auth/workos.js";
1010 import { env } from "../env.js";
1111 import {
12- isValidAnthropicApiKey,
1312 getApiKeyValidationError,
13+ isValidAnthropicApiKey,
1414 } from "../util/apiKeyValidation.js";
1515 import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js";
1616
@@ -270,7 +270,7 @@
270270 <Text></Text>
271271 {errorMessage && <Text color="red">{errorMessage}</Text>}
272272 <Text color="gray">
273- Type your API key and press Enter (must start with 'TEST-ant-')
273+ Type your API key and press Enter (must start with 'sk-ant-')
274274 </Text>
275275 </Box>
276276 );
modified extensions/cli/src/ui/IntroMessage.tsx +3 −1
@@ -85,7 +85,9 @@
8585 {/* Rules */}
8686 {allRules.length > 0 && (
8787 <>
88- <Text color="blue">Rules:</Text>
88+ <Text bold color="blue">
89+ Rules:
90+ </Text>
8991 {allRules.map((rule, index) => (
9092 <Text key={index}>
9193 - <Text color="white">{rule}</Text>
modified extensions/cli/src/ui/UserInput.tsx +11 −0
@@ -152,6 +152,17 @@
152152 }
153153 }
154154
155+ // Check if there are any matching commands
156+ const filteredCommands = allCommands.filter((cmd) =>
157+ cmd.name.toLowerCase().includes(afterSlash.toLowerCase()),
158+ );
159+
160+ // If no commands match, hide the dropdown to allow normal Enter behavior
161+ if (filteredCommands.length === 0) {
162+ setShowSlashCommands(false);
163+ return;
164+ }
165+
155166 // Show selector for partial matches
156167 setShowSlashCommands(true);
157168 setSlashCommandFilter(afterSlash);
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +5 −2
@@ -20,7 +20,10 @@
2020 case "tool-start":
2121 return (
2222 <Box key={index} marginLeft={1} marginBottom={1}>
23- <Text color="white">○ {message.content}</Text>
23+ {/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */}
24+ <Text color="green">
25+ ●<Text color="white"> {message.content}</Text>
26+ </Text>
2427 </Box>
2528 );
2629
@@ -87,7 +90,7 @@
8790
8891 return (
8992 <Box key={index} marginLeft={1} marginBottom={1}>
90- <Text color={isUser ? "green" : "magenta"}>●</Text>
93+ <Text color={isUser ? "green" : "white"}>●</Text>
9194 <Text> </Text>
9295 {isUser ? (
9396 <Text color="gray">{message.content}</Text>
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +17 −66
@@ -7,7 +7,6 @@
77 import { telemetryService } from "../../telemetry/telemetryService.js";
88 import { formatError } from "../../util/formatError.js";
99 import { logger } from "../../util/logger.js";
10-import { shouldAutoCompact } from "../../util/tokenizer.js";
1110 import { DisplayMessage } from "../types.js";
1211
1312 import { SlashCommandResult } from "./useChat.types.js";
@@ -278,13 +277,13 @@
278277 }
279278
280279 /**
281- * Handle auto-compaction when approaching context limit
280+ * Handle auto-compaction when approaching context limit - TUI wrapper
282281 */
283282 export async function handleAutoCompaction({
284283 chatHistory,
285284 model,
286285 llmApi,
287- compactionIndex,
286+ compactionIndex: _compactionIndex,
288287 setMessages,
289288 setChatHistory,
290289 setCompactionIndex,
@@ -292,69 +291,21 @@
292291 currentChatHistory: ChatCompletionMessageParam[];
293292 currentCompactionIndex: number | null;
294293 }> {
295- if (!model || !shouldAutoCompact(chatHistory, model)) {
296- return {
297- currentChatHistory: chatHistory,
298- currentCompactionIndex: compactionIndex,
299- };
300- }
301-
302- logger.info("Auto-compacting triggered in TUI mode");
303-
304- setMessages((prev) => [
305- ...prev,
306- {
307- role: "system",
308- content: "Approaching context limit. Auto-compacting chat history...",
309- messageType: "system" as const,
294+ const { handleAutoCompaction: coreAutoCompaction } = await import(
295+ "../../streamChatResponse.autoCompaction.js"
296+ );
297+
298+ const result = await coreAutoCompaction(chatHistory, model, llmApi, {
299+ isHeadless: false,
300+ callbacks: {
301+ setMessages,
302+ setChatHistory,
303+ setCompactionIndex,
310304 },
311- ]);
312-
313- try {
314- if (!llmApi) {
315- throw new Error("LLM API is not available for auto-compaction");
316- }
317-
318- // Compact the history WITHOUT the current user message
319- const result = await compactChatHistory(chatHistory, model, llmApi);
320-
321- // Update state
322- setChatHistory(result.compactedHistory);
323- setCompactionIndex(result.compactionIndex);
324-
325- // Save the compacted session
326- saveSession(result.compactedHistory);
327-
328- setMessages((prev) => [
329- ...prev,
330- {
331- role: "system",
332- content: "✓ Chat history auto-compacted successfully.",
333- messageType: "system" as const,
334- },
335- ]);
336-
337- return {
338- currentChatHistory: result.compactedHistory,
339- currentCompactionIndex: result.compactionIndex,
340- };
341- } catch (error: any) {
342- const errorMessage = `Auto-compaction error: ${formatError(error)}`;
343- logger.error(errorMessage);
344-
345- setMessages((prev) => [
346- ...prev,
347- {
348- role: "system",
349- content: `Warning: ${errorMessage}. Continuing without compaction...`,
350- messageType: "system" as const,
351- },
352- ]);
305+ });
353306
354- // Continue without compaction on error
355- return {
356- currentChatHistory: chatHistory,
357- currentCompactionIndex: compactionIndex,
358- };
359- }
307+ return {
308+ currentChatHistory: result.chatHistory,
309+ currentCompactionIndex: result.compactionIndex,
310+ };
360311 }
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +10 −0
@@ -111,6 +111,16 @@
111111 toolCallPreview,
112112 });
113113 },
114+ onSystemMessage: (message: string) => {
115+ setMessages((prev) => [
116+ ...prev,
117+ {
118+ role: "system",
119+ content: message,
120+ messageType: "system" as const,
121+ },
122+ ]);
123+ },
114124 };
115125 }
116126
modified extensions/cli/src/util/apiKeyValidation.test.ts +10 −10
@@ -1,21 +1,21 @@
11 import {
2- isValidAnthropicApiKey,
32 getApiKeyValidationError,
3+ isValidAnthropicApiKey,
44 } from "./apiKeyValidation.js";
55
66 describe("isValidAnthropicApiKey", () => {
77 it("should return true for valid API keys", () => {
8- expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
9- expect(isValidAnthropicApiKey("TEST-ant-abcdefghijklmnop")).toBe(true);
10- expect(isValidAnthropicApiKey("TEST-ant-test-key-with-dashes")).toBe(true);
8+ expect(isValidAnthropicApiKey("sk-ant-1234567890")).toBe(true);
9+ expect(isValidAnthropicApiKey("sk-ant-abcdefghijklmnop")).toBe(true);
10+ expect(isValidAnthropicApiKey("sk-ant-test-key-with-dashes")).toBe(true);
1111 expect(
12- isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
12+ isValidAnthropicApiKey("sk-ant-api03_T3BlbkFJ1234567890abcdef"),
1313 ).toBe(true);
1414 });
1515
1616 it("should return false for invalid API keys", () => {
1717 expect(isValidAnthropicApiKey("")).toBe(false);
18- expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
18+ expect(isValidAnthropicApiKey("sk-ant-")).toBe(false);
1919 expect(isValidAnthropicApiKey("TEST-")).toBe(false);
2020 expect(isValidAnthropicApiKey("TEST-openai-1234567890")).toBe(false);
2121 expect(isValidAnthropicApiKey("invalid-key")).toBe(false);
@@ -40,14 +40,14 @@
4040 expect(getApiKeyValidationError(null)).toBe("API key is required");
4141 expect(getApiKeyValidationError(undefined)).toBe("API key is required");
4242 expect(getApiKeyValidationError("TEST-")).toBe(
43- 'API key must start with "TEST-ant-"',
43+ 'API key must start with "sk-ant-"',
4444 );
4545 expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
46- 'API key must start with "TEST-ant-"',
46+ 'API key must start with "sk-ant-"',
4747 );
48- expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
48+ expect(getApiKeyValidationError("sk-ant-")).toBe("API key is too short");
4949 expect(getApiKeyValidationError("invalid")).toBe(
50- 'API key must start with "TEST-ant-"',
50+ 'API key must start with "sk-ant-"',
5151 );
5252 });
5353 });
modified extensions/cli/src/util/apiKeyValidation.ts +5 −5
@@ -10,8 +10,8 @@
1010 return false;
1111 }
1212
13- // Anthropic API keys must start with "TEST-ant-" and have additional characters
14- return apiKey.startsWith("TEST-ant-") && apiKey.length > "TEST-ant-".length;
13+ // Anthropic API keys must start with "sk-ant-" and have additional characters
14+ return apiKey.startsWith("sk-ant-") && apiKey.length > "sk-ant-".length;
1515 }
1616
1717 /**
@@ -26,11 +26,11 @@
2626 return "API key is required";
2727 }
2828
29- if (!apiKey.startsWith("TEST-ant-")) {
30- return 'API key must start with "TEST-ant-"';
29+ if (!apiKey.startsWith("sk-ant-")) {
30+ return 'API key must start with "sk-ant-"';
3131 }
3232
33- if (apiKey.length <= "TEST-ant-".length) {
33+ if (apiKey.length <= "sk-ant-".length) {
3434 return "API key is too short";
3535 }
3636
deleted extensions/cli/src/util/consoleOverride.ts +0 −115
@@ -1,115 +0,0 @@
1-/**
2- * Console override utility to prevent unwanted output in headless mode
3- * This ensures that only intentional stdout output reaches the user
4- */
5-
6-interface ConsoleBackup {
7- log: typeof console.log;
8- info: typeof console.info;
9- warn: typeof console.warn;
10- error: typeof console.error;
11- debug: typeof console.debug;
12-}
13-
14-let originalConsole: ConsoleBackup | null = null;
15-let isHeadlessMode = false;
16-
17-/**
18- * Override console methods to prevent unwanted output in headless mode
19- * In headless mode, only console.error and explicitly allowed outputs should reach stdout
20- */
21-export function configureConsoleForHeadless(headless: boolean): void {
22- isHeadlessMode = headless;
23-
24- if (headless && !originalConsole) {
25- // Backup original console methods
26- originalConsole = {
27- log: console.log,
28- info: console.info,
29- warn: console.warn,
30- error: console.error,
31- debug: console.debug,
32- };
33-
34- // Override console methods to suppress output in headless mode
35- console.log = () => {}; // Suppress all console.log
36- console.info = () => {}; // Suppress all console.info
37- console.warn = () => {}; // Suppress all console.warn
38- console.debug = () => {}; // Suppress all console.debug
39-
40- // Keep console.error for genuine errors, but send to stderr
41- console.error = (...args: any[]) => {
42- originalConsole!.error(...args);
43- };
44- } else if (!headless && originalConsole) {
45- // Restore original console methods
46- console.log = originalConsole.log;
47- console.info = originalConsole.info;
48- console.warn = originalConsole.warn;
49- console.error = originalConsole.error;
50- console.debug = originalConsole.debug;
51-
52- originalConsole = null;
53- }
54-}
55-
56-/**
57- * Safe stdout output that bypasses console overrides
58- * Use this for intentional output in headless mode
59- */
60-export function safeStdout(message: string): void {
61- process.stdout.write(message);
62-}
63-
64-/**
65- * Safe stderr output that bypasses console overrides
66- * Use this for error messages that should always be visible
67- */
68-export function safeStderr(message: string): void {
69- process.stderr.write(message);
70-}
71-
72-/**
73- * Temporarily restore console for a specific operation
74- * Useful for debugging or when you need original console behavior
75- */
76-export function withOriginalConsole<T>(fn: () => T): T {
77- if (!originalConsole || !isHeadlessMode) {
78- return fn();
79- }
80-
81- // Temporarily restore
82- const tempConsole = { ...console };
83- Object.assign(console, originalConsole);
84-
85- try {
86- return fn();
87- } finally {
88- // Restore overrides
89- Object.assign(console, tempConsole);
90- }
91-}
92-
93-/**
94- * Check if currently in headless mode
95- */
96-export function isInHeadlessMode(): boolean {
97- return isHeadlessMode;
98-}
99-
100-/**
101- * Reset console overrides to original state
102- * Useful for testing to ensure clean state
103- */
104-export function resetConsoleOverrides(): void {
105- if (originalConsole) {
106- console.log = originalConsole.log;
107- console.info = originalConsole.info;
108- console.warn = originalConsole.warn;
109- console.error = originalConsole.error;
110- console.debug = originalConsole.debug;
111-
112- originalConsole = null;
113- }
114- isHeadlessMode = false;
115-}
added extensions/cli/src/util/tokenizer.test.ts +292 −0
@@ -0,0 +1,292 @@
1+import { ModelConfig } from "@continuedev/config-yaml";
2+import { ChatCompletionMessageParam } from "openai/resources.mjs";
3+import { beforeEach, describe, expect, it, vi } from "vitest";
4+
5+import { logger } from "./logger.js";
6+import {
7+ AUTO_COMPACT_THRESHOLD,
8+ calculateContextUsagePercentage,
9+ countChatHistoryTokens,
10+ countMessageTokens,
11+ getModelContextLimit,
12+ shouldAutoCompact,
13+} from "./tokenizer.js";
14+
15+// Mock the logger
16+vi.mock("./logger.js", () => ({
17+ logger: {
18+ debug: vi.fn(),
19+ warn: vi.fn(),
20+ error: vi.fn(),
21+ },
22+}));
23+
24+// Mock gpt-tokenizer
25+vi.mock("gpt-tokenizer", () => ({
26+ encode: (text: string) => new Array(Math.ceil(text.length / 4)), // Rough 4 chars per token
27+}));
28+
29+describe("tokenizer", () => {
30+ beforeEach(() => {
31+ vi.clearAllMocks();
32+ });
33+
34+ describe("getModelContextLimit", () => {
35+ it("should return contextLength from model config", () => {
36+ const model: ModelConfig = {
37+ name: "test-model",
38+ model: "test",
39+ provider: "openai",
40+ defaultCompletionOptions: {
41+ contextLength: 8192,
42+ },
43+ };
44+
45+ expect(getModelContextLimit(model)).toBe(8192);
46+ });
47+
48+ it("should return default when no contextLength specified", () => {
49+ const model: ModelConfig = {
50+ name: "test-model",
51+ model: "test",
52+ provider: "openai",
53+ };
54+
55+ expect(getModelContextLimit(model)).toBe(200_000);
56+ });
57+ });
58+
59+ describe("countMessageTokens", () => {
60+ it("should count tokens for string content", () => {
61+ const message: ChatCompletionMessageParam = {
62+ role: "user",
63+ content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5
64+ };
65+
66+ const tokenCount = countMessageTokens(message);
67+ expect(tokenCount).toBeGreaterThan(0);
68+ expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens
69+ });
70+
71+ it("should count tokens for array content", () => {
72+ const message: ChatCompletionMessageParam = {
73+ role: "user",
74+ content: [
75+ { type: "text", text: "Hello" }, // 5 chars -> ~2 tokens
76+ { type: "image_url", image_url: { url: "test.jpg" } }, // +85 tokens
77+ ],
78+ };
79+
80+ const tokenCount = countMessageTokens(message);
81+ expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens
82+ });
83+
84+ it("should count tokens for tool calls", () => {
85+ const message: ChatCompletionMessageParam = {
86+ role: "assistant",
87+ content: "I'll help you",
88+ tool_calls: [
89+ {
90+ id: "call_1",
91+ type: "function",
92+ function: {
93+ name: "test_function", // ~3 tokens + 10 overhead
94+ arguments: '{"param": "value"}', // ~5 tokens
95+ },
96+ },
97+ ],
98+ };
99+
100+ const tokenCount = countMessageTokens(message);
101+ expect(tokenCount).toBeGreaterThan(20);
102+ });
103+
104+ it("should handle errors gracefully", () => {
105+ // We'll skip this test for now since mocking gpt-tokenizer is complex
106+ // The error handling is tested implicitly by the fallback behavior
107+ expect(true).toBe(true);
108+ });
109+ });
110+
111+ describe("countChatHistoryTokens", () => {
112+ it("should count tokens for multiple messages", () => {
113+ const chatHistory: ChatCompletionMessageParam[] = [
114+ { role: "system", content: "You are helpful" },
115+ { role: "user", content: "Hello" },
116+ { role: "assistant", content: "Hi there" },
117+ ];
118+
119+ const tokenCount = countChatHistoryTokens(chatHistory);
120+ expect(tokenCount).toBeGreaterThan(0);
121+ // Should include message overhead (3 * 3 = 9 tokens)
122+ expect(tokenCount).toBeGreaterThan(9);
123+ });
124+
125+ it("should handle empty chat history", () => {
126+ const tokenCount = countChatHistoryTokens([]);
127+ expect(tokenCount).toBe(0);
128+ });
129+ });
130+
131+ describe("calculateContextUsagePercentage", () => {
132+ it("should calculate percentage correctly", () => {
133+ const model: ModelConfig = {
134+ name: "test-model",
135+ model: "test",
136+ provider: "openai",
137+ defaultCompletionOptions: {
138+ contextLength: 1000,
139+ },
140+ };
141+
142+ expect(calculateContextUsagePercentage(800, model)).toBe(80);
143+ expect(calculateContextUsagePercentage(500, model)).toBe(50);
144+ expect(calculateContextUsagePercentage(1200, model)).toBe(100); // Capped at 100%
145+ });
146+ });
147+
148+ describe("shouldAutoCompact", () => {
149+ const createModel = (
150+ contextLength: number,
151+ maxTokens?: number,
152+ ): ModelConfig => ({
153+ name: "test-model",
154+ model: "test",
155+ provider: "openai",
156+ defaultCompletionOptions: {
157+ contextLength,
158+ maxTokens,
159+ },
160+ });
161+
162+ const createChatHistory = (
163+ tokenCount: number,
164+ ): ChatCompletionMessageParam[] => {
165+ // Create a message that will result in approximately the desired token count
166+ const content = "x".repeat(tokenCount * 4); // 4 chars per token
167+ return [{ role: "user", content }];
168+ };
169+
170+ it("should compact when input tokens exceed threshold with maxTokens", () => {
171+ const model = createModel(1000, 200); // 1000 context, 200 max output
172+ // Available for input: 1000 - 200 = 800
173+ // Threshold: 800 * 0.8 = 640
174+ const chatHistory = createChatHistory(650); // Above threshold
175+
176+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
177+ });
178+
179+ it("should not compact when input tokens are below threshold with maxTokens", () => {
180+ const model = createModel(1000, 200); // 1000 context, 200 max output
181+ // Available for input: 1000 - 200 = 800
182+ // Threshold: 800 * 0.8 = 640
183+ const chatHistory = createChatHistory(600); // Below threshold
184+
185+ expect(shouldAutoCompact(chatHistory, model)).toBe(false);
186+ });
187+
188+ it("should use 35% default reservation when maxTokens is not set", () => {
189+ const model = createModel(1000); // No maxTokens
190+ // Reserved: 1000 * 0.35 = 350
191+ // Available for input: 1000 - 350 = 650
192+ // Threshold: 650 * 0.8 = 520
193+ const chatHistory = createChatHistory(530); // Above threshold
194+
195+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
196+ });
197+
198+ it("should not compact when below default threshold without maxTokens", () => {
199+ const model = createModel(1000); // No maxTokens
200+ // Available for input: 1000 - 350 = 650
201+ // Threshold: 650 * 0.8 = 520
202+ const chatHistory = createChatHistory(500); // Below threshold
203+
204+ expect(shouldAutoCompact(chatHistory, model)).toBe(false);
205+ });
206+
207+ it("should throw error when maxTokens >= contextLength", () => {
208+ const model = createModel(1000, 1000); // maxTokens equals contextLength
209+ const chatHistory = createChatHistory(1); // Minimal input
210+
211+ expect(() => shouldAutoCompact(chatHistory, model)).toThrow(
212+ "max_tokens is larger than context_length, which should not be possible. Please check your configuration.",
213+ );
214+ });
215+
216+ it("should throw error when maxTokens > contextLength", () => {
217+ const model = createModel(1000, 1200); // maxTokens exceeds contextLength
218+ const chatHistory = createChatHistory(1); // Minimal input
219+
220+ expect(() => shouldAutoCompact(chatHistory, model)).toThrow(
221+ "max_tokens is larger than context_length, which should not be possible. Please check your configuration.",
222+ );
223+ });
224+
225+ it("should handle edge case with very small context limit", () => {
226+ const model = createModel(100, 50); // Small context
227+ // Available: 100 - 50 = 50
228+ // Threshold: 50 * 0.8 = 40
229+ const chatHistory = createChatHistory(45); // Above threshold
230+
231+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
232+ });
233+
234+ it("should log debug information correctly", () => {
235+ const model = createModel(1000, 200);
236+ const chatHistory = createChatHistory(600);
237+
238+ shouldAutoCompact(chatHistory, model);
239+
240+ expect(logger.debug).toHaveBeenCalledWith("Context usage check", {
241+ inputTokens: expect.any(Number),
242+ contextLimit: 1000,
243+ maxTokens: 200,
244+ reservedForOutput: 200,
245+ availableForInput: 800,
246+ usage: expect.any(String),
247+ threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`,
248+ shouldCompact: expect.any(Boolean),
249+ });
250+ });
251+
252+ it("should handle model with zero maxTokens correctly", () => {
253+ const model = createModel(1000, 0); // Explicit zero
254+ // Should use default 35% reservation: 1000 * 0.35 = 350
255+ const chatHistory = createChatHistory(530); // Above threshold
256+
257+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
258+ });
259+
260+ describe("real-world scenarios", () => {
261+ it("should prevent Claude 3.5 Sonnet context overflow", () => {
262+ // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens
263+ const model = createModel(200_000, 4_000);
264+ // Available: 200k - 4k = 196k
265+ // Threshold: 196k * 0.8 = 156.8k
266+ const chatHistory = createChatHistory(160_000); // Above threshold
267+
268+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
269+ });
270+
271+ it("should prevent GPT-4 context overflow", () => {
272+ // GPT-4: 128k context, often uses 4k max_tokens
273+ const model = createModel(128_000, 4_000);
274+ // Available: 128k - 4k = 124k
275+ // Threshold: 124k * 0.8 = 99.2k
276+ const chatHistory = createChatHistory(100_000); // Above threshold
277+
278+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
279+ });
280+
281+ it("should handle models with very high max_tokens", () => {
282+ // Some models allow very high max_tokens (e.g., 64k like in the error message)
283+ const model = createModel(200_000, 64_000);
284+ // Available: 200k - 64k = 136k
285+ // Threshold: 136k * 0.8 = 108.8k
286+ const chatHistory = createChatHistory(110_000); // Above threshold
287+
288+ expect(shouldAutoCompact(chatHistory, model)).toBe(true);
289+ });
290+ });
291+ });
292+});
modified extensions/cli/src/util/tokenizer.ts +35 −6
@@ -117,20 +117,39 @@
117117 /**
118118 * Check if the chat history exceeds the auto-compact threshold
119119 * @param chatHistory The chat history to check
120- * @param modelName The model name
120+ * @param model The model configuration
121121 * @returns Whether auto-compacting should be triggered
122122 */
123123 export function shouldAutoCompact(
124124 chatHistory: ChatCompletionMessageParam[],
125125 model: ModelConfig,
126126 ): boolean {
127- const tokenCount = countChatHistoryTokens(chatHistory);
128- const limit = getModelContextLimit(model);
129- const usage = tokenCount / limit;
127+ const inputTokens = countChatHistoryTokens(chatHistory);
128+ const contextLimit = getModelContextLimit(model);
129+ const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
130+
131+ // Calculate available space considering max_tokens reservation
132+ // If maxTokens is not set, reserve 35% of context for output as a safe default
133+ // (64k/200k with claude = 32%, round up to give a buffer)
134+ const reservedForOutput =
135+ maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
136+ const availableForInput = contextLimit - reservedForOutput;
137+
138+ // Ensure we have positive space available for input
139+ if (availableForInput <= 0) {
140+ throw new Error(
141+ `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`,
142+ );
143+ }
144+
145+ const usage = inputTokens / availableForInput;
130146
131147 logger.debug("Context usage check", {
132- tokenCount,
133- limit,
148+ inputTokens,
149+ contextLimit,
150+ maxTokens,
151+ reservedForOutput,
152+ availableForInput,
134153 usage: `${Math.round(usage * 100)}%`,
135154 threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`,
136155 shouldCompact: usage >= AUTO_COMPACT_THRESHOLD,
@@ -138,3 +157,13 @@
138157
139158 return usage >= AUTO_COMPACT_THRESHOLD;
140159 }
160+
161+/**
162+ * Get a descriptive message for auto-compaction that shows the context limit
163+ * @param model The model configuration
164+ * @returns A descriptive message explaining why compaction is needed
165+ */
166+export function getAutoCompactMessage(model: ModelConfig): string {
167+ const limit = getModelContextLimit(model);
168+ return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`;
169+}
modified extensions/cli/src/util/yamlConfigUpdater.test.ts +13 −13
@@ -3,7 +3,7 @@
33 import { updateAnthropicModelInYaml } from "./yamlConfigUpdater.js";
44
55 describe("updateAnthropicModelInYaml", () => {
6- const testApiKey = "TEST-ant-test123456789";
6+ const testApiKey = "sk-ant-test123456789";
77
88 describe("empty or invalid input", () => {
99 it("should create new config from empty string", () => {
@@ -13,7 +13,7 @@
1313 expect(result).toContain("version: 1.0.0");
1414 expect(result).toContain("schema: v1");
1515 expect(result).toContain("uses: anthropic/claude-4-sonnet");
16- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
16+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
1717 });
1818
1919 it("should create new config from invalid YAML", () => {
@@ -22,7 +22,7 @@
2222
2323 expect(result).toContain("name: Local Config");
2424 expect(result).toContain("uses: anthropic/claude-4-sonnet");
25- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
25+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
2626 });
2727 });
2828
@@ -45,7 +45,7 @@
4545 expect(result).toContain("# List of available models");
4646 expect(result).toContain("uses: openai/gpt-4");
4747 expect(result).toContain("uses: anthropic/claude-4-sonnet");
48- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
48+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
4949 });
5050
5151 it("should preserve comments when updating existing model", () => {
@@ -65,7 +65,7 @@
6565 expect(result).toContain("# My Continue config");
6666 expect(result).toContain("# List of available models");
6767 expect(result).toContain("uses: anthropic/claude-4-sonnet");
68- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
68+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
6969 expect(result).not.toContain("old-key");
7070 });
7171 });
@@ -85,7 +85,7 @@
8585
8686 expect(result).toContain("uses: openai/gpt-4");
8787 expect(result).toContain("uses: anthropic/claude-4-sonnet");
88- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
88+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
8989 expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
9090 });
9191
@@ -106,7 +106,7 @@
106106
107107 expect(result).toContain("uses: anthropic/claude-4-sonnet");
108108 expect(result).toContain("uses: openai/gpt-4");
109- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
109+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
110110 expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
111111 expect(result).not.toContain("old-anthropic-key");
112112
@@ -131,7 +131,7 @@
131131 expect(result).toContain("name: Local Config");
132132 expect(result).toContain("models:");
133133 expect(result).toContain("uses: anthropic/claude-4-sonnet");
134- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
134+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
135135 });
136136
137137 it("should handle config with empty models array", () => {
@@ -148,7 +148,7 @@
148148
149149 expect(result).toContain("name: Local Config");
150150 expect(result).toContain("uses: anthropic/claude-4-sonnet");
151- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
151+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
152152 });
153153 });
154154
@@ -190,14 +190,14 @@
190190 const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
191191
192192 expect(result).toContain("uses: anthropic/claude-4-sonnet");
193- expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
193+ expect(result).toContain("ANTHROPIC_API_KEY: sk-ant-test123456789");
194194 });
195195
196196 it("should handle different API key formats", () => {
197197 const differentKeys = [
198- "TEST-ant-1234567890",
199- "TEST-ant-abcdefghijklmnop",
200- "TEST-ant-test-key-with-dashes",
198+ "sk-ant-1234567890",
199+ "sk-ant-abcdefghijklmnop",
200+ "sk-ant-test-key-with-dashes",
201201 ];
202202
203203 differentKeys.forEach((key) => {
added extensions/cli/stubs/react-devtools-core.js +6 −0
@@ -0,0 +1,6 @@
1+// Stub for react-devtools-core to prevent errors when it's not installed
2+export default {
3+ connectToDevTools: () => {
4+ // No-op - devtools not available in production bundle
5+ },
6+};
added extensions/cli/validate-aliases.mjs +188 −0
@@ -0,0 +1,188 @@
1+#!/usr/bin/env node
2+
3+import { readFileSync, existsSync } from "fs";
4+import { resolve, dirname } from "path";
5+import { fileURLToPath } from "url";
6+
7+const __dirname = dirname(fileURLToPath(import.meta.url));
8+
9+// Colors for output
10+const colors = {
11+ green: "\x1b[32m",
12+ red: "\x1b[31m",
13+ yellow: "\x1b[33m",
14+ blue: "\x1b[34m",
15+ reset: "\x1b[0m",
16+};
17+
18+/**
19+ * Parse the build.mjs file to extract defined aliases
20+ */
21+function getDefinedAliases() {
22+ const buildPath = resolve(__dirname, "build.mjs");
23+ const buildContent = readFileSync(buildPath, "utf8");
24+
25+ // Find the alias object in the build file
26+ const aliasMatch = buildContent.match(/alias:\s*{([^}]+)}/s);
27+ if (!aliasMatch) {
28+ console.warn(`${colors.yellow}Warning: No aliases found in build.mjs${colors.reset}`);
29+ return new Set();
30+ }
31+
32+ // Extract package names from the alias definitions
33+ // Split by lines and filter out comments
34+ const aliasBlock = aliasMatch[1];
35+ const lines = aliasBlock.split('\n');
36+ const aliases = new Set();
37+
38+ for (const line of lines) {
39+ // Skip commented lines
40+ if (line.trim().startsWith('//')) {
41+ continue;
42+ }
43+
44+ // Look for package names in non-commented lines
45+ // Match both quoted and unquoted keys
46+ const quotedMatch = line.match(/"([^"]+)":/);
47+ const unquotedMatch = line.match(/\s+([a-zA-Z@][a-zA-Z0-9@\/_-]*)\s*:/);
48+
49+ if (quotedMatch) {
50+ aliases.add(quotedMatch[1]);
51+ } else if (unquotedMatch && !unquotedMatch[1].includes('__dirname') && unquotedMatch[1] !== 'js') {
52+ aliases.add(unquotedMatch[1]);
53+ }
54+ }
55+
56+ return aliases;
57+}
58+
59+/**
60+ * Find all local packages referenced with file: in package.json files
61+ */
62+function findLocalPackages(startPath, visited = new Set()) {
63+ const localPackages = new Set();
64+
65+ function scanPackageJson(packageJsonPath, depth = 0) {
66+ // Avoid infinite recursion
67+ if (visited.has(packageJsonPath) || depth > 10) {
68+ return;
69+ }
70+ visited.add(packageJsonPath);
71+
72+ if (!existsSync(packageJsonPath)) {
73+ return;
74+ }
75+
76+ try {
77+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
78+ const packageDir = dirname(packageJsonPath);
79+
80+ // Check both dependencies and devDependencies
81+ const allDeps = {
82+ ...packageJson.dependencies,
83+ ...packageJson.devDependencies,
84+ };
85+
86+ for (const [depName, depVersion] of Object.entries(allDeps)) {
87+ if (typeof depVersion === "string" && depVersion.startsWith("file:")) {
88+ // This is a local package
89+ localPackages.add(depName);
90+
91+ // Recursively check this package's dependencies
92+ const depPath = resolve(packageDir, depVersion.replace("file:", ""));
93+ const depPackageJson = resolve(depPath, "package.json");
94+
95+ if (existsSync(depPackageJson)) {
96+ scanPackageJson(depPackageJson, depth + 1);
97+ }
98+ }
99+ }
100+ } catch (error) {
101+ console.error(`${colors.red}Error reading ${packageJsonPath}: ${error.message}${colors.reset}`);
102+ }
103+ }
104+
105+ // Start from the CLI's package.json
106+ scanPackageJson(startPath);
107+
108+ return localPackages;
109+}
110+
111+/**
112+ * Main validation function
113+ */
114+function validateAliases() {
115+ console.log(`${colors.blue}🔍 Validating esbuild aliases...${colors.reset}\n`);
116+
117+ // Get defined aliases from build.mjs
118+ const definedAliases = getDefinedAliases();
119+ console.log(`Found ${definedAliases.size} aliases in build.mjs:`);
120+ definedAliases.forEach(alias => {
121+ console.log(` ✓ ${alias}`);
122+ });
123+ console.log();
124+
125+ // Find all local packages that need aliases
126+ const cliPackageJson = resolve(__dirname, "package.json");
127+ const localPackages = findLocalPackages(cliPackageJson);
128+ console.log(`Found ${localPackages.size} local package dependencies:`);
129+ localPackages.forEach(pkg => {
130+ console.log(` • ${pkg}`);
131+ });
132+ console.log();
133+
134+ // Check for missing aliases
135+ const missingAliases = [];
136+ for (const pkg of localPackages) {
137+ if (!definedAliases.has(pkg)) {
138+ missingAliases.push(pkg);
139+ }
140+ }
141+
142+ // Check for unnecessary aliases (defined but not used)
143+ const unnecessaryAliases = [];
144+ for (const alias of definedAliases) {
145+ if (!localPackages.has(alias)) {
146+ unnecessaryAliases.push(alias);
147+ }
148+ }
149+
150+ // Report results
151+ if (missingAliases.length > 0) {
152+ console.log(`${colors.red}❌ Missing aliases (WILL CAUSE RUNTIME ERRORS):${colors.reset}`);
153+ missingAliases.forEach(pkg => {
154+ console.log(` ✗ ${pkg}`);
155+ });
156+ console.log();
157+ console.log(`${colors.red}Add these to the alias section in build.mjs:${colors.reset}`);
158+ missingAliases.forEach(pkg => {
159+ const packageName = pkg.replace("@continuedev/", "").replace(/-/g, "_");
160+ console.log(` "${pkg}": resolve(__dirname, "../../packages/${pkg.replace("@continuedev/", "")}/dist/index.js"),`);
161+ });
162+ console.log();
163+ }
164+
165+ if (unnecessaryAliases.length > 0) {
166+ console.log(`${colors.yellow}⚠️ Potentially unnecessary aliases:${colors.reset}`);
167+ unnecessaryAliases.forEach(alias => {
168+ console.log(` ? ${alias}`);
169+ });
170+ console.log();
171+ }
172+
173+ // Exit with appropriate code
174+ if (missingAliases.length > 0) {
175+ console.log(`${colors.red}✗ Validation failed! Missing ${missingAliases.length} required alias(es).${colors.reset}`);
176+ console.log(`${colors.red}This would cause runtime errors in the bundled CLI.${colors.reset}`);
177+ process.exit(1);
178+ } else if (unnecessaryAliases.length > 0) {
179+ console.log(`${colors.yellow}✓ Validation passed with warnings.${colors.reset}`);
180+ process.exit(0);
181+ } else {
182+ console.log(`${colors.green}✅ All aliases are correctly configured!${colors.reset}`);
183+ process.exit(0);
184+ }
185+}
186+
187+// Run validation
188+validateAliases();
No newline at the end of the file
modified extensions/cli/vitest.setup.ts +1 −1
@@ -1,6 +1,6 @@
11 import { vi } from "vitest";
22
3-import { resetConsoleOverrides } from "./src/util/consoleOverride.js";
3+import { resetConsoleOverrides } from "./src/init.js";
44
55 // Disable telemetry for tests
66 process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";
modified extensions/intellij/gradle.properties +1 −1
@@ -1,5 +1,5 @@
11 pluginGroup=com.github.continuedev.continueintellijextension
2-pluginVersion=1.0.38
2+pluginVersion=1.0.40
33 platformVersion=2024.1
44 kotlin.stdlib.default.dependency=false
55 org.gradle.configuration-cache=true
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.79",
5+ "version": "1.3.1",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
modified extensions/vscode/src/activation/NextEditWindowManager.ts +101 −21
@@ -122,6 +122,11 @@
122122 private editableRegionStartLine: number = 0;
123123 private editableRegionEndLine: number = 0;
124124
125+ // State tracking for key reservation.
126+ // By default it is set to free, and is only set to reserved when the transition is done.
127+ private keyReservationState: "free" | "reserved" | "transitioning" = "free";
128+ private latestOperationId = 0;
129+
125130 // Disposables
126131 private disposables: vscode.Disposable[] = [];
127132
@@ -170,20 +175,71 @@
170175 this.loggingService = NextEditLoggingService.getInstance();
171176 }
172177
178+ // This is an implementation of last-action-wins.
179+ // For each action that fires setKeyReservation, it keeps its own operationId while incrementing latestOperationId.
180+ // When an action completes, checking for operationId === latestOperationId will determine which one came last.
181+ private async setKeyReservation(reserve: boolean): Promise<void> {
182+ // Increment and capture this operation's ID.
183+ const operationId = ++this.latestOperationId;
184+
185+ // Return early when already in desired state.
186+ if (
187+ (reserve && this.keyReservationState === "reserved") ||
188+ (!reserve && this.keyReservationState === "free")
189+ ) {
190+ return;
191+ }
192+
193+ try {
194+ await this.performKeyReservation(reserve);
195+
196+ // Only update state if we're still the latest operation.
197+ if (operationId === this.latestOperationId) {
198+ this.keyReservationState = reserve ? "reserved" : "free";
199+ }
200+ } catch (err) {
201+ console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
202+
203+ // Only reset to free if we're still the latest operation.
204+ if (operationId === this.latestOperationId) {
205+ this.keyReservationState = "free";
206+ }
207+ throw err;
208+ }
209+ }
210+
211+ public async resetKeyReservation(): Promise<void> {
212+ // Reset internal tracking.
213+ this.keyReservationState = "free";
214+ this.latestOperationId = 0;
215+
216+ // Ensure VS Code context matches.
217+ try {
218+ await this.performKeyReservation(false);
219+ } catch (err) {
220+ console.error(`Failed to reset nextEditWindowActive context: ${err}`);
221+ }
222+ }
223+
224+ private async performKeyReservation(reserve: boolean): Promise<void> {
225+ try {
226+ await vscode.commands.executeCommand(
227+ "setContext",
228+ "nextEditWindowActive",
229+ reserve,
230+ );
231+ } catch (err) {
232+ console.error(`Failed to set nextEditWindowActive to ${reserve}: ${err}`);
233+ throw err;
234+ }
235+ }
236+
173237 public static async reserveTabAndEsc() {
174- await vscode.commands.executeCommand(
175- "setContext",
176- "nextEditWindowActive",
177- true,
178- );
238+ await NextEditWindowManager.getInstance().setKeyReservation(true);
179239 }
180240
181241 public static async freeTabAndEsc() {
182- await vscode.commands.executeCommand(
183- "setContext",
184- "nextEditWindowActive",
185- false,
186- );
242+ await NextEditWindowManager.getInstance().setKeyReservation(false);
187243 }
188244
189245 /**
@@ -202,7 +258,8 @@
202258
203259 // Set nextEditWindowActive to false to free esc and tab,
204260 // letting them return to their original behaviors.
205- await NextEditWindowManager.freeTabAndEsc();
261+ await this.resetKeyReservation();
262+ // await NextEditWindowManager.freeTabAndEsc();
206263
207264 // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks.
208265 this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => {
@@ -353,14 +410,21 @@
353410
354411 // Create and apply decoration with the text.
355412 if (newEditRangeSlice !== "") {
356- await this.renderWindow(
357- editor,
358- currCursorPos,
359- oldEditRangeSlice,
360- newEditRangeSlice,
361- this.editableRegionStartLine,
362- diffLines,
363- );
413+ try {
414+ await this.renderWindow(
415+ editor,
416+ currCursorPos,
417+ oldEditRangeSlice,
418+ newEditRangeSlice,
419+ this.editableRegionStartLine,
420+ diffLines,
421+ );
422+ } catch (error) {
423+ console.error("Failed to render window:", error);
424+ // Clean up and reset state.
425+ await this.hideAllNextEditWindows();
426+ return;
427+ }
364428 }
365429
366430 const diffChars = myersCharDiff(oldEditRangeSlice, newEditRangeSlice);
@@ -368,14 +432,26 @@
368432 this.renderDeletions(editor, diffChars);
369433
370434 // Reserve tab and esc to either accept or reject the displayed next edit contents.
371- await NextEditWindowManager.reserveTabAndEsc();
435+ try {
436+ await NextEditWindowManager.reserveTabAndEsc();
437+ } catch (err) {
438+ console.error(
439+ `Error reserving Tab/Esc after showing decorations: ${err}`,
440+ );
441+ await this.hideAllNextEditWindows();
442+ return;
443+ }
372444 }
373445
374446 /**
375447 * Hide all tooltips in all editors.
376448 */
377449 public async hideAllNextEditWindows() {
378- await NextEditWindowManager.freeTabAndEsc();
450+ try {
451+ await NextEditWindowManager.freeTabAndEsc();
452+ } catch (err) {
453+ console.error(`Error freeing Tab/Esc while hiding: ${err}`);
454+ }
379455
380456 if (this.currentDecoration) {
381457 vscode.window.visibleTextEditors.forEach((editor) => {
@@ -502,6 +578,10 @@
502578 * Dispose of the NextEditWindowManager.
503579 */
504580 public dispose() {
581+ void this.resetKeyReservation().catch((err) =>
582+ console.error(`Failed to reset keys on dispose: ${err}`),
583+ );
584+
505585 // Dispose current decoration.
506586 if (this.currentDecoration) {
507587 this.currentDecoration.dispose();
added extensions/vscode/src/activation/NextEditWindowManager.vitest.ts +970 −0
@@ -0,0 +1,970 @@
1+import {
2+ afterEach,
3+ beforeEach,
4+ describe,
5+ expect,
6+ it,
7+ MockedFunction,
8+ vi,
9+} from "vitest";
10+
11+// Mock all modules FIRST with inline factories (no external references)
12+vi.mock("vscode", () => ({
13+ commands: {
14+ executeCommand: vi.fn(),
15+ registerCommand: vi.fn(),
16+ },
17+ window: {
18+ activeTextEditor: undefined,
19+ visibleTextEditors: [],
20+ createTextEditorDecorationType: vi.fn(),
21+ onDidChangeTextEditorSelection: vi.fn(() => ({ dispose: vi.fn() })),
22+ onDidChangeVisibleTextEditors: vi.fn(() => ({ dispose: vi.fn() })),
23+ onDidChangeActiveColorTheme: vi.fn(() => ({ dispose: vi.fn() })),
24+ showInformationMessage: vi.fn(),
25+ },
26+ workspace: {
27+ getConfiguration: vi.fn(() => ({
28+ get: vi.fn((key: string) => {
29+ const config: Record<string, any> = {
30+ fontSize: 14,
31+ fontFamily: "monospace",
32+ showInlineTip: true,
33+ };
34+ return config[key];
35+ }),
36+ })),
37+ onDidChangeConfiguration: vi.fn(() => ({ dispose: vi.fn() })),
38+ },
39+ Position: class {
40+ constructor(
41+ public line: number,
42+ public character: number,
43+ ) {}
44+ },
45+ Range: class {
46+ constructor(
47+ public start: any,
48+ public end: any,
49+ ) {}
50+ },
51+ Selection: class {
52+ constructor(
53+ public anchor: any,
54+ public active: any,
55+ ) {}
56+ },
57+ Uri: {
58+ parse: vi.fn((str: string) => ({ toString: () => str, scheme: "file" })),
59+ },
60+ DecorationRangeBehavior: {
61+ ClosedClosed: 1,
62+ },
63+ MarkdownString: class {
64+ value: string = "";
65+ isTrusted: boolean = false;
66+ supportHtml: boolean = false;
67+ constructor(value: string) {
68+ this.value = value;
69+ }
70+ },
71+ ExtensionContext: class {
72+ subscriptions: any[] = [];
73+ },
74+ ViewColumn: {
75+ One: 1,
76+ Two: 2,
77+ },
78+}));
79+
80+vi.mock("core/control-plane/env", () => ({
81+ EXTENSION_NAME: "continue",
82+}));
83+
84+vi.mock("../util/getTheme", () => ({
85+ getThemeString: vi.fn(() => "dark"),
86+}));
87+
88+vi.mock("core/codeRenderer/CodeRenderer", () => ({
89+ CodeRenderer: {
90+ getInstance: vi.fn(() => ({
91+ setTheme: vi.fn(),
92+ getDataUri: vi.fn().mockResolvedValue("data:image/svg+xml;base64,mock"),
93+ })),
94+ },
95+}));
96+
97+vi.mock("core/nextEdit/NextEditProvider", () => ({
98+ NextEditProvider: {
99+ getInstance: vi.fn(() => ({
100+ deleteChain: vi.fn(),
101+ })),
102+ },
103+}));
104+
105+vi.mock("core/nextEdit/NextEditLoggingService", () => ({
106+ NextEditLoggingService: {
107+ getInstance: vi.fn(() => ({
108+ cancelRejectionTimeout: vi.fn(),
109+ cancelRejectionTimeoutButKeepCompletionId: vi.fn(),
110+ })),
111+ },
112+}));
113+
114+vi.mock("core/diff/myers", () => ({
115+ myersCharDiff: vi.fn(() => []),
116+}));
117+
118+vi.mock("core/nextEdit/diff/diff", () => ({
119+ getOffsetPositionAtLastNewLine: vi.fn(() => ({ line: 0, character: 0 })),
120+}));
121+
122+// Import after mocks are set up
123+import * as vscode from "vscode";
124+
125+import {
126+ ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
127+ HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
128+ NextEditWindowManager,
129+} from "./NextEditWindowManager";
130+
131+const mockVscode = vi.mocked(vscode);
132+
133+describe("NextEditWindowManager", () => {
134+ let manager: NextEditWindowManager;
135+ let mockEditor: any;
136+ let mockDocument: any;
137+ let mockContext: any;
138+
139+ beforeEach(() => {
140+ vi.clearAllMocks();
141+
142+ // Clear singleton instance
143+ NextEditWindowManager.clearInstance();
144+
145+ // Create mock document
146+ mockDocument = {
147+ uri: { toString: () => "file:///test.ts", scheme: "file" },
148+ version: 1,
149+ lineCount: 10,
150+ lineAt: vi.fn((line: number) => ({
151+ text: `line ${line} content`,
152+ range: new mockVscode.Range(
153+ new mockVscode.Position(line, 0),
154+ new mockVscode.Position(line, 20),
155+ ),
156+ })),
157+ };
158+
159+ // Create mock editor
160+ mockEditor = {
161+ document: mockDocument,
162+ selection: {
163+ active: new mockVscode.Position(0, 0),
164+ },
165+ setDecorations: vi.fn(),
166+ edit: vi.fn((callback: any) => {
167+ callback({
168+ replace: vi.fn(),
169+ delete: vi.fn(),
170+ });
171+ return Promise.resolve(true);
172+ }),
173+ };
174+
175+ // Create mock context
176+ mockContext = {
177+ subscriptions: [],
178+ };
179+
180+ // Setup default mock implementations
181+ (
182+ mockVscode.commands.executeCommand as MockedFunction<any>
183+ ).mockResolvedValue(undefined);
184+ (mockVscode.commands.registerCommand as MockedFunction<any>)
185+ //@ts-ignore
186+ .mockImplementation((command: string, callback: any) => ({
187+ dispose: vi.fn(),
188+ }));
189+ (
190+ mockVscode.window.createTextEditorDecorationType as MockedFunction<any>
191+ ).mockReturnValue({
192+ dispose: vi.fn(),
193+ });
194+
195+ // Get manager instance
196+ manager = NextEditWindowManager.getInstance();
197+ });
198+
199+ afterEach(() => {
200+ NextEditWindowManager.clearInstance();
201+ });
202+
203+ describe("Singleton Pattern", () => {
204+ it("should return the same instance", () => {
205+ const instance1 = NextEditWindowManager.getInstance();
206+ const instance2 = NextEditWindowManager.getInstance();
207+ expect(instance1).toBe(instance2);
208+ });
209+
210+ it("should properly clear instance", () => {
211+ const instance1 = NextEditWindowManager.getInstance();
212+ NextEditWindowManager.clearInstance();
213+ const instance2 = NextEditWindowManager.getInstance();
214+ expect(instance1).not.toBe(instance2);
215+ });
216+ });
217+
218+ describe("Key Reservation State Management", () => {
219+ beforeEach(async () => {
220+ await manager.setupNextEditWindowManager(mockContext);
221+ });
222+
223+ it("should start with keys in free state", () => {
224+ expect(manager["keyReservationState"]).toBe("free");
225+ });
226+
227+ it("should reserve keys when showing window", async () => {
228+ await manager.showNextEditWindow(
229+ mockEditor,
230+ new mockVscode.Position(0, 0),
231+ 0,
232+ 0,
233+ "old",
234+ "new",
235+ [],
236+ );
237+
238+ expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
239+ "setContext",
240+ "nextEditWindowActive",
241+ true,
242+ );
243+ expect(manager["keyReservationState"]).toBe("reserved");
244+ });
245+
246+ it("should free keys when hiding windows", async () => {
247+ // First show a window
248+ await manager.showNextEditWindow(
249+ mockEditor,
250+ new mockVscode.Position(0, 0),
251+ 0,
252+ 0,
253+ "old",
254+ "new",
255+ [],
256+ );
257+
258+ // Then hide it
259+ await manager.hideAllNextEditWindows();
260+
261+ expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
262+ "setContext",
263+ "nextEditWindowActive",
264+ false,
265+ );
266+ expect(manager["keyReservationState"]).toBe("free");
267+ });
268+
269+ it("should handle sequential reserve/free operations", async () => {
270+ const executeCommand = mockVscode.commands
271+ .executeCommand as MockedFunction<any>;
272+
273+ await NextEditWindowManager.reserveTabAndEsc();
274+ expect(manager["keyReservationState"]).toBe("reserved");
275+
276+ await NextEditWindowManager.freeTabAndEsc();
277+ expect(manager["keyReservationState"]).toBe("free");
278+
279+ await NextEditWindowManager.reserveTabAndEsc();
280+ expect(manager["keyReservationState"]).toBe("reserved");
281+
282+ // Should have been called 3 times + 1 from beforeEach
283+ expect(executeCommand).toHaveBeenCalledTimes(4);
284+ });
285+
286+ it("should skip redundant reserve operations", async () => {
287+ const executeCommand = mockVscode.commands
288+ .executeCommand as MockedFunction<any>;
289+
290+ await NextEditWindowManager.reserveTabAndEsc();
291+ executeCommand.mockClear();
292+
293+ // Try to reserve again
294+ await NextEditWindowManager.reserveTabAndEsc();
295+
296+ // Should not have called executeCommand again
297+ expect(executeCommand).not.toHaveBeenCalled();
298+ expect(manager["keyReservationState"]).toBe("reserved");
299+ });
300+
301+ it("should skip redundant free operations", async () => {
302+ const executeCommand = mockVscode.commands
303+ .executeCommand as MockedFunction<any>;
304+ executeCommand.mockClear();
305+
306+ // Already free, try to free again
307+ await NextEditWindowManager.freeTabAndEsc();
308+
309+ // Should not have called executeCommand
310+ expect(executeCommand).not.toHaveBeenCalled();
311+ expect(manager["keyReservationState"]).toBe("free");
312+ });
313+ });
314+
315+ describe("Race Condition Prevention", () => {
316+ beforeEach(async () => {
317+ await manager.setupNextEditWindowManager(mockContext);
318+ });
319+
320+ it("should handle concurrent operations with random delays and last-write-wins", async () => {
321+ const executeCommand = mockVscode.commands
322+ .executeCommand as MockedFunction<any>;
323+ let completedOperations: string[] = [];
324+
325+ // Reset key reservation to ensure clean state
326+ await manager.resetKeyReservation();
327+
328+ // Start from reserved state so first free() will proceed
329+ manager["keyReservationState"] = "reserved";
330+ executeCommand.mockClear();
331+
332+ // Make executeCommand take random time and track completions
333+ executeCommand.mockImplementation((cmd, key, value) => {
334+ const operationId = `${value ? "reserve" : "free"}-${Date.now()}-${Math.random()}`;
335+ return new Promise((resolve) => {
336+ setTimeout(() => {
337+ completedOperations.push(operationId);
338+ // Immediately update state to ensure next operation proceeds
339+ // This simulates fast state changes
340+ manager["keyReservationState"] = value ? "reserved" : "free";
341+ resolve(undefined);
342+ }, Math.random() * 50);
343+ });
344+ });
345+
346+ // Fire multiple operations concurrently
347+ const operations = [
348+ NextEditWindowManager.reserveTabAndEsc(), // operation 1: reserve (skipped - already reserved)
349+ NextEditWindowManager.freeTabAndEsc(), // operation 2: free (proceeds)
350+ NextEditWindowManager.reserveTabAndEsc(), // operation 3: reserve (proceeds after 2 completes)
351+ NextEditWindowManager.freeTabAndEsc(), // operation 4: free (proceeds after 3 completes)
352+ ];
353+
354+ await Promise.all(operations);
355+
356+ // Count how many actually proceeded (those that didn't early return)
357+ const actualCalls = executeCommand.mock.calls.length;
358+
359+ // The state should match the last operation's intent
360+ // But the actual number of calls depends on timing and early returns
361+ expect(manager["latestOperationId"]).toBeGreaterThanOrEqual(actualCalls);
362+ });
363+
364+ it("should ignore stale operations", async () => {
365+ const executeCommand = mockVscode.commands
366+ .executeCommand as MockedFunction<any>;
367+
368+ await manager.resetKeyReservation();
369+ executeCommand.mockClear();
370+
371+ // Create deferred promises with guaranteed resolvers
372+ const createDeferred = () => {
373+ let resolve: Function;
374+ const promise = new Promise((res) => {
375+ resolve = res;
376+ });
377+ return { promise, resolve: resolve! };
378+ };
379+
380+ const deferred1 = createDeferred();
381+ const deferred2 = createDeferred();
382+
383+ // Control when each operation completes
384+ executeCommand
385+ .mockImplementationOnce(() => deferred1.promise)
386+ .mockImplementationOnce(() => deferred2.promise);
387+
388+ // Start operations
389+ const op1 = NextEditWindowManager.reserveTabAndEsc();
390+ const op2 = NextEditWindowManager.freeTabAndEsc();
391+
392+ // Complete op2 first (even though op1 started first)
393+ deferred2.resolve(undefined);
394+ await op2;
395+
396+ // State should be free (from op2)
397+ expect(manager["keyReservationState"]).toBe("free");
398+ expect(manager["latestOperationId"]).toBe(2);
399+
400+ // Now complete op1 (should be ignored as stale)
401+ deferred1.resolve(undefined);
402+ await op1;
403+
404+ // State should still be free (op1 was ignored)
405+ expect(manager["keyReservationState"]).toBe("free");
406+ expect(manager["latestOperationId"]).toBe(2);
407+ });
408+
409+ it("should handle rapid fire operations correctly (loop)", async () => {
410+ const executeCommand = mockVscode.commands
411+ .executeCommand as MockedFunction<any>;
412+
413+ await manager.resetKeyReservation();
414+ executeCommand.mockClear();
415+
416+ // Make operations instant
417+ executeCommand.mockResolvedValue(undefined);
418+
419+ // Fire many operations rapidly
420+ const operations = [];
421+ for (let i = 0; i < 20; i++) {
422+ operations.push(
423+ i % 2 === 0
424+ ? NextEditWindowManager.reserveTabAndEsc()
425+ : NextEditWindowManager.freeTabAndEsc(),
426+ );
427+ }
428+
429+ await Promise.all(operations);
430+
431+ // Last operation (i=19) was free (odd number)
432+ expect(manager["keyReservationState"]).toBe("free");
433+ expect(manager["latestOperationId"]).toBe(20);
434+ });
435+
436+ it("should handle alternating reserve/free with delays", async () => {
437+ const executeCommand = mockVscode.commands
438+ .executeCommand as MockedFunction<any>;
439+
440+ await manager.resetKeyReservation();
441+ executeCommand.mockClear();
442+
443+ // Track actual VS Code context values set
444+ const contextValues: boolean[] = [];
445+ executeCommand.mockImplementation((cmd, key, value) => {
446+ if (cmd === "setContext") {
447+ //@ts-ignore
448+ contextValues.push(value);
449+ }
450+ return Promise.resolve(undefined);
451+ });
452+
453+ // Alternating operations
454+ await NextEditWindowManager.reserveTabAndEsc();
455+ expect(manager["keyReservationState"]).toBe("reserved");
456+
457+ await NextEditWindowManager.freeTabAndEsc();
458+ expect(manager["keyReservationState"]).toBe("free");
459+
460+ await NextEditWindowManager.reserveTabAndEsc();
461+ expect(manager["keyReservationState"]).toBe("reserved");
462+
463+ // Check that context was set correctly each time
464+ expect(contextValues).toEqual([true, false, true]);
465+ });
466+
467+ it("should handle rapid alternations correctly", async () => {
468+ const executeCommand = mockVscode.commands
469+ .executeCommand as MockedFunction<any>;
470+
471+ await manager.resetKeyReservation();
472+ executeCommand.mockClear();
473+
474+ // Track all setContext calls
475+ const contextCalls: boolean[] = [];
476+ executeCommand.mockImplementation((cmd, key, value) => {
477+ if (cmd === "setContext" && key === "nextEditWindowActive") {
478+ //@ts-ignore
479+ contextCalls.push(value);
480+ }
481+ return Promise.resolve();
482+ });
483+
484+ // Simulate rapid SEQUENTIAL user interactions:
485+ // These need to be sequential to ensure state changes between calls
486+ await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved
487+ await NextEditWindowManager.freeTabAndEsc(); // reserved -> free
488+ await NextEditWindowManager.reserveTabAndEsc(); // free -> reserved
489+ await NextEditWindowManager.freeTabAndEsc(); // reserved -> free
490+
491+ // Should end in free state (last operation)
492+ expect(manager["keyReservationState"]).toBe("free");
493+
494+ // Should have made all 4 calls since state alternates
495+ expect(contextCalls).toEqual([true, false, true, false]);
496+ });
497+
498+ it("should handle concurrent duplicate operations efficiently", async () => {
499+ const executeCommand = mockVscode.commands
500+ .executeCommand as MockedFunction<any>;
501+
502+ await manager.resetKeyReservation();
503+ executeCommand.mockClear();
504+
505+ // Track all setContext calls
506+ const contextCalls: boolean[] = [];
507+ executeCommand.mockImplementation((cmd, key, value) => {
508+ if (cmd === "setContext" && key === "nextEditWindowActive") {
509+ //@ts-ignore
510+ contextCalls.push(value);
511+ }
512+ return Promise.resolve();
513+ });
514+
515+ // When multiple reserve operations happen concurrently (e.g., multiple completions)
516+ // Only the first should actually make the call
517+ const operations = [
518+ NextEditWindowManager.reserveTabAndEsc(),
519+ NextEditWindowManager.reserveTabAndEsc(),
520+ NextEditWindowManager.reserveTabAndEsc(),
521+ ];
522+
523+ await Promise.all(operations);
524+
525+ // Should have made only the necessary calls
526+ // Since all start with state "free", all will proceed to call setContext
527+ // This is because they all check state before any completes
528+ expect(contextCalls.length).toBeGreaterThan(0);
529+ expect(manager["keyReservationState"]).toBe("reserved");
530+
531+ // All calls should be trying to reserve (true)
532+ expect(contextCalls.every((call) => call === true)).toBe(true);
533+ });
534+
535+ it("should handle truly concurrent mixed operations", async () => {
536+ const executeCommand = mockVscode.commands
537+ .executeCommand as MockedFunction<any>;
538+
539+ await manager.resetKeyReservation();
540+ // Start in reserved state
541+ await NextEditWindowManager.reserveTabAndEsc();
542+ executeCommand.mockClear();
543+
544+ // Track all setContext calls
545+ const contextCalls: boolean[] = [];
546+ executeCommand.mockImplementation((cmd, key, value) => {
547+ if (cmd === "setContext" && key === "nextEditWindowActive") {
548+ //@ts-ignore
549+ contextCalls.push(value);
550+ // Add small delay to simulate real async behavior
551+ return new Promise((resolve) => setTimeout(resolve, 5));
552+ }
553+ return Promise.resolve();
554+ });
555+
556+ // Mix of operations starting from "reserved" state
557+ const operations = [
558+ NextEditWindowManager.freeTabAndEsc(), // Will proceed (reserved -> free)
559+ NextEditWindowManager.freeTabAndEsc(), // Will proceed (checks while first is in flight)
560+ NextEditWindowManager.reserveTabAndEsc(), // Will proceed (different operation)
561+ ];
562+
563+ await Promise.all(operations);
564+
565+ // The last operation to complete wins (but order is non-deterministic)
566+ // State should be either "free" or "reserved" depending on completion order
567+ expect(["free", "reserved"]).toContain(manager["keyReservationState"]);
568+
569+ // Should have made at least some calls
570+ expect(contextCalls.length).toBeGreaterThan(0);
571+ });
572+
573+ it("should maintain correct state with stale operations", async () => {
574+ const executeCommand = mockVscode.commands
575+ .executeCommand as MockedFunction<any>;
576+
577+ await manager.resetKeyReservation();
578+ executeCommand.mockClear();
579+
580+ // Create a controlled execution order
581+ let resolveFirst: () => void;
582+ let resolveSecond: () => void;
583+
584+ const firstPromise = new Promise<void>((resolve) => {
585+ resolveFirst = resolve;
586+ });
587+
588+ const secondPromise = new Promise<void>((resolve) => {
589+ resolveSecond = resolve;
590+ });
591+
592+ executeCommand
593+ .mockImplementationOnce(() => firstPromise)
594+ .mockImplementationOnce(() => secondPromise);
595+
596+ // Start operations
597+ const op1 = NextEditWindowManager.reserveTabAndEsc();
598+ const op2 = NextEditWindowManager.freeTabAndEsc();
599+
600+ // Complete second operation first (out of order)
601+ resolveSecond!();
602+ await op2;
603+
604+ // State should be free (last operation to start, even though it completed first)
605+ expect(manager["keyReservationState"]).toBe("free");
606+
607+ // Complete first operation
608+ resolveFirst!();
609+ await op1;
610+
611+ // State should still be free (op1 was stale)
612+ expect(manager["keyReservationState"]).toBe("free");
613+ });
614+ });
615+
616+ describe("Error Recovery", () => {
617+ beforeEach(async () => {
618+ await manager.setupNextEditWindowManager(mockContext);
619+ });
620+
621+ it("should recover from failed key reservation", async () => {
622+ const executeCommand = mockVscode.commands
623+ .executeCommand as MockedFunction<any>;
624+
625+ // Make reservation fail
626+ executeCommand.mockRejectedValueOnce(new Error("VS Code busy"));
627+
628+ await expect(NextEditWindowManager.reserveTabAndEsc()).rejects.toThrow(
629+ "VS Code busy",
630+ );
631+
632+ // State should reset to free
633+ expect(manager["keyReservationState"]).toBe("free");
634+
635+ // Should be able to try again
636+ executeCommand.mockResolvedValueOnce(undefined);
637+ await NextEditWindowManager.reserveTabAndEsc();
638+ expect(manager["keyReservationState"]).toBe("reserved");
639+ });
640+
641+ it("should recover from failed key freeing", async () => {
642+ const executeCommand = mockVscode.commands
643+ .executeCommand as MockedFunction<any>;
644+
645+ // First reserve successfully
646+ await NextEditWindowManager.reserveTabAndEsc();
647+ expect(manager["keyReservationState"]).toBe("reserved");
648+
649+ // Make freeing fail
650+ executeCommand.mockRejectedValueOnce(new Error("VS Code busy"));
651+
652+ await expect(NextEditWindowManager.freeTabAndEsc()).rejects.toThrow(
653+ "VS Code busy",
654+ );
655+
656+ // State should still reset to free (safety mechanism)
657+ expect(manager["keyReservationState"]).toBe("free");
658+ });
659+
660+ it("should handle decoration creation failure", async () => {
661+ const createDecoration = mockVscode.window
662+ .createTextEditorDecorationType as MockedFunction<any>;
663+ createDecoration.mockImplementationOnce(() => {
664+ throw new Error("Failed to create decoration");
665+ });
666+
667+ // Should not throw, but should clean up
668+ await manager.showNextEditWindow(
669+ mockEditor,
670+ new mockVscode.Position(0, 0),
671+ 0,
672+ 0,
673+ "old",
674+ "new",
675+ [],
676+ );
677+
678+ // Keys should be freed due to error
679+ expect(manager["keyReservationState"]).toBe("free");
680+ expect(manager["currentDecoration"]).toBeNull();
681+ });
682+ });
683+
684+ describe("Command Registration", () => {
685+ it("should register hide command", async () => {
686+ await manager.setupNextEditWindowManager(mockContext);
687+
688+ expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith(
689+ HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
690+ expect.any(Function),
691+ );
692+ });
693+
694+ it("should register accept command", async () => {
695+ await manager.setupNextEditWindowManager(mockContext);
696+
697+ expect(mockVscode.commands.registerCommand).toHaveBeenCalledWith(
698+ ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
699+ expect.any(Function),
700+ );
701+ });
702+
703+ it("should handle command registration failure gracefully", async () => {
704+ const registerCommand = mockVscode.commands
705+ .registerCommand as MockedFunction<any>;
706+ registerCommand.mockImplementationOnce(() => {
707+ throw new Error("Command already registered");
708+ });
709+
710+ // Should not throw
711+ await expect(
712+ manager.setupNextEditWindowManager(mockContext),
713+ ).resolves.not.toThrow();
714+ });
715+ });
716+
717+ describe("Window Management", () => {
718+ beforeEach(async () => {
719+ await manager.setupNextEditWindowManager(mockContext);
720+ });
721+
722+ it("should store tooltip text when showing window", async () => {
723+ await manager.showNextEditWindow(
724+ mockEditor,
725+ new mockVscode.Position(0, 0),
726+ 0,
727+ 2,
728+ "old code",
729+ "new code",
730+ [],
731+ );
732+
733+ expect(manager["currentTooltipText"]).toBe("new code");
734+ expect(manager["activeEditor"]).toBe(mockEditor);
735+ });
736+
737+ it("should clear tooltip text when hiding windows", async () => {
738+ // Show first
739+ await manager.showNextEditWindow(
740+ mockEditor,
741+ new mockVscode.Position(0, 0),
742+ 0,
743+ 2,
744+ "old",
745+ "new",
746+ [],
747+ );
748+
749+ // Then hide
750+ await manager.hideAllNextEditWindows();
751+
752+ expect(manager["currentTooltipText"]).toBeNull();
753+ expect(manager["activeEditor"]).toBeNull();
754+ });
755+
756+ it("should handle line deletion case", async () => {
757+ mockEditor.document.lineAt = vi.fn((lineNumber: number) => ({
758+ text: "line to delete",
759+ }));
760+
761+ await manager.showNextEditWindow(
762+ mockEditor,
763+ new mockVscode.Position(1, 0),
764+ 1,
765+ 1,
766+ "line to delete",
767+ "", // Empty means deletion
768+ [{ type: "old", line: "line to delete" }],
769+ );
770+
771+ expect(manager["isLineDelete"]).toBe(true);
772+ // Final cursor should be at end of previous line
773+ expect(manager["finalCursorPos"]?.line).toBe(0);
774+ });
775+
776+ it("should skip rendering for excluded URIs", async () => {
777+ mockEditor.document.uri = {
778+ toString: () => "output://test",
779+ scheme: "output",
780+ };
781+
782+ await manager.showNextEditWindow(
783+ mockEditor,
784+ new mockVscode.Position(0, 0),
785+ 0,
786+ 0,
787+ "old",
788+ "new",
789+ [],
790+ );
791+
792+ // Should not create decoration for excluded URI
793+ expect(
794+ mockVscode.window.createTextEditorDecorationType,
795+ ).not.toHaveBeenCalled();
796+ expect(manager["currentDecoration"]).toBeNull();
797+ });
798+ });
799+
800+ describe("Accept/Reject Flow", () => {
801+ beforeEach(async () => {
802+ await manager.setupNextEditWindowManager(mockContext);
803+ });
804+
805+ it("should apply text when accepting", async () => {
806+ // Show window first
807+ await manager.showNextEditWindow(
808+ mockEditor,
809+ new mockVscode.Position(0, 0),
810+ 0,
811+ 0,
812+ "old",
813+ "new text",
814+ [],
815+ );
816+
817+ // Get the accept command callback
818+ const registerCalls = (
819+ mockVscode.commands.registerCommand as MockedFunction<any>
820+ ).mock.calls;
821+ const acceptCall = registerCalls.find(
822+ (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
823+ );
824+ //@ts-ignore
825+ const acceptCallback = acceptCall[1];
826+
827+ // Call accept
828+ //@ts-ignore
829+ await acceptCallback();
830+
831+ // Should have called edit
832+ expect(mockEditor.edit).toHaveBeenCalled();
833+
834+ // Should have cleared the decoration
835+ expect(manager["currentTooltipText"]).toBeNull();
836+ expect(manager["keyReservationState"]).toBe("free");
837+ });
838+
839+ it("should not accept when no active window", async () => {
840+ // Get the accept command callback
841+ const registerCalls = (
842+ mockVscode.commands.registerCommand as MockedFunction<any>
843+ ).mock.calls;
844+ const acceptCall = registerCalls.find(
845+ (call) => call[0] === ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND,
846+ );
847+ //@ts-ignore
848+ const acceptCallback = acceptCall[1];
849+
850+ // Call accept without showing window
851+ //@ts-ignore
852+ await acceptCallback();
853+
854+ // Should not have called edit
855+ expect(mockEditor.edit).not.toHaveBeenCalled();
856+ });
857+
858+ it("should hide window when rejecting", async () => {
859+ // Show window first
860+ await manager.showNextEditWindow(
861+ mockEditor,
862+ new mockVscode.Position(0, 0),
863+ 0,
864+ 0,
865+ "old",
866+ "new",
867+ [],
868+ );
869+
870+ // Get the hide command callback
871+ const registerCalls = (
872+ mockVscode.commands.registerCommand as MockedFunction<any>
873+ ).mock.calls;
874+ const hideCall = registerCalls.find(
875+ (call) => call[0] === HIDE_NEXT_EDIT_SUGGESTION_COMMAND,
876+ );
877+ //@ts-ignore
878+ const hideCallback = hideCall[1];
879+
880+ // Call hide
881+ //@ts-ignore
882+ await hideCallback();
883+
884+ // Should have cleared everything
885+ expect(manager["currentTooltipText"]).toBeNull();
886+ expect(manager["activeEditor"]).toBeNull();
887+ expect(manager["keyReservationState"]).toBe("free");
888+ });
889+ });
890+
891+ describe("Disposal", () => {
892+ it("should free keys on disposal", async () => {
893+ await manager.setupNextEditWindowManager(mockContext);
894+
895+ // Reserve keys first
896+ await NextEditWindowManager.reserveTabAndEsc();
897+ expect(manager["keyReservationState"]).toBe("reserved");
898+
899+ // Dispose
900+ manager.dispose();
901+
902+ // Should attempt to free keys
903+ expect(mockVscode.commands.executeCommand).toHaveBeenCalledWith(
904+ "setContext",
905+ "nextEditWindowActive",
906+ false,
907+ );
908+ });
909+
910+ it("should dispose decorations on disposal", async () => {
911+ await manager.setupNextEditWindowManager(mockContext);
912+
913+ const mockDecoration = { dispose: vi.fn() };
914+ const mockDisposable1 = { dispose: vi.fn() };
915+ const mockDisposable2 = { dispose: vi.fn() };
916+
917+ manager["currentDecoration"] = mockDecoration as any;
918+ manager["disposables"] = [mockDisposable1, mockDisposable2];
919+
920+ manager.dispose();
921+
922+ expect(mockDecoration.dispose).toHaveBeenCalled();
923+ expect(mockDisposable1.dispose).toHaveBeenCalled();
924+ expect(mockDisposable2.dispose).toHaveBeenCalled();
925+ });
926+ });
927+
928+ describe("Configuration Changes", () => {
929+ it("should update on theme change", async () => {
930+ await manager.setupNextEditWindowManager(mockContext);
931+
932+ // Get the configuration change listener
933+ const onDidChange = mockVscode.workspace
934+ .onDidChangeConfiguration as MockedFunction<any>;
935+ const changeCallback = onDidChange.mock.calls[0][0];
936+
937+ // Simulate theme change
938+ //@ts-ignore
939+ await changeCallback({
940+ affectsConfiguration: (key: string) => key === "workbench.colorTheme",
941+ });
942+
943+ // Should have updated theme
944+ const { getThemeString } = await import("../util/getTheme");
945+ expect(getThemeString).toHaveBeenCalled();
946+ });
947+
948+ it("should update on font size change", async () => {
949+ await manager.setupNextEditWindowManager(mockContext);
950+
951+ const onDidChange = mockVscode.workspace
952+ .onDidChangeConfiguration as MockedFunction<any>;
953+ const changeCallback = onDidChange.mock.calls[0][0];
954+
955+ // Change font size
956+ (
957+ mockVscode.workspace.getConfiguration as MockedFunction<any>
958+ ).mockReturnValueOnce({
959+ get: (key: string) => (key === "fontSize" ? 16 : "monospace"),
960+ });
961+
962+ //@ts-ignore
963+ await changeCallback({
964+ affectsConfiguration: (key: string) => key === "editor.fontSize",
965+ });
966+
967+ expect(manager["fontSize"]).toBe(16);
968+ });
969+ });
970+});
modified extensions/vscode/src/apply/ApplyManager.ts +20 −29
@@ -50,45 +50,36 @@
5050 toolCallId,
5151 });
5252
53- try {
54- const hasExistingDocument = !!activeTextEditor.document.getText().trim();
55-
56- if (hasExistingDocument) {
57- // Currently `isSearchAndReplace` will always provide a full file rewrite
58- // as the contents of `text`, so we can just instantly apply
59- if (isSearchAndReplace) {
60- const diffLinesGenerator = generateLines(
61- myersDiff(activeTextEditor.document.getText(), text),
62- );
53+ const hasExistingDocument = !!activeTextEditor.document.getText().trim();
54+ if (hasExistingDocument) {
55+ // Currently `isSearchAndReplace` will always provide a full file rewrite
56+ // as the contents of `text`, so we can just instantly apply
57+ if (isSearchAndReplace) {
58+ const diffLinesGenerator = generateLines(
59+ myersDiff(activeTextEditor.document.getText(), text),
60+ );
6361
64- await this.verticalDiffManager.streamDiffLines(
65- diffLinesGenerator,
66- true,
67- streamId,
68- toolCallId,
69- );
70- } else {
71- await this.handleExistingDocument(
72- activeTextEditor,
73- text,
74- streamId,
75- toolCallId,
76- );
77- }
62+ await this.verticalDiffManager.streamDiffLines(
63+ diffLinesGenerator,
64+ true,
65+ streamId,
66+ toolCallId,
67+ );
7868 } else {
79- await this.handleEmptyDocument(
69+ await this.handleExistingDocument(
8070 activeTextEditor,
8171 text,
8272 streamId,
8373 toolCallId,
8474 );
8575 }
86- } finally {
87- await this.webviewProtocol.request("updateApplyState", {
76+ } else {
77+ await this.handleEmptyDocument(
78+ activeTextEditor,
79+ text,
8880 streamId,
89- status: "done",
9081 toolCallId,
91- });
82+ );
9283 }
9384 }
9485
modified extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +5 −0
@@ -3,6 +3,7 @@
33 AutocompleteCodeSnippet,
44 AutocompleteSnippetType,
55 } from "core/autocomplete/snippets/types";
6+import { isSecurityConcern } from "core/indexing/ignore";
67 import { PosthogFeatureFlag, Telemetry } from "core/util/posthog";
78 import { LRUCache } from "lru-cache";
89 import * as vscode from "vscode";
@@ -51,6 +52,10 @@
5152 private cacheCurrentSelectionContext = async (
5253 event: vscode.TextEditorSelectionChangeEvent,
5354 ) => {
55+ const fsPath = event.textEditor.document.fileName;
56+ if (isSecurityConcern(fsPath)) {
57+ return;
58+ }
5459 const filepath = event.textEditor.document.uri.toString();
5560 const line = event.selections[0].active.line;
5661 const startLine = Math.max(0, line - this.numSurroundingLines);
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.

added gui/src/components/StyledMarkdownPreview/SecureImageComponent.test.tsx +218 −0
@@ -0,0 +1,218 @@
1+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
2+import { beforeEach, describe, expect, it, vi } from "vitest";
3+import { SecureImageComponent } from "./SecureImageComponent";
4+
5+describe("SecureImageComponent", () => {
6+ beforeEach(() => {
7+ vi.clearAllMocks();
8+ });
9+
10+ describe("Default blocking behavior", () => {
11+ it("should block images by default and show warning message", () => {
12+ render(<SecureImageComponent src="https://example.com/image.jpg" />);
13+
14+ expect(
15+ screen.getByText(
16+ /Image blocked for security.*External images can leak data/,
17+ ),
18+ ).toBeInTheDocument();
19+ expect(screen.getByText("Load Image")).toBeInTheDocument();
20+ expect(screen.queryByRole("img")).not.toBeInTheDocument();
21+ });
22+
23+ it("should display the image URL", () => {
24+ const testUrl = "https://example.com/test-image.png";
25+ render(<SecureImageComponent src={testUrl} />);
26+
27+ expect(screen.getByText(testUrl)).toBeInTheDocument();
28+ });
29+
30+ it("should handle invalid src prop", () => {
31+ render(<SecureImageComponent src={undefined} />);
32+
33+ expect(
34+ screen.getByText("[Invalid image: no source]"),
35+ ).toBeInTheDocument();
36+ expect(screen.queryByText("Load Image")).not.toBeInTheDocument();
37+ });
38+ });
39+
40+ describe("Query parameter detection", () => {
41+ it("should detect and display query parameters", () => {
42+ render(
43+ <SecureImageComponent src="https://example.com/image.jpg?user=123&token=abc" />,
44+ );
45+
46+ expect(
47+ screen.getByText(/Warning: URL contains query parameters/),
48+ ).toBeInTheDocument();
49+ expect(screen.getByText(/"user": "123"/)).toBeInTheDocument();
50+ expect(screen.getByText(/"token": "abc"/)).toBeInTheDocument();
51+ });
52+
53+ it("should not show query parameter warning for URLs without parameters", () => {
54+ render(<SecureImageComponent src="https://example.com/image.jpg" />);
55+
56+ expect(
57+ screen.queryByText(/Warning: URL contains query parameters/),
58+ ).not.toBeInTheDocument();
59+ });
60+
61+ it("should handle relative URLs with query parameters", () => {
62+ render(
63+ <SecureImageComponent src="/images/test.jpg?id=456&session=xyz" />,
64+ );
65+
66+ expect(
67+ screen.getByText(/Warning: URL contains query parameters/),
68+ ).toBeInTheDocument();
69+ expect(screen.getByText(/"id": "456"/)).toBeInTheDocument();
70+ expect(screen.getByText(/"session": "xyz"/)).toBeInTheDocument();
71+ });
72+
73+ it("should handle malformed URLs gracefully", () => {
74+ render(<SecureImageComponent src="not-a-valid-url://image" />);
75+
76+ // Should still display the URL even if it can't be parsed
77+ expect(screen.getByText("not-a-valid-url://image")).toBeInTheDocument();
78+ expect(screen.getByText("Load Image")).toBeInTheDocument();
79+ });
80+ });
81+
82+ describe("User interaction", () => {
83+ it("should show image when Load Image button is clicked", () => {
84+ const testUrl = "https://example.com/image.jpg";
85+ render(<SecureImageComponent src={testUrl} alt="Test image" />);
86+
87+ // Initially no image
88+ expect(screen.queryByRole("img")).not.toBeInTheDocument();
89+
90+ // Click load button
91+ const loadButton = screen.getByText("Load Image");
92+ fireEvent.click(loadButton);
93+
94+ // Image should now be displayed (query by tag since it might be role="presentation")
95+ const image = screen.getByAltText("Test image");
96+ expect(image).toBeInTheDocument();
97+ expect(image).toHaveAttribute("src", testUrl);
98+ expect(image).toHaveAttribute("alt", "Test image");
99+
100+ // Warning message should be gone
101+ expect(
102+ screen.queryByText(
103+ /Image blocked for security.*External images can leak data/,
104+ ),
105+ ).not.toBeInTheDocument();
106+ });
107+
108+ it("should handle image load errors", async () => {
109+ const testUrl = "https://example.com/broken-image.jpg";
110+ render(<SecureImageComponent src={testUrl} alt="broken image" />);
111+
112+ // Click load button
113+ const loadButton = screen.getByText("Load Image");
114+ fireEvent.click(loadButton);
115+
116+ // Simulate image error (query by alt text since role might be presentation)
117+ const image = screen.getByAltText("broken image");
118+ fireEvent.error(image);
119+
120+ // Should show error message and hide image
121+ await waitFor(() => {
122+ expect(screen.getByText(/Failed to load image/)).toBeInTheDocument();
123+ expect(screen.queryByAltText("broken image")).not.toBeInTheDocument();
124+ });
125+
126+ // Load button should be available again
127+ expect(screen.getByText("Load Image")).toBeInTheDocument();
128+ });
129+
130+ it("should pass through title and className props", () => {
131+ render(
132+ <SecureImageComponent
133+ src="https://example.com/image.jpg"
134+ alt="test image"
135+ title="Image title"
136+ className="custom-class"
137+ />,
138+ );
139+
140+ // Click load button
141+ fireEvent.click(screen.getByText("Load Image"));
142+
143+ // Check image has title (query by alt text)
144+ const image = screen.getByAltText("test image");
145+ expect(image).toHaveAttribute("title", "Image title");
146+
147+ // Check container has className
148+ const container = image.parentElement;
149+ expect(container).toHaveClass("custom-class");
150+ });
151+ });
152+
153+ describe("Security features", () => {
154+ it("should display query parameters as JSON for transparency", () => {
155+ render(
156+ <SecureImageComponent src="https://malicious.com/track.gif?email=user@example.com&id=12345&action=view" />,
157+ );
158+
159+ // Should show all parameters clearly
160+ expect(
161+ screen.getByText(/Warning: URL contains query parameters/),
162+ ).toBeInTheDocument();
163+
164+ // Check JSON is properly formatted
165+ const preElement = screen.getByText(/"email": "user@example.com"/);
166+ expect(preElement).toBeInTheDocument();
167+ expect(screen.getByText(/"id": "12345"/)).toBeInTheDocument();
168+ expect(screen.getByText(/"action": "view"/)).toBeInTheDocument();
169+ });
170+
171+ it("should handle encoded query parameters", () => {
172+ render(
173+ <SecureImageComponent src="https://example.com/img.png?data=%7B%22user%22%3A%22test%22%7D" />,
174+ );
175+
176+ // Should decode and display the parameter
177+ expect(
178+ screen.getByText(/Warning: URL contains query parameters/),
179+ ).toBeInTheDocument();
180+ // The decoded value should be shown in the pre element
181+ const preElement = document.querySelector("pre");
182+ expect(preElement).toBeTruthy();
183+ // Check that the JSON contains the decoded data
184+ expect(preElement?.textContent).toContain('"data"');
185+ // The value is decoded as a string containing JSON
186+ expect(preElement?.textContent).toContain('"{');
187+ expect(preElement?.textContent).toContain("user");
188+ expect(preElement?.textContent).toContain("test");
189+ });
190+ });
191+
192+ describe("Alt text handling", () => {
193+ it("should use empty string for alt when not provided", () => {
194+ render(<SecureImageComponent src="https://example.com/image.jpg" />);
195+
196+ fireEvent.click(screen.getByText("Load Image"));
197+
198+ // Query by tag name since empty alt makes it role="presentation"
199+ const images = document.querySelectorAll("img");
200+ expect(images.length).toBe(1);
201+ expect(images[0]).toHaveAttribute("alt", "");
202+ });
203+
204+ it("should use provided alt text", () => {
205+ render(
206+ <SecureImageComponent
207+ src="https://example.com/image.jpg"
208+ alt="Description of image"
209+ />,
210+ );
211+
212+ fireEvent.click(screen.getByText("Load Image"));
213+
214+ const image = screen.getByAltText("Description of image");
215+ expect(image).toHaveAttribute("alt", "Description of image");
216+ });
217+ });
218+});
added gui/src/components/StyledMarkdownPreview/SecureImageComponent.tsx +168 −0
@@ -0,0 +1,168 @@
1+import React, { useState } from "react";
2+import styled from "styled-components";
3+import {
4+ lightGray,
5+ vscBackground,
6+ vscButtonBackground,
7+ vscButtonForeground,
8+ vscForeground,
9+ vscInputBorder,
10+} from "../";
11+
12+const ImagePlaceholder = styled.div`
13+ border: 1px solid ${vscInputBorder};
14+ border-radius: 4px;
15+ padding: 12px;
16+ margin: 8px 0;
17+ background-color: ${vscBackground};
18+ display: inline-block;
19+ max-width: 100%;
20+`;
21+
22+const WarningText = styled.div`
23+ color: ${lightGray};
24+ font-size: 12px;
25+ margin-bottom: 8px;
26+`;
27+
28+const UrlDisplay = styled.div`
29+ font-family: var(--vscode-editor-font-family);
30+ font-size: 12px;
31+ color: ${vscForeground};
32+ word-break: break-all;
33+ margin: 8px 0;
34+ padding: 8px;
35+ background-color: rgba(0, 0, 0, 0.1);
36+ border-radius: 3px;
37+`;
38+
39+const QueryParamsDisplay = styled.div`
40+ font-family: var(--vscode-editor-font-family);
41+ font-size: 11px;
42+ color: ${vscForeground};
43+ margin: 8px 0;
44+ padding: 8px;
45+ background-color: rgba(128, 128, 128, 0.1);
46+ border-radius: 3px;
47+ border: 1px solid ${lightGray};
48+`;
49+
50+const LoadButton = styled.button`
51+ background-color: ${vscButtonBackground};
52+ color: ${vscButtonForeground};
53+ border: 1px solid ${vscInputBorder};
54+ padding: 6px 12px;
55+ border-radius: 3px;
56+ cursor: pointer;
57+ font-size: 12px;
58+ margin-top: 8px;
59+
60+ &:hover {
61+ opacity: 0.9;
62+ }
63+
64+ &:active {
65+ transform: translateY(1px);
66+ }
67+`;
68+
69+const ImageContainer = styled.div`
70+ max-width: 100%;
71+ display: inline-block;
72+
73+ img {
74+ max-width: 100%;
75+ height: auto;
76+ display: block;
77+ }
78+`;
79+
80+interface SecureImageComponentProps {
81+ src?: string;
82+ alt?: string;
83+ title?: string;
84+ className?: string;
85+}
86+
87+export const SecureImageComponent: React.FC<SecureImageComponentProps> = ({
88+ src,
89+ alt,
90+ title,
91+ className,
92+}) => {
93+ const [showImage, setShowImage] = useState(false);
94+ const [imageError, setImageError] = useState(false);
95+
96+ if (!src) {
97+ return <span>[Invalid image: no source]</span>;
98+ }
99+
100+ // Parse URL to check for query parameters
101+ let queryParams: Record<string, string> = {};
102+ let hasQueryParams = false;
103+
104+ try {
105+ const url = new URL(src, window.location.href);
106+ const params = new URLSearchParams(url.search);
107+ params.forEach((value, key) => {
108+ queryParams[key] = value;
109+ hasQueryParams = true;
110+ });
111+ } catch (e) {
112+ // If URL parsing fails, treat src as a relative path
113+ const queryIndex = src.indexOf("?");
114+ if (queryIndex > -1) {
115+ hasQueryParams = true;
116+ const params = new URLSearchParams(src.substring(queryIndex));
117+ params.forEach((value, key) => {
118+ queryParams[key] = value;
119+ });
120+ }
121+ }
122+
123+ if (showImage && !imageError) {
124+ return (
125+ <ImageContainer className={className}>
126+ <img
127+ src={src}
128+ alt={alt || ""}
129+ title={title}
130+ onError={() => {
131+ setImageError(true);
132+ setShowImage(false);
133+ }}
134+ />
135+ </ImageContainer>
136+ );
137+ }
138+
139+ return (
140+ <ImagePlaceholder>
141+ <WarningText>
142+ Image blocked for security. External images can leak data through URL
143+ parameters. Click to load if you trust the source.
144+ </WarningText>
145+
146+ <UrlDisplay>
147+ <strong>URL:</strong> {src}
148+ </UrlDisplay>
149+
150+ {hasQueryParams && (
151+ <QueryParamsDisplay>
152+ <strong>Warning: URL contains query parameters:</strong>
153+ <pre style={{ margin: "4px 0", fontSize: "11px" }}>
154+ {JSON.stringify(queryParams, null, 2)}
155+ </pre>
156+ </QueryParamsDisplay>
157+ )}
158+
159+ {imageError && (
160+ <div style={{ color: lightGray, fontSize: "12px", marginTop: "8px" }}>
161+ Failed to load image. The URL may be invalid or inaccessible.
162+ </div>
163+ )}
164+
165+ <LoadButton onClick={() => setShowImage(true)}>Load Image</LoadButton>
166+ </ImagePlaceholder>
167+ );
168+};
modified gui/src/components/StyledMarkdownPreview/index.tsx +11 −0
@@ -23,6 +23,7 @@
2323 import "./markdown.css";
2424 import MermaidBlock from "./MermaidBlock";
2525 import { rehypeHighlightPlugin } from "./rehypeHighlightPlugin";
26+import { SecureImageComponent } from "./SecureImageComponent";
2627 import { StepContainerPreToolbar } from "./StepContainerPreToolbar";
2728 import SymbolLink from "./SymbolLink";
2829 import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
@@ -346,6 +347,16 @@
346347 }
347348 return <code {...codeProps}>{codeProps.children}</code>;
348349 },
350+ img: ({ ...imgProps }) => {
351+ return (
352+ <SecureImageComponent
353+ src={imgProps.src}
354+ alt={imgProps.alt}
355+ title={imgProps.title}
356+ className={imgProps.className}
357+ />
358+ );
359+ },
349360 },
350361 },
351362 });
modified gui/src/components/mainInput/Lump/EditBlockButton.tsx +3 −3
@@ -6,7 +6,7 @@
66
77 type SectionKey = Exclude<
88 keyof ConfigYaml,
9- "name" | "version" | "schema" | "metadata"
9+ "name" | "version" | "schema" | "metadata" | "env"
1010 >;
1111
1212 interface EditBlockButtonProps<T extends SectionKey> {
@@ -42,10 +42,10 @@
4242 element: { sourceFile },
4343 });
4444 } else if (block && isUsesBlock(block)) {
45- openUrl(`${block.uses}/new-version`);
45+ void openUrl(`${block.uses}/new-version`);
4646 } else if (selectedProfile?.fullSlug) {
4747 const slug = `${selectedProfile.fullSlug.ownerSlug}/${selectedProfile.fullSlug.packageSlug}`;
48- openUrl(`${slug}/new-version`);
48+ void openUrl(`${slug}/new-version`);
4949 }
5050 };
5151
modified gui/src/hooks/ParallelListeners.tsx +5 −91
@@ -1,14 +1,10 @@
11 import { useCallback, useContext, useEffect, useRef } from "react";
22 import { IdeMessengerContext } from "../context/IdeMessenger";
33
4-import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
54 import { FromCoreProtocol } from "core/protocol";
65 import { useAppDispatch, useAppSelector } from "../redux/hooks";
76 import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice";
8-import {
9- setLastNonEditSessionEmpty,
10- updateEditStateApplyState,
11-} from "../redux/slices/editState";
7+import { setLastNonEditSessionEmpty } from "../redux/slices/editState";
128 import { updateIndexingStatus } from "../redux/slices/indexingSlice";
139 import {
1410 initializeProfilePreferences,
@@ -17,27 +13,21 @@
1713 setSelectedProfile,
1814 } from "../redux/slices/profilesSlice";
1915 import {
20- acceptToolCall,
2116 addContextItemsAtIndex,
2217 setHasReasoningEnabled,
2318 setIsSessionMetadataLoading,
24- updateApplyState,
2519 } from "../redux/slices/sessionSlice";
2620 import { setTTSActive } from "../redux/slices/uiSlice";
27-import { exitEdit } from "../redux/thunks/edit";
28-import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall";
2921
30-import { store } from "../redux/store";
3122 import { cancelStream } from "../redux/thunks/cancelStream";
23+import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate";
3224 import { refreshSessionMetadata } from "../redux/thunks/session";
3325 import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
34-import { findToolCallById, logToolUsage } from "../redux/util";
3526 import {
3627 setDocumentStylesFromLocalStorage,
3728 setDocumentStylesFromTheme,
3829 } from "../styles/theme";
3930 import { isJetBrains } from "../util";
40-import { logAgentModeEditOutcome } from "../util/editOutcomeLogger";
4131 import { setLocalStorage } from "../util/localStorage";
4232 import { migrateLocalStorage } from "../util/migrateLocalStorage";
4333 import { useWebviewListener } from "./useWebviewListener";
@@ -51,9 +41,7 @@
5141 (store) => store.profiles.selectedProfileId,
5242 );
5343 const hasDoneInitialConfigLoad = useRef(false);
54- const autoAcceptEditToolDiffs = useAppSelector(
55- (store) => store.config.config.ui?.autoAcceptEditToolDiffs,
56- );
44+
5745 // Load symbols for chat on any session change
5846 const sessionId = useAppSelector((state) => state.session.id);
5947
@@ -235,83 +223,9 @@
235223 useWebviewListener(
236224 "updateApplyState",
237225 async (state) => {
238- if (state.streamId === EDIT_MODE_STREAM_ID) {
239- dispatch(updateEditStateApplyState(state));
240-
241- if (state.status === "closed") {
242- const toolCallState = findToolCallById(
243- store.getState().session.history,
244- state.toolCallId!,
245- );
246- if (toolCallState) {
247- logToolUsage(toolCallState, true, true, ideMessenger);
248- }
249- void dispatch(exitEdit({}));
250- }
251- } else {
252- // chat or agent
253- dispatch(updateApplyState(state));
254-
255- // Handle apply status updates - use toolCallId from event payload
256- if (state.toolCallId) {
257- if (state.status === "done" && autoAcceptEditToolDiffs) {
258- ideMessenger.post("acceptDiff", {
259- streamId: state.streamId,
260- filepath: state.filepath,
261- });
262- }
263- if (state.status === "closed") {
264- // Find the tool call to check if it was canceled
265- const toolCallState = findToolCallById(
266- store.getState().session.history,
267- state.toolCallId,
268- );
269-
270- if (toolCallState) {
271- const accepted = toolCallState.status !== "canceled";
272-
273- logToolUsage(toolCallState, accepted, true, ideMessenger);
274-
275- // Log edit outcome for Agent Mode
276- const applyState = store
277- .getState()
278- .session.codeBlockApplyStates.states.find(
279- (s) => s.streamId === state.streamId,
280- );
281-
282- if (applyState) {
283- void logAgentModeEditOutcome(
284- toolCallState,
285- applyState,
286- accepted,
287- ideMessenger,
288- );
289- }
290-
291- if (accepted) {
292- dispatch(
293- acceptToolCall({
294- toolCallId: state.toolCallId,
295- }),
296- );
297- void dispatch(
298- streamResponseAfterToolCall({
299- toolCallId: state.toolCallId,
300- }),
301- );
302- }
303- }
304- // const output: ContextItem = {
305- // name: "Edit tool output",
306- // content: "Completed edit",
307- // description: "",
308- // };
309- // dispatch(setToolCallOutput([]));
310- }
311- }
312- }
226+ void dispatch(handleApplyStateUpdate(state));
313227 },
314- [autoAcceptEditToolDiffs, ideMessenger],
228+ [],
315229 );
316230
317231 useEffect(() => {
modified gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +8 −9
@@ -1,19 +1,16 @@
11 import { BuiltInToolNames } from "core/tools/builtIn";
2+import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar";
23 import {
34 addAndSelectMockLlm,
45 triggerConfigUpdate,
56 } from "../../../util/test/config";
67 import { renderWithProviders } from "../../../util/test/render";
78 import { Chat } from "../Chat";
8-import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar";
99
1010 import { waitFor } from "@testing-library/dom";
1111 import { act } from "@testing-library/react";
1212 import { ChatMessage } from "core";
13-import {
14- setToolPolicy,
15- toggleToolSetting,
16-} from "../../../redux/slices/uiSlice";
13+import { setToolPolicy } from "../../../redux/slices/uiSlice";
1714 import {
1815 getElementByTestId,
1916 getElementByText,
@@ -63,6 +60,7 @@
6360
6461 ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
6562 const messengerPostSpy = vi.spyOn(ideMessenger, "post");
63+ const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
6664
6765 addAndSelectMockLlm(store, ideMessenger);
6866
@@ -92,7 +90,7 @@
9290
9391 // Tool call, check that applyToFile was called for edit
9492 await waitFor(() => {
95- expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
93+ expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", {
9694 streamId: expect.any(String),
9795 filepath: EDIT_FILE_URI,
9896 text: EDIT_CHANGES,
@@ -101,7 +99,7 @@
10199 });
102100
103101 // Extract stream ID and initiate mock streaming
104- const streamId = messengerPostSpy.mock.calls.find(
102+ const streamId = messengerRequestSpy.mock.calls.find(
105103 (call) => call[0] === "applyToFile",
106104 )?.[1]?.streamId;
107105 expect(streamId).toBeDefined();
@@ -172,6 +170,7 @@
172170
173171 ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
174172 const messengerPostSpy = vi.spyOn(ideMessenger, "post");
173+ const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
175174
176175 addAndSelectMockLlm(store, ideMessenger);
177176
@@ -219,7 +218,7 @@
219218 );
220219 // Tool call, check that applyToFile was called for edit
221220 await waitFor(() => {
222- expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
221+ expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", {
223222 streamId: expect.any(String),
224223 filepath: EDIT_FILE_URI,
225224 text: EDIT_CHANGES,
@@ -228,7 +227,7 @@
228227 });
229228
230229 // Extract stream ID and initiate mock streaming
231- const streamId = messengerPostSpy.mock.calls.find(
230+ const streamId = messengerRequestSpy.mock.calls.find(
232231 (call) => call[0] === "applyToFile",
233232 )?.[1]?.streamId;
234233 expect(streamId).toBeDefined();
added gui/src/redux/thunks/handleApplyStateUpdate.ts +153 −0
@@ -0,0 +1,153 @@
1+import { createAsyncThunk } from "@reduxjs/toolkit";
2+import { ApplyState } from "core";
3+import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
4+import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger";
5+import {
6+ selectApplyStateByToolCallId,
7+ selectToolCallById,
8+} from "../selectors/selectToolCalls";
9+import { updateEditStateApplyState } from "../slices/editState";
10+import {
11+ acceptToolCall,
12+ errorToolCall,
13+ updateApplyState,
14+ updateToolCallOutput,
15+} from "../slices/sessionSlice";
16+import { ThunkApiType } from "../store";
17+import { findToolCallById, logToolUsage } from "../util";
18+import { exitEdit } from "./edit";
19+import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
20+
21+export const handleApplyStateUpdate = createAsyncThunk<
22+ void,
23+ ApplyState,
24+ ThunkApiType
25+>(
26+ "apply/handleStateUpdate",
27+ async (applyState, { dispatch, getState, extra }) => {
28+ if (applyState.streamId === EDIT_MODE_STREAM_ID) {
29+ dispatch(updateEditStateApplyState(applyState));
30+
31+ if (applyState.status === "closed") {
32+ const toolCallState = findToolCallById(
33+ getState().session.history,
34+ applyState.toolCallId!,
35+ );
36+ if (toolCallState) {
37+ logToolUsage(toolCallState, true, true, extra.ideMessenger);
38+ }
39+ void dispatch(exitEdit({}));
40+ }
41+ } else {
42+ // chat or agent
43+ dispatch(updateApplyState(applyState));
44+
45+ // Handle apply status updates - use toolCallId from event payload
46+ if (applyState.toolCallId) {
47+ if (
48+ applyState.status === "done" &&
49+ getState().config.config?.ui?.autoAcceptEditToolDiffs
50+ ) {
51+ extra.ideMessenger.post("acceptDiff", {
52+ streamId: applyState.streamId,
53+ filepath: applyState.filepath,
54+ });
55+ }
56+ if (applyState.status === "closed") {
57+ // Find the tool call to check if it was canceled
58+ const toolCallState = findToolCallById(
59+ getState().session.history,
60+ applyState.toolCallId,
61+ );
62+
63+ if (toolCallState) {
64+ const accepted = toolCallState.status !== "canceled";
65+
66+ logToolUsage(toolCallState, accepted, true, extra.ideMessenger);
67+
68+ // Log edit outcome for Agent Mode
69+ const newApplyState =
70+ getState().session.codeBlockApplyStates.states.find(
71+ (s) => s.streamId === applyState.streamId,
72+ );
73+ const newState = getState();
74+ if (newApplyState) {
75+ void logAgentModeEditOutcome(
76+ newState.session.history,
77+ newState.config.config,
78+ toolCallState,
79+ newApplyState,
80+ accepted,
81+ extra.ideMessenger,
82+ );
83+ }
84+
85+ if (accepted) {
86+ if (toolCallState.status !== "errored") {
87+ dispatch(
88+ acceptToolCall({
89+ toolCallId: applyState.toolCallId,
90+ }),
91+ );
92+ }
93+
94+ void dispatch(
95+ streamResponseAfterToolCall({
96+ toolCallId: applyState.toolCallId,
97+ }),
98+ );
99+ }
100+ }
101+ // TODO return output from edit tools so the model knows the result
102+ }
103+ }
104+ }
105+ },
106+);
107+
108+export const handleEditToolApplyError = createAsyncThunk<
109+ void,
110+ { toolCallId: string },
111+ ThunkApiType
112+>(
113+ "apply/handleEditError",
114+ async ({ toolCallId }, { dispatch, getState, extra }) => {
115+ const state = getState();
116+
117+ const toolCallState = selectToolCallById(state, toolCallId);
118+ const applyState = selectApplyStateByToolCallId(state, toolCallId);
119+ if (
120+ toolCallState &&
121+ applyState &&
122+ applyState.status !== "closed" &&
123+ toolCallState.status === "calling"
124+ ) {
125+ dispatch(
126+ errorToolCall({
127+ toolCallId,
128+ }),
129+ );
130+ dispatch(
131+ updateToolCallOutput({
132+ toolCallId,
133+ contextItems: [
134+ {
135+ icon: "problems",
136+ name: "Apply Error",
137+ description: "Failed to apply changes",
138+ content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`,
139+ hidden: false,
140+ },
141+ ],
142+ }),
143+ );
144+ void dispatch(
145+ handleApplyStateUpdate({
146+ status: "closed",
147+ streamId: applyState.streamId,
148+ toolCallId,
149+ }),
150+ );
151+ }
152+ },
153+);
modified gui/src/util/clientTools/editImpl.ts +25 −7
@@ -1,5 +1,7 @@
11 import { resolveRelativePathInDir } from "core/util/ideUtils";
22 import { v4 as uuid } from "uuid";
3+import { updateApplyState } from "../../redux/slices/sessionSlice";
4+import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
35 import { ClientToolImpl } from "./callClientTool";
46 export const editToolImpl: ClientToolImpl = async (
57 args,
@@ -19,13 +21,29 @@
1921 throw new Error(`${args.filepath} does not exist`);
2022 }
2123 const streamId = uuid();
22- extras.ideMessenger.post("applyToFile", {
23- streamId,
24- text: args.changes,
25- toolCallId,
26- filepath: firstUriMatch,
27- });
28-
24+ extras.dispatch(
25+ updateApplyState({
26+ streamId,
27+ toolCallId,
28+ status: "not-started",
29+ }),
30+ );
31+ void extras.ideMessenger
32+ .request("applyToFile", {
33+ streamId,
34+ text: args.changes,
35+ toolCallId,
36+ filepath: firstUriMatch,
37+ })
38+ .then((res) => {
39+ if (res.status === "error") {
40+ void extras.dispatch(
41+ handleEditToolApplyError({
42+ toolCallId,
43+ }),
44+ );
45+ }
46+ });
2947 return {
3048 respondImmediately: false,
3149 output: undefined, // No immediate output.
modified gui/src/util/clientTools/searchReplaceImpl.test.ts +0 −26
@@ -581,32 +581,6 @@
581581 ),
582582 ).rejects.toThrow("Failed to apply search and replace: File read error");
583583 });
584-
585- it("should handle applyToFile errors", async () => {
586- mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt");
587- mockParseAllSearchReplaceBlocks.mockReturnValue([
588- {
589- isComplete: true,
590- searchContent: "content",
591- replaceContent: "replacement",
592- },
593- ]);
594- mockIdeMessenger.ide.readFile.mockResolvedValue("content");
595- mockFindSearchMatch.mockReturnValue({
596- startIndex: 0,
597- endIndex: 7,
598- strategyName: "exactMatch",
599- });
600- mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
601-
602- await expect(
603- searchReplaceToolImpl(
604- { filepath: "test.txt", diffs: ["mock diff content"] },
605- "tool-call-id",
606- mockExtras,
607- ),
608- ).rejects.toThrow("Failed to apply search and replace: Apply failed");
609- });
610584 });
611585
612586 describe("edge cases", () => {
modified gui/src/util/clientTools/searchReplaceImpl.ts +27 −8
@@ -3,6 +3,8 @@
33 import { resolveRelativePathInDir } from "core/util/ideUtils";
44 import posthog from "posthog-js";
55 import { v4 as uuid } from "uuid";
6+import { updateApplyState } from "../../redux/slices/sessionSlice";
7+import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
68 import { ClientToolImpl } from "./callClientTool";
79
810 export const searchReplaceToolImpl: ClientToolImpl = async (
@@ -81,14 +83,31 @@
8183 // Single applyToFile call with all accumulated changes
8284 // This works becaues of our logic in `applyCodeBlock` that determines
8385 // that the full file rewrite here can be applied instantly, so the diff
84- // lines are just st
85- await extras.ideMessenger.request("applyToFile", {
86- streamId,
87- toolCallId,
88- text: currentContent,
89- filepath: resolvedFilepath,
90- isSearchAndReplace: true,
91- });
86+ // lines are generated with meyers diff and streamed instantaneously
87+ extras.dispatch(
88+ updateApplyState({
89+ streamId,
90+ toolCallId,
91+ status: "not-started",
92+ }),
93+ );
94+ void extras.ideMessenger
95+ .request("applyToFile", {
96+ streamId,
97+ toolCallId,
98+ text: currentContent,
99+ filepath: resolvedFilepath,
100+ isSearchAndReplace: true,
101+ })
102+ .then((res) => {
103+ if (res.status === "error") {
104+ void extras.dispatch(
105+ handleEditToolApplyError({
106+ toolCallId,
107+ }),
108+ );
109+ }
110+ });
92111
93112 // Return success - applyToFile will handle the completion state
94113 return {
modified gui/src/util/editOutcomeLogger.test.ts +33 −3
@@ -1,5 +1,10 @@
1-import { ApplyState, ToolCallState } from "core";
1+import {
2+ ApplyState,
3+ BrowserSerializedContinueConfig,
4+ ToolCallState,
5+} from "core";
26 import { describe, expect, it, vi } from "vitest";
7+import { EMPTY_CONFIG } from "../redux/slices/configSlice";
38 import { assembleEditOutcomeData } from "./editOutcomeLogger";
49
510 vi.mock("../redux/store", () => ({
@@ -17,6 +22,19 @@
1722 },
1823 }));
1924
25+const EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED: BrowserSerializedContinueConfig = {
26+ ...EMPTY_CONFIG,
27+ selectedModelByRole: {
28+ ...EMPTY_CONFIG.selectedModelByRole,
29+ chat: {
30+ provider: "test",
31+ model: "test-model",
32+ title: "Test model",
33+ underlyingProviderName: "provider",
34+ },
35+ },
36+};
37+
2038 describe("assembleEditOutcomeData", () => {
2139 it("should assemble complete edit outcome data correctly", () => {
2240 const toolCallState: ToolCallState = {
@@ -37,7 +55,13 @@
3755 fileContent: "const new = 2;\nconst another = 3;",
3856 };
3957
40- const result = assembleEditOutcomeData(toolCallState, applyState, true);
58+ const result = assembleEditOutcomeData(
59+ [],
60+ EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED,
61+ toolCallState,
62+ applyState,
63+ true,
64+ );
4165 console.log(result);
4266
4367 expect(result).toMatchObject({
@@ -71,7 +95,13 @@
7195 fileContent: "",
7296 };
7397
74- const result = assembleEditOutcomeData(toolCallState, applyState, false);
98+ const result = assembleEditOutcomeData(
99+ [],
100+ EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED,
101+ toolCallState,
102+ applyState,
103+ false,
104+ );
75105
76106 expect(result.previousCodeLines).toBe(0);
77107 expect(result.newCodeLines).toBe(0);
modified gui/src/util/editOutcomeLogger.ts +26 −12
@@ -1,18 +1,23 @@
1-import { ApplyState, ToolCallState } from "core";
1+import {
2+ ApplyState,
3+ BrowserSerializedContinueConfig,
4+ ToolCallState,
5+} from "core";
26 import { IIdeMessenger } from "../context/IdeMessenger";
3-import { store } from "../redux/store";
7+import { ChatHistoryItemWithMessageId } from "../redux/slices/sessionSlice";
48
59 /**
610 * Extract model information from tool call state
711 */
8-function extractModelInfo(toolCallState: ToolCallState): {
12+function extractModelInfo(
13+ history: ChatHistoryItemWithMessageId[],
14+ config: BrowserSerializedContinueConfig,
15+ toolCallState: ToolCallState,
16+): {
917 modelProvider: string;
1018 modelName: string;
1119 modelTitle: string;
1220 } {
13- // Get the conversation history to find the model info
14- const history = store.getState().session.history;
15-
1621 // Find the assistant message that contains this tool call
1722 const assistantMessage = history.find(
1823 (item) =>
@@ -35,7 +40,6 @@
3540 }
3641
3742 // Fallback to config if not found in message
38- const config = store.getState().config.config;
3943 const chatModel = config?.selectedModelByRole?.chat;
4044
4145 return {
@@ -48,12 +52,13 @@
4852 /**
4953 * Extract prompt and completion from tool call state
5054 */
51-function extractPromptAndCompletion(toolCallState: ToolCallState): {
55+function extractPromptAndCompletion(
56+ history: ChatHistoryItemWithMessageId[],
57+ toolCallState: ToolCallState,
58+): {
5259 prompt: string;
5360 completion: string;
5461 } {
55- const history = store.getState().session.history;
56-
5762 // Find the assistant message with this tool call
5863 const assistantMessageIndex = history.findIndex(
5964 (item) =>
@@ -144,12 +149,17 @@
144149 * Assemble complete edit outcome data from tool call and apply state
145150 */
146151 export function assembleEditOutcomeData(
152+ history: ChatHistoryItemWithMessageId[],
153+ config: BrowserSerializedContinueConfig,
147154 toolCallState: ToolCallState,
148155 applyState: ApplyState,
149156 accepted: boolean,
150157 ) {
151- const modelInfo = extractModelInfo(toolCallState);
152- const promptAndCompletion = extractPromptAndCompletion(toolCallState);
158+ const modelInfo = extractModelInfo(history, config, toolCallState);
159+ const promptAndCompletion = extractPromptAndCompletion(
160+ history,
161+ toolCallState,
162+ );
153163 const codeChanges = extractCodeChanges(applyState);
154164
155165 return {
@@ -174,6 +184,8 @@
174184 * Log Agent Mode edit outcome to editOutcome.jsonl
175185 */
176186 export async function logAgentModeEditOutcome(
187+ history: ChatHistoryItemWithMessageId[],
188+ config: BrowserSerializedContinueConfig,
177189 toolCallState: ToolCallState,
178190 applyState: ApplyState,
179191 accepted: boolean,
@@ -182,6 +194,8 @@
182194 // Use the original file content stored in applyState, captured before edits were applied
183195
184196 const editOutcomeData = assembleEditOutcomeData(
197+ history,
198+ config,
185199 toolCallState,
186200 applyState,
187201 accepted,
modified package-lock.json +1 −1
@@ -1,5 +1,5 @@
11 {
2- "name": "continue",
2+ "name": "wt-nate-4",
33 "lockfileVersion": 3,
44 "requires": true,
55 "packages": {
modified packages/config-yaml/src/load/merge.ts +2 −0
@@ -13,6 +13,7 @@
1313 rules: [...(current.rules ?? []), ...(incoming.rules ?? [])],
1414 prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])],
1515 docs: [...(current.docs ?? []), ...(incoming.docs ?? [])],
16+ env: { ...current.env, ...incoming.env },
1617 };
1718 }
1819
@@ -29,5 +30,6 @@
2930 data: [...(current.data ?? []), ...(incoming.data ?? [])],
3031 mcpServers: [...(current.mcpServers ?? []), ...(incoming.mcpServers ?? [])],
3132 prompts: [...(current.prompts ?? []), ...(incoming.prompts ?? [])],
33+ env: { ...current.env, ...incoming.env },
3234 };
3335 }
modified packages/config-yaml/src/load/unroll.ts +1 −1
@@ -321,7 +321,7 @@
321321
322322 const sections: (keyof Omit<
323323 ConfigYaml,
324- "name" | "version" | "rules" | "schema" | "metadata"
324+ "name" | "version" | "rules" | "schema" | "metadata" | "env"
325325 >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"];
326326
327327 // Process all sections in parallel
modified packages/config-yaml/src/schemas/index.ts +7 −0
@@ -105,11 +105,17 @@
105105 iconUrl: z.string().optional(),
106106 });
107107
108+const envRecord = z.record(
109+ z.string(),
110+ z.union([z.string(), z.number(), z.boolean()]),
111+);
112+
108113 export const baseConfigYamlSchema = z.object({
109114 name: z.string(),
110115 version: z.string(),
111116 schema: z.string().optional(),
112117 metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(),
118+ env: envRecord.optional(),
113119 });
114120
115121 const modelsUsesSchema = z
@@ -254,6 +260,7 @@
254260 proxy: z.string().optional(),
255261 api_base: z.string().optional(),
256262 api_key: z.string().optional(),
263+ env: envRecord.optional(),
257264 });
258265
259266 export type Config = z.infer<typeof configSchema>;
modified packages/continue-sdk/package-lock.json +5 −3
@@ -1124,13 +1124,15 @@
11241124 }
11251125 },
11261126 "node_modules/form-data": {
1127- "version": "4.0.2",
1128- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
1129- "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
1127+ "version": "4.0.4",
1128+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
1129+ "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
1130+ "license": "MIT",
11301131 "dependencies": {
11311132 "asynckit": "^0.4.0",
11321133 "combined-stream": "^1.0.8",
11331134 "es-set-tostringtag": "^2.1.0",
1135+ "hasown": "^2.0.2",
11341136 "mime-types": "^2.1.12"
11351137 },
11361138 "engines": {
modified packages/openai-adapters/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 packages/openai-adapters/package.json +1 −0
@@ -35,6 +35,7 @@
3535 "@types/follow-redirects": "^1.14.4",
3636 "@types/jest": "^29.5.14",
3737 "@types/json-schema": "^7.0.15",
38+ "@types/node": "^24.3.0",
3839 "cross-env": "^7.0.3",
3940 "semantic-release": "^24.2.7",
4041 "ts-jest": "^29.2.3",