Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into plan-mode-sys-prompt
Changeset92c2e10596054ec7a45fce6038159c4dc81c2bc1610c8230a2d75138172baf36
AuthorNate <sestinj@gmail.com> · 2025-08-23 12:30 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-23 12:30 -07:00
Parentsdc523ee971e7, 8eb3ae7b8d16

Browse the files at this changeset

83 files changed

modified .github/actions/run-jetbrains-tests/action.yml +11 −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
@@ -135,14 +136,22 @@
135136 shell: bash
136137 run: |
137138 cd extensions/intellij
138- 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
139144
140145 - name: Copy logs
141146 if: ${{ failure() }}
142147 shell: bash
143148 run: |
144149 cd extensions/intellij
145- 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
146155
147156 - name: Save fails report
148157 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 +1 −1
@@ -18,7 +18,7 @@
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 }}
modified .github/workflows/cli-pr-checks.yml +10 −4
@@ -3,8 +3,6 @@
33 on:
44 pull_request:
55 branches: [main]
6- paths:
7- - "extensions/cli/**"
86
97 permissions:
108 contents: read
@@ -12,11 +10,19 @@
1210 issues: write
1311
1412 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+
1521 lint:
1622 runs-on: ubuntu-latest
1723 steps:
1824 - name: Checkout code
19- uses: actions/checkout@v4
25+ uses: actions/checkout@v5
2026
2127 - name: Setup Node.js
2228 uses: actions/setup-node@v4
@@ -52,7 +58,7 @@
5258
5359 steps:
5460 - name: Checkout code
55- uses: actions/checkout@v4
61+ uses: actions/checkout@v5
5662
5763 - name: Setup Node.js ${{ matrix.node-version }}
5864 uses: actions/setup-node@v4
modified .github/workflows/compliance.yaml +1 −1
@@ -36,7 +36,7 @@
3636 else
3737 echo "❌ PR title does not follow conventional commit format"
3838 echo "valid=false" >> $GITHUB_OUTPUT
39- exit 1
39+ # Don't exit with failure - just mark as invalid for comment
4040 fi
4141
4242 - name: Add PR title guidance comment
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 +1 −1
@@ -34,7 +34,7 @@
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 }}
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([
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/nextEdit/NextEditProvider.ts +136 −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,39 +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";
3320 import { isSecurityConcern } from "../indexing/ignore.js";
3421 import { modelSupportsNextEdit } from "../llm/autodetect.js";
35-import { NEXT_EDIT_MODELS } from "../llm/constants.js";
3622 import { countTokens } from "../llm/countTokens.js";
3723 import { localPathOrUriToPath } from "../util/pathToUri.js";
38-import {
39- INSTINCT_SYSTEM_PROMPT,
40- MERCURY_SYSTEM_PROMPT,
41- MODEL_WINDOW_SIZES,
42- UNIQUE_TOKEN,
43-} from "./constants.js";
4424 import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
45-import {
46- calculateFinalCursorPosition,
47- DiffGroup,
48- groupDiffLines,
49-} from "./diff/diff.js";
5025 import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
5126 import { NextEditLoggingService } from "./NextEditLoggingService.js";
5227 import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
28+import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
29+import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
5330 import {
54- renderDefaultSystemPrompt,
55- renderDefaultUserPrompt,
56- renderPrompt,
57-} from "./templating/NextEditPromptEngine.js";
58-import {
31+ ModelSpecificContext,
5932 NextEditOutcome,
6033 Prompt,
6134 PromptMetadata,
6235 RecentlyEditedRange,
6336 } from "./types.js";
64-import { isWhitespaceOnlyDeletion } from "./utils.js";
6537
6638 const autocompleteCache = AutocompleteLruCache.get();
6739
@@ -92,6 +64,9 @@
9264 private previousCompletions: NextEditOutcome[] = [];
9365 // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
9466
67+ // Model-specific provider instance.
68+ private modelProvider: BaseNextEditProvider | null = null;
69+
9570 private constructor(
9671 private readonly configHandler: ConfigHandler,
9772 private readonly ide: IDE,
@@ -298,28 +273,23 @@
298273 } = await this._initializeCompletionRequest(input, token);
299274 if (!helper) return undefined;
300275
276+ // Create model-specific provider based on the model name.
277+ this.modelProvider = NextEditProviderFactory.createProvider(
278+ helper.modelName,
279+ );
280+
301281 const { editableRegionStartLine, editableRegionEndLine, prompts } =
302282 await this._generatePrompts(helper, opts);
303283
304- if (this.endpointType === "default") {
305- return await this._handleDefaultEndpointCompletion(
306- helper,
307- prompts,
308- abortToken,
309- startTime,
310- editableRegionEndLine,
311- );
312- } else {
313- return await this._handleFineTunedEndpointCompletion(
314- helper,
315- prompts,
316- abortToken,
317- startTime,
318- editableRegionStartLine,
319- editableRegionEndLine,
320- opts,
321- );
322- }
284+ return await this._handleCompletion(
285+ helper,
286+ prompts,
287+ abortToken,
288+ startTime,
289+ editableRegionStartLine,
290+ editableRegionEndLine,
291+ opts,
292+ );
323293 } catch (e: any) {
324294 this.onError(e);
325295 } finally {
@@ -335,7 +305,7 @@
335305 startTime: number;
336306 helper: HelperVars | undefined;
337307 }> {
338- // Create abort signal if not given.
308+ // Create abort signal if not given
339309 if (!token) {
340310 const controller = this.loggingService.createAbortController(
341311 input.completionId,
@@ -345,7 +315,7 @@
345315 const startTime = Date.now();
346316 const options = await this._getAutocompleteOptions();
347317
348- // Debounce.
318+ // Debounce
349319 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
350320 return { token, startTime, helper: undefined };
351321 }
@@ -355,9 +325,7 @@
355325 return { token, startTime, helper: undefined };
356326 }
357327
358- // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
359- // For other editors, this check should be done in their respective config reloaders.
360- // This is left for a final check.
328+ // Check model capabilities
361329 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
362330 console.error(`${llm.model} is not capable of next edit.`);
363331 return { token, startTime, helper: undefined };
@@ -387,6 +355,10 @@
387355 editableRegionEndLine: number;
388356 prompts: Prompt[];
389357 }> {
358+ if (!this.modelProvider) {
359+ throw new Error("Model provider not initialized");
360+ }
361+
390362 const [snippetPayload, workspaceDirs] = await Promise.all([
391363 getAllSnippetsWithoutRace({
392364 helper,
@@ -397,56 +369,118 @@
397369 this.ide.getWorkspaceDirs(),
398370 ]);
399371
400- const modelName = helper.modelName.includes(
401- NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
402- )
403- ? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
404- : helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
405- ? NEXT_EDIT_MODELS.MERCURY_CODER
406- : NEXT_EDIT_MODELS.INSTINCT;
407-
372+ // Calculate editable region based on model and options.
408373 const { editableRegionStartLine, editableRegionEndLine } =
409- opts?.usingFullFileDiff
410- ? this._calculateOptimalEditableRegion(helper, "tokenizer")
411- : {
412- editableRegionStartLine: Math.max(
413- helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
414- 0,
415- ),
416- editableRegionEndLine: Math.min(
417- helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
418- helper.fileLines.length - 1,
419- ),
420- };
421-
422- // const editableRegionStartLine = opts?.usingFullFileDiff
423- // ? 0
424- // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
425-
426- // const editableRegionEndLine = opts?.usingFullFileDiff
427- // ? helper.fileLines.length - 1
428- // : Math.min(
429- // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
430- // helper.fileLines.length - 1,
431- // );
432-
433- const prompts: Prompt[] = [];
434-
435- if (this.endpointType === "default") {
436- prompts.push(renderDefaultSystemPrompt());
437- 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+ );
438462 } else {
439- prompts.push(
440- ...(await this._generateFineTunedPrompts(
441- helper,
442- snippetPayload,
443- editableRegionStartLine,
444- editableRegionEndLine,
445- )),
463+ outcome = await this.modelProvider.handleFullFileDiff(
464+ helper,
465+ editableRegionStartLine,
466+ editableRegionEndLine,
467+ startTime,
468+ llm,
469+ nextCompletion,
470+ this.promptMetadata!,
471+ this.ide,
446472 );
447473 }
448474
449- 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;
450484 }
451485
452486 private _calculateOptimalEditableRegion(
@@ -540,500 +574,6 @@
540574 };
541575 }
542576
543- private async _generateFineTunedPrompts(
544- helper: HelperVars,
545- snippetPayload: SnippetPayload,
546- editableRegionStartLine: number,
547- editableRegionEndLine: number,
548- ): Promise<Prompt[]> {
549- const historyDiff = createDiff({
550- beforeContent:
551- DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
552- localPathOrUriToPath(helper.filepath),
553- ) ?? "",
554- afterContent: helper.fileContents,
555- filePath: helper.filepath,
556- diffType: DiffFormatType.Unified,
557- contextLines: 3,
558- });
559-
560- const modelName = helper.modelName;
561- let ctx: any;
562-
563- if (
564- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
565- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
566- ) {
567- ctx = {
568- recentlyViewedCodeSnippets:
569- snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
570- filepath: snip.filepath,
571- content: snip.content,
572- })) ?? [],
573- currentFileContent: helper.fileContents,
574- editableRegionStartLine,
575- editableRegionEndLine,
576- editDiffHistory: this.diffContext,
577- currentFilePath: helper.filepath,
578- };
579- } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
580- // Calculate the window around the cursor position (25 lines above and below).
581- const windowStart = Math.max(0, helper.pos.line - 25);
582- const windowEnd = Math.min(
583- helper.fileLines.length - 1,
584- helper.pos.line + 25,
585- );
586-
587- // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
588- // const actualEditableStart = Math.max(
589- // 0,
590- // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
591- // );
592- // const actualEditableEnd = Math.min(
593- // helper.fileLines.length - 1,
594- // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
595- // );
596-
597- // Ensure editable region boundaries are within the window.
598- const adjustedEditableStart = Math.max(
599- windowStart,
600- editableRegionStartLine,
601- );
602- const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
603- ctx = {
604- contextSnippets: this.autocompleteContext,
605- currentFileContent: helper.fileContents,
606- windowStart,
607- windowEnd,
608- editableRegionStartLine: adjustedEditableStart,
609- editableRegionEndLine: adjustedEditableEnd,
610- editDiffHistory: this.diffContext,
611- currentFilePath: helper.filepath,
612- languageShorthand: helper.lang.name,
613- };
614- } else {
615- ctx = {};
616- }
617-
618- const promptMetadata = await renderPrompt(helper, ctx);
619- this.promptMetadata = promptMetadata;
620-
621- const systemPrompt: Prompt = {
622- role: "system",
623- content:
624- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
625- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
626- ? MERCURY_SYSTEM_PROMPT
627- : INSTINCT_SYSTEM_PROMPT,
628- };
629-
630- return [systemPrompt, promptMetadata.prompt];
631- }
632-
633- private async _handleDefaultEndpointCompletion(
634- helper: HelperVars,
635- prompts: Prompt[],
636- token: AbortSignal,
637- startTime: number,
638- editableRegionEndLine: number,
639- ): Promise<NextEditOutcome | undefined> {
640- const llm = await this._prepareLlm();
641- if (!llm) return undefined;
642-
643- const msg: ChatMessage = await llm.chat(prompts, token);
644-
645- if (typeof msg.content === "string") {
646- const nextCompletion = JSON.parse(msg.content).newCode;
647- const finalCursorPos: Position = {
648- line: editableRegionEndLine,
649- character: 0,
650- };
651-
652- const outcomeNext = await this._createNextEditOutcome({
653- helper,
654- startTime,
655- llm,
656- promptContent: prompts.join("\n"),
657- completion: nextCompletion,
658- finalCursorPosition: finalCursorPos,
659- editableRegionStartLine: 0,
660- editableRegionEndLine: 0,
661- userEdits: "",
662- userExcerpts: "",
663- originalEditableRange: "",
664- diffLines: [],
665- });
666-
667- // Mark as displayed for JetBrains extension
668- await this._markDisplayedIfJetBrains(
669- helper.input.completionId,
670- outcomeNext,
671- );
672-
673- return outcomeNext;
674- }
675-
676- return undefined;
677- }
678-
679- private async _handleFineTunedEndpointCompletion(
680- helper: HelperVars,
681- prompts: Prompt[],
682- token: AbortSignal,
683- startTime: number,
684- editableRegionStartLine: number,
685- editableRegionEndLine: number,
686- opts?: {
687- withChain: boolean;
688- usingFullFileDiff: boolean;
689- },
690- ): Promise<NextEditOutcome | undefined> {
691- const llm = await this._prepareLlm();
692- if (!llm) return undefined;
693-
694- // Check for mercury models, and inject unique token for next edit.
695- // Capture the unique tokens in llm Inception.ts and apis Inception.ts
696- const modelName = helper.modelName;
697- if (
698- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
699- modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
700- ) {
701- // Inject the unique token to the last prompt's content.
702- const lastPrompt = prompts[prompts.length - 1];
703- if (lastPrompt && typeof lastPrompt.content === "string") {
704- lastPrompt.content += UNIQUE_TOKEN;
705- }
706- }
707-
708- const msg: ChatMessage = await llm.chat([prompts[1]], token, {
709- stream: false,
710- });
711-
712- if (typeof msg.content !== "string") {
713- return undefined;
714- }
715-
716- // NOTE: Keep this in case there is a change in spec.
717- // const nextCompletion =
718- // msg.content
719- // .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
720- // .replace(/\n$/, "") ?? msg.content;
721- const nextCompletion = msg.content.slice(
722- msg.content.indexOf("```\n") + "'''\n".length,
723- msg.content.lastIndexOf("\n\n```"),
724- );
725-
726- if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
727- return await this._handlePartialFileDiff(
728- // we could use fillFileDiff
729- helper,
730- editableRegionStartLine,
731- editableRegionEndLine,
732- startTime,
733- llm,
734- nextCompletion,
735- );
736- } else {
737- return await this._handleFullFileDiff(
738- helper,
739- editableRegionStartLine,
740- editableRegionEndLine,
741- startTime,
742- llm,
743- nextCompletion,
744- );
745- }
746- }
747-
748- private async _handlePartialFileDiff(
749- helper: HelperVars,
750- editableRegionStartLine: number,
751- editableRegionEndLine: number,
752- startTime: number,
753- llm: ILLM,
754- nextCompletion: string,
755- ): Promise<NextEditOutcome | undefined> {
756- const oldEditRangeSlice = helper.fileContents
757- .split("\n")
758- .slice(editableRegionStartLine, editableRegionEndLine + 1)
759- .join("\n");
760-
761- const finalCursorPos = calculateFinalCursorPosition(
762- helper.pos,
763- editableRegionStartLine,
764- oldEditRangeSlice,
765- nextCompletion,
766- );
767-
768- const outcomeNext = await this._createNextEditOutcome({
769- helper,
770- startTime,
771- llm,
772- promptContent: this.promptMetadata!.prompt.content,
773- completion: nextCompletion,
774- finalCursorPosition: finalCursorPos,
775- editableRegionStartLine,
776- editableRegionEndLine,
777- userEdits: this.promptMetadata!.userEdits,
778- userExcerpts: this.promptMetadata!.userExcerpts,
779- originalEditableRange: oldEditRangeSlice,
780- diffLines: [],
781- });
782-
783- this.previousCompletions.push(outcomeNext);
784-
785- // Mark as displayed for JetBrains extension
786- await this._markDisplayedIfJetBrains(
787- helper.input.completionId,
788- outcomeNext,
789- );
790-
791- return outcomeNext;
792- }
793-
794- private async _handleFullFileDiff(
795- helper: HelperVars,
796- editableRegionStartLine: number,
797- editableRegionEndLine: number,
798- startTime: number,
799- llm: ILLM,
800- nextCompletion: string,
801- ): Promise<NextEditOutcome | undefined> {
802- const fileSlice = helper.fileLines
803- .slice(editableRegionStartLine, editableRegionEndLine + 1)
804- .join("\n");
805- const diffLines = myersDiff(fileSlice, nextCompletion);
806- const diffGroups = groupDiffLines(
807- diffLines,
808- editableRegionStartLine,
809- 5,
810- ).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
811- const currentLine = helper.pos.line;
812- const prefetchQueue = PrefetchQueue.getInstance();
813-
814- // Process diff groups and find the one containing the cursor
815- const cursorLocalDiffGroup = await this._processDiffGroups(
816- diffGroups,
817- currentLine,
818- helper,
819- startTime,
820- llm,
821- prefetchQueue,
822- );
823-
824- // Handle the diff group containing the cursor if found
825- if (cursorLocalDiffGroup) {
826- return await this._createOutcomeFromDiffGroup(
827- cursorLocalDiffGroup,
828- helper,
829- startTime,
830- llm,
831- helper.input.completionId,
832- true,
833- );
834- // } else if (diffGroups.length > 0) {
835- // // Fallback to first diff group if cursor's group not found
836- // return await this._createOutcomeFromDiffGroup(
837- // diffGroups[0],
838- // helper,
839- // startTime,
840- // llm,
841- // helper.input.completionId,
842- // false,
843- // );
844- }
845-
846- return undefined;
847- }
848-
849- private async _processDiffGroups(
850- diffGroups: DiffGroup[],
851- currentLine: number,
852- helper: HelperVars,
853- startTime: number,
854- llm: ILLM,
855- prefetchQueue: PrefetchQueue,
856- ): Promise<DiffGroup | undefined> {
857- let cursorGroup: DiffGroup | undefined;
858-
859- console.log("diffGroups:");
860- console.log(diffGroups);
861-
862- for (const group of diffGroups) {
863- if (currentLine >= group.startLine && currentLine <= group.endLine) {
864- cursorGroup = group;
865- } else {
866- // Add non-cursor groups to prefetch queue
867- await this._addDiffGroupToPrefetchQueue(
868- group,
869- helper,
870- startTime,
871- llm,
872- prefetchQueue,
873- );
874- }
875- }
876-
877- return cursorGroup;
878- }
879-
880- private async _addDiffGroupToPrefetchQueue(
881- group: DiffGroup,
882- helper: HelperVars,
883- startTime: number,
884- llm: ILLM,
885- prefetchQueue: PrefetchQueue,
886- ): Promise<void> {
887- const groupContent = group.lines
888- .filter((l) => l.type !== "old")
889- .map((l) => l.line)
890- .join("\n");
891-
892- // Create a range for this diff group
893- const rangeInFile: RangeInFile = {
894- filepath: helper.filepath,
895- range: {
896- start: { line: group.startLine, character: 0 },
897- end: {
898- line: group.endLine,
899- character: group.lines[group.lines.length - 1].line.length,
900- },
901- },
902- };
903-
904- const originalContent = group.lines
905- .filter((l) => l.type !== "new")
906- .map((l) => l.line)
907- .join("\n");
908-
909- // Build outcome for this diff group
910- const groupOutcome = await this._createNextEditOutcome({
911- helper,
912- startTime,
913- llm,
914- promptContent: this.promptMetadata!.prompt.content,
915- completion: groupContent,
916- finalCursorPosition: {
917- line: group.endLine,
918- character: group.lines[group.lines.length - 1].line.length,
919- },
920- editableRegionStartLine: group.startLine,
921- editableRegionEndLine: group.endLine,
922- userEdits: this.promptMetadata!.userEdits,
923- userExcerpts: this.promptMetadata!.userExcerpts,
924- originalEditableRange: originalContent,
925- cursorPosition: { line: group.startLine, character: 0 },
926- completionId: uuidv4(), // Generate a new ID for this prefetched item
927- diffLines: group.lines,
928- });
929-
930- // Add to prefetch queue
931- prefetchQueue.enqueueProcessed({
932- location: rangeInFile,
933- outcome: groupOutcome,
934- });
935- }
936-
937- private async _createOutcomeFromDiffGroup(
938- diffGroup: DiffGroup,
939- helper: HelperVars,
940- startTime: number,
941- llm: ILLM,
942- completionId: string,
943- isCurrentCursorGroup: boolean,
944- ): Promise<NextEditOutcome> {
945- const groupContent = diffGroup.lines
946- .filter((l) => l.type !== "old")
947- .map((line) => line.line)
948- .join("\n");
949-
950- const originalContent = diffGroup.lines
951- .filter((l) => l.type !== "new")
952- .map((l) => l.line)
953- .join("\n");
954-
955- // Use the actual cursor position if this is the group containing the cursor
956- // Otherwise use the start of the diff group
957- const cursorPos = isCurrentCursorGroup
958- ? helper.pos
959- : { line: diffGroup.startLine, character: 0 };
960-
961- const finalCursorPos = calculateFinalCursorPosition(
962- cursorPos,
963- diffGroup.startLine,
964- originalContent,
965- groupContent,
966- );
967-
968- const outcomeNext = await this._createNextEditOutcome({
969- helper,
970- startTime,
971- llm,
972- promptContent: this.promptMetadata!.prompt.content,
973- completion: groupContent,
974- finalCursorPosition: finalCursorPos,
975- editableRegionStartLine: diffGroup.startLine,
976- editableRegionEndLine: diffGroup.endLine,
977- userEdits: this.promptMetadata!.userEdits,
978- userExcerpts: this.promptMetadata!.userExcerpts,
979- originalEditableRange: originalContent,
980- cursorPosition: cursorPos,
981- completionId,
982- diffLines: diffGroup.lines,
983- });
984-
985- this.previousCompletions.push(outcomeNext);
986-
987- // Mark as displayed for JetBrains
988- await this._markDisplayedIfJetBrains(completionId, outcomeNext);
989-
990- return outcomeNext;
991- }
992-
993- private async _createNextEditOutcome(outcomeCtx: {
994- helper: HelperVars;
995- startTime: number;
996- llm: ILLM;
997- promptContent: string;
998- completion: string;
999- finalCursorPosition: Position;
1000- editableRegionStartLine: number;
1001- editableRegionEndLine: number;
1002- userEdits: string;
1003- userExcerpts: string;
1004- originalEditableRange: string;
1005- cursorPosition?: Position;
1006- completionId?: string;
1007- diffLines: DiffLine[];
1008- }): Promise<NextEditOutcome> {
1009- return {
1010- elapsed: Date.now() - outcomeCtx.startTime,
1011- modelProvider: outcomeCtx.llm.underlyingProviderName,
1012- modelName: outcomeCtx.llm.model + ":zetaDataset",
1013- completionOptions: null,
1014- completionId:
1015- outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
1016- gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
1017- uniqueId: await this.ide.getUniqueId(),
1018- timestamp: Date.now(),
1019- fileUri: outcomeCtx.helper.filepath,
1020- workspaceDirUri:
1021- outcomeCtx.helper.workspaceUris[0] ??
1022- path.dirname(outcomeCtx.helper.filepath),
1023- prompt: outcomeCtx.promptContent,
1024- userEdits: outcomeCtx.userEdits ?? "",
1025- userExcerpts: outcomeCtx.userExcerpts ?? "",
1026- originalEditableRange: outcomeCtx.originalEditableRange ?? "",
1027- completion: outcomeCtx.completion,
1028- cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
1029- finalCursorPosition: outcomeCtx.finalCursorPosition,
1030- editableRegionStartLine: outcomeCtx.editableRegionStartLine,
1031- editableRegionEndLine: outcomeCtx.editableRegionEndLine,
1032- diffLines: outcomeCtx.diffLines,
1033- ...outcomeCtx.helper.options,
1034- };
1035- }
1036-
1037577 private async _markDisplayedIfJetBrains(
1038578 completionId: string,
1039579 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
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/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 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 +1 −1
@@ -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">
modified docs/docs.json +4 −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"
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 +1 −39
@@ -10,45 +10,7 @@
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
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/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 extensions/cli/build.mjs +12 −6
@@ -1,8 +1,8 @@
11 #!/usr/bin/env node
22
33 import * as esbuild from "esbuild";
4-import { writeFileSync, chmodSync } from "fs";
5-import { resolve, dirname } from "path";
4+import { chmodSync, writeFileSync } from "fs";
5+import { dirname, resolve } from "path";
66 import { fileURLToPath } from "url";
77
88 const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -59,9 +59,15 @@
5959 __dirname,
6060 "../../packages/config-types/dist/index.js",
6161 ),
62- "core": resolve(__dirname, "../../core"),
63- "@continuedev/fetch": resolve(__dirname, "../../packages/fetch/dist/index.js"),
64- "@continuedev/llm-info": resolve(__dirname, "../../packages/llm-info/dist/index.js"),
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+ ),
6571 },
6672
6773 // Add banner to create require for CommonJS packages
@@ -76,7 +82,7 @@
7682
7783 // Create wrapper script with shebang
7884 writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
79-
85+
8086 // Make the wrapper script executable
8187 chmodSync("dist/cn.js", 0o755);
8288
modified extensions/cli/package.json +3 −3
@@ -15,11 +15,11 @@
1515 "test:e2e": "vitest run --config vitest.e2e.config.ts",
1616 "test:smoke": "node smoke-test.mjs",
1717 "build:tsc": "tsc -p tsconfig.build.json",
18- "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../openai-adapters && npm i && npm run build",
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",
1919 "build:validate": "node validate-aliases.mjs",
2020 "build:bundle": "node build.mjs",
21- "build": "npm run build:local-deps && npm run build:validate && npm run build:bundle",
22- "start": "node dist/index.js",
21+ "build": "npm run build:validate && npm run build:bundle",
22+ "start": "node dist/cn.js",
2323 "dev": "tsx src/index.ts",
2424 "repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
2525 "repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
modified extensions/cli/src/__mocks__/args.ts +3 −1
@@ -1,3 +1,5 @@
11 import { vi } from "vitest";
22
3-export const processRule = vi.fn<(rule: string) => Promise<string>>();
3+export const processPromptOrRule = vi.fn<(spec: string) => Promise<string>>();
4+
5+export const processPrompt = vi.fn<(prompt: string) => Promise<string>>();
added extensions/cli/src/args.prompt.test.ts +84 −0
@@ -0,0 +1,84 @@
1+import { describe, it, expect, beforeEach, afterAll } from "vitest";
2+
3+import { parseArgs, processPromptOrRule } from "./args.js";
4+
5+describe("args --prompt flag", () => {
6+ const originalArgv = process.argv;
7+
8+ beforeEach(() => {
9+ // Reset process.argv for each test
10+ process.argv = ["node", "script.js"];
11+ });
12+
13+ afterAll(() => {
14+ // Restore original process.argv after all tests
15+ process.argv = originalArgv;
16+ });
17+
18+ it("should parse single prompt from --prompt flag", () => {
19+ process.argv = ["node", "script.js", "--prompt", "my-prompt"];
20+ const result = parseArgs();
21+ expect(result.prompts).toEqual(["my-prompt"]);
22+ });
23+
24+ it("should parse multiple prompts from multiple --prompt flags", () => {
25+ process.argv = [
26+ "node",
27+ "script.js",
28+ "--prompt",
29+ "prompt1",
30+ "--prompt",
31+ "prompt2",
32+ ];
33+ const result = parseArgs();
34+ expect(result.prompts).toEqual(["prompt1", "prompt2"]);
35+ });
36+
37+ it("should handle mixed flags including --prompt", () => {
38+ process.argv = [
39+ "node",
40+ "script.js",
41+ "--config",
42+ "myconfig",
43+ "--prompt",
44+ "myprompt",
45+ "--resume",
46+ ];
47+ const result = parseArgs();
48+ expect(result.configPath).toBe("myconfig");
49+ expect(result.prompts).toEqual(["myprompt"]);
50+ expect(result.resume).toBe(true);
51+ });
52+
53+ it("should not include --prompt value in non-flag arguments", () => {
54+ process.argv = [
55+ "node",
56+ "script.js",
57+ "--prompt",
58+ "prompt-value",
59+ "actual-prompt",
60+ ];
61+ const result = parseArgs();
62+ expect(result.prompts).toEqual(["prompt-value"]);
63+ expect(result.prompt).toBe("actual-prompt");
64+ });
65+
66+ it("should handle both --rule and --prompt flags", () => {
67+ process.argv = [
68+ "node",
69+ "script.js",
70+ "--rule",
71+ "my-rule",
72+ "--prompt",
73+ "my-prompt",
74+ ];
75+ const result = parseArgs();
76+ expect(result.rules).toEqual(["my-rule"]);
77+ expect(result.prompts).toEqual(["my-prompt"]);
78+ });
79+
80+ it("should process direct string content", async () => {
81+ const result = await processPromptOrRule("This is a direct prompt");
82+ expect(result).toBe("This is a direct prompt");
83+ });
84+});
modified extensions/cli/src/args.test.ts +27 −15
@@ -1,6 +1,6 @@
11 import { vi } from "vitest";
22
3-import { parseArgs, processRule } from "./args.js";
3+import { parseArgs, processPromptOrRule } from "./args.js";
44
55 describe("parseArgs", () => {
66 const originalArgv = process.argv;
@@ -217,7 +217,7 @@
217217 });
218218 });
219219
220-describe("processRule (loadRuleFromHub integration)", () => {
220+describe("processPromptOrRule (loadRuleFromHub integration)", () => {
221221 // Mock fetch for hub tests
222222 const originalFetch = global.fetch;
223223 const mockFetch = vi.fn() as any;
@@ -251,7 +251,7 @@
251251 arrayBuffer: () => Promise.resolve(zipBuffer),
252252 } as Response);
253253
254- const result = await processRule("continuedev/sentry-nextjs");
254+ const result = await processPromptOrRule("continuedev/sentry-nextjs");
255255
256256 expect(result).toBe(ruleContent);
257257 expect(mockFetch).toHaveBeenCalledWith(
@@ -269,7 +269,9 @@
269269 statusText: "Not Found",
270270 } as Response);
271271
272- await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
272+ await expect(
273+ processPromptOrRule("continuedev/nonexistent-rule"),
274+ ).rejects.toThrow(
273275 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found',
274276 );
275277 });
@@ -277,7 +279,9 @@
277279 it("should handle network errors when loading from hub", async () => {
278280 mockFetch.mockRejectedValue(new Error("Network error"));
279281
280- await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
282+ await expect(
283+ processPromptOrRule("continuedev/sentry-nextjs"),
284+ ).rejects.toThrow(
281285 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error',
282286 );
283287 });
@@ -285,7 +289,9 @@
285289 it("should handle invalid slug format", async () => {
286290 // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
287291 // Let's test with a slug that has wrong format but contains "/"
288- await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
292+ await expect(
293+ processPromptOrRule("invalid/slug/too/many/parts"),
294+ ).rejects.toThrow(
289295 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts',
290296 );
291297 });
@@ -300,7 +306,9 @@
300306 arrayBuffer: () => Promise.resolve(zipBuffer),
301307 } as Response);
302308
303- await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
309+ await expect(
310+ processPromptOrRule("continuedev/empty-rule"),
311+ ).rejects.toThrow(
304312 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file',
305313 );
306314 });
@@ -316,7 +324,9 @@
316324 arrayBuffer: () => Promise.resolve(zipBuffer),
317325 } as Response);
318326
319- await expect(processRule("continuedev/directory-only")).rejects.toThrow(
327+ await expect(
328+ processPromptOrRule("continuedev/directory-only"),
329+ ).rejects.toThrow(
320330 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file',
321331 );
322332 });
@@ -338,7 +348,7 @@
338348 arrayBuffer: () => Promise.resolve(zipBuffer),
339349 } as Response);
340350
341- const result = await processRule("continuedev/mixed-files");
351+ const result = await processPromptOrRule("continuedev/mixed-files");
342352
343353 expect(result).toBe(mdContent);
344354 });
@@ -359,7 +369,7 @@
359369 arrayBuffer: () => Promise.resolve(zipBuffer),
360370 } as Response);
361371
362- const result = await processRule("continuedev/multiple-rules");
372+ const result = await processPromptOrRule("continuedev/multiple-rules");
363373
364374 // Should use the first markdown file found (alphabetically)
365375 expect(result).toBe(rule1Content);
@@ -373,13 +383,15 @@
373383 arrayBuffer: () => Promise.resolve(invalidZipBuffer),
374384 } as Response);
375385
376- await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
386+ await expect(
387+ processPromptOrRule("continuedev/corrupted-zip"),
388+ ).rejects.toThrow(
377389 'Failed to load rule from hub "continuedev/corrupted-zip"',
378390 );
379391 });
380392 });
381393
382- describe("processRule logic", () => {
394+ describe("processPromptOrRule logic", () => {
383395 it("should identify hub slugs correctly", async () => {
384396 const JSZip = (await import("jszip")).default;
385397 const zip = new JSZip();
@@ -391,14 +403,14 @@
391403 arrayBuffer: () => Promise.resolve(zipBuffer),
392404 } as Response);
393405
394- const result = await processRule("owner/package");
406+ const result = await processPromptOrRule("owner/package");
395407 expect(result).toBe("# Hub Rule");
396408 expect(mockFetch).toHaveBeenCalled();
397409 });
398410
399411 it("should treat direct strings as content", async () => {
400412 const directContent = "This is direct rule content";
401- const result = await processRule(directContent);
413+ const result = await processPromptOrRule(directContent);
402414 expect(result).toBe(directContent);
403415 expect(mockFetch).not.toHaveBeenCalled();
404416 });
@@ -406,7 +418,7 @@
406418 it("should distinguish between hub slugs and file paths", async () => {
407419 // This would be treated as a file path, not a hub slug
408420 // since it starts with "."
409- await expect(processRule("./owner/package")).rejects.toThrow(
421+ await expect(processPromptOrRule("./owner/package")).rejects.toThrow(
410422 'Failed to read rule file "./owner/package": Rule file not found',
411423 );
412424 expect(mockFetch).not.toHaveBeenCalled();
modified extensions/cli/src/args.ts +44 −18
@@ -12,6 +12,7 @@
1212 resume?: boolean; // Resume from last session
1313 readonly?: boolean; // Start in plan mode (backward compatibility)
1414 rules?: string[]; // Array of rule specifications
15+ prompts?: string[]; // Array of prompt specifications
1516 format?: "json"; // Output format for headless mode
1617 }
1718
@@ -83,31 +84,23 @@
8384 }
8485
8586 /**
86- * Process a rule specification and return its content
87- * @param ruleSpec - Can be a file path, hub slug, or direct string content
88- * @returns The processed rule content
87+ * Process a specification (rule or prompt) and return its content
88+ * @param spec - Can be a file path, hub slug, or direct string content
89+ * @returns The processed content
8990 */
90-export async function processRule(ruleSpec: string): Promise<string> {
91+export async function processPromptOrRule(spec: string): Promise<string> {
9192 // If it looks like a hub slug (contains / but doesn't start with . or /)
92- if (
93- ruleSpec.includes("/") &&
94- !ruleSpec.startsWith(".") &&
95- !ruleSpec.startsWith("/")
96- ) {
97- return await loadRuleFromHub(ruleSpec);
93+ if (spec.includes("/") && !spec.startsWith(".") && !spec.startsWith("/")) {
94+ return await loadRuleFromHub(spec);
9895 }
9996
10097 // If it looks like a file path (contains . or / or ends with common file extensions)
101- if (
102- ruleSpec.includes(".") ||
103- ruleSpec.includes("/") ||
104- ruleSpec.includes("\\")
105- ) {
106- return loadRuleFromFile(ruleSpec);
98+ if (spec.includes(".") || spec.includes("/") || spec.includes("\\")) {
99+ return loadRuleFromFile(spec);
107100 }
108101
109102 // Otherwise, treat it as direct string content
110- return ruleSpec;
103+ return spec;
111104 }
112105
113106 /**
@@ -115,6 +108,7 @@
115108 * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility.
116109 * @returns Parsed command line arguments
117110 */
111+/* eslint-disable */
118112 export function parseArgs(): CommandLineArgs {
119113 const args = process.argv.slice(2);
120114
@@ -170,8 +164,40 @@
170164 }
171165 }
172166
167+ // Get prompts from --prompt flags (can be specified multiple times)
168+ const promptIndices: number[] = [];
169+ for (let i = 0; i < args.length; i++) {
170+ if (args[i] === "--prompt") {
171+ promptIndices.push(i);
172+ }
173+ }
174+
175+ if (promptIndices.length > 0) {
176+ result.prompts = [];
177+ for (const promptIndex of promptIndices) {
178+ if (promptIndex + 1 >= args.length) {
179+ throw new Error("--prompt flag requires a value");
180+ }
181+
182+ const promptValue = args[promptIndex + 1];
183+
184+ // Check if the next argument is actually another flag
185+ if (promptValue.startsWith("--")) {
186+ throw new Error("--prompt flag requires a value, found flag instead");
187+ }
188+
189+ result.prompts.push(promptValue);
190+ }
191+ }
192+
173193 // Find the last argument that's not a flag or a flag value
174- const flagsWithValues = ["--config", "--org", "--rule", "--format"];
194+ const flagsWithValues = [
195+ "--config",
196+ "--org",
197+ "--rule",
198+ "--prompt",
199+ "--format",
200+ ];
175201 const nonFlagArgs = args.filter((arg, index) => {
176202 // Skip flags (starting with --)
177203 if (arg.startsWith("--") || arg === "-p") return false;
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 +77 −56
@@ -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,13 +23,11 @@
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 {
2929 calculateContextUsagePercentage,
3030 countChatHistoryTokens,
31- getAutoCompactMessage,
3231 shouldAutoCompact,
3332 } from "../util/tokenizer.js";
3433
@@ -79,6 +78,7 @@
7978 headless?: boolean;
8079 resume?: boolean;
8180 rule?: string[]; // Array of rule specifications
81+ prompt?: string[]; // Array of prompt specifications
8282 format?: "json"; // Output format for headless mode
8383 silent?: boolean; // Strip <think></think> tags and excess whitespace
8484 org?: string; // Organization slug to use for this session
@@ -160,7 +160,7 @@
160160 }
161161 }
162162
163-// Helper function to handle auto-compaction
163+// Helper function to handle auto-compaction for headless mode
164164 async function handleAutoCompaction(
165165 chatHistory: ChatCompletionMessageParam[],
166166 model: ModelConfig,
@@ -168,60 +168,71 @@
168168 isHeadless: boolean,
169169 format?: "json",
170170 ): Promise<number | null> {
171- logger.info("Auto-compacting triggered due to context limit");
172-
173- if (!isHeadless) {
174- console.info(chalk.yellow(`\n${getAutoCompactMessage(model)}`));
175- } else if (format === "json") {
176- safeStdout(
177- JSON.stringify({
178- status: "info",
179- message: "Auto-compacting triggered",
180- contextUsage:
181- calculateContextUsagePercentage(
182- countChatHistoryTokens(chatHistory),
183- model,
184- ) + "%",
185- }) + "\n",
186- );
187- }
171+ const { handleAutoCompaction: coreAutoCompaction } = await import(
172+ "../streamChatResponse.autoCompaction.js"
173+ );
188174
189- try {
190- const result = await compactChatHistory(chatHistory, model, llmApi);
191- chatHistory.length = 0;
192- chatHistory.push(...result.compactedHistory);
193- saveSession(chatHistory);
175+ // Custom callbacks for headless mode console output
176+ const callbacks = {
177+ onSystemMessage: (message: string) => {
178+ if (
179+ message.includes("Auto-compacting") ||
180+ message.includes("Approaching")
181+ ) {
182+ if (!isHeadless) {
183+ console.info(chalk.yellow(`\n${message}`));
184+ } else if (format === "json") {
185+ safeStdout(
186+ JSON.stringify({
187+ status: "info",
188+ message: "Auto-compacting triggered",
189+ contextUsage:
190+ calculateContextUsagePercentage(
191+ countChatHistoryTokens(chatHistory),
192+ model,
193+ ) + "%",
194+ }) + "\n",
195+ );
196+ }
197+ } else if (message.includes("✓")) {
198+ if (!isHeadless) {
199+ console.info(chalk.green(message));
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+ } else if (message.includes("Warning:")) {
210+ if (!isHeadless) {
211+ console.error(chalk.red(message));
212+ console.info(chalk.yellow("Continuing without compaction..."));
213+ } else if (format === "json") {
214+ safeStdout(
215+ JSON.stringify({
216+ status: "warning",
217+ message: "Auto-compaction failed, continuing without compaction",
218+ }) + "\n",
219+ );
220+ }
221+ }
222+ },
223+ };
194224
195- if (!isHeadless) {
196- console.info(chalk.green("✓ Chat history auto-compacted successfully."));
197- } else if (format === "json") {
198- safeStdout(
199- JSON.stringify({
200- status: "success",
201- message: "Auto-compacted successfully",
202- historyLength: chatHistory.length,
203- }) + "\n",
204- );
205- }
225+ const result = await coreAutoCompaction(chatHistory, model, llmApi, {
226+ isHeadless,
227+ format,
228+ callbacks,
229+ });
206230
207- return result.compactionIndex;
208- } catch (error) {
209- const errorMsg = `Auto-compaction error: ${formatError(error)}`;
210- logger.error(errorMsg);
231+ // Update the original array reference for headless mode
232+ chatHistory.length = 0;
233+ chatHistory.push(...result.chatHistory);
211234
212- if (!isHeadless) {
213- console.error(chalk.red(`Warning: ${errorMsg}`));
214- console.info(chalk.yellow("Continuing without compaction..."));
215- } else if (format === "json") {
216- safeStdout(
217- JSON.stringify({
218- status: "warning",
219- message: "Auto-compaction failed, continuing without compaction",
220- }) + "\n",
221- );
222- }
223- return null;
224- }
235+ return result.compactionIndex;
225236 }
226237
227238 interface ProcessMessageOptions {
@@ -385,17 +396,26 @@
385396 compactionIndex = findCompactionIndex(chatHistory);
386397 }
387398
399+ // Handle additional prompts from --prompt flags
400+ const { processAndCombinePrompts } = await import(
401+ "../util/promptProcessor.js"
402+ );
403+ const initialUserInput = await processAndCombinePrompts(
404+ options.prompt,
405+ prompt,
406+ );
407+
388408 let isFirstMessage = true;
389409 while (true) {
390410 // When in headless mode, don't ask for user input
391- if (!isFirstMessage && prompt && options.headless) {
411+ if (!isFirstMessage && initialUserInput && options.headless) {
392412 break;
393413 }
394414
395415 // Get user input
396416 const userInput =
397- isFirstMessage && prompt
398- ? prompt
417+ isFirstMessage && initialUserInput
418+ ? initialUserInput
399419 : readlineSync.question(`\n${chalk.bold.green("You:")} `);
400420
401421 isFirstMessage = false;
@@ -462,6 +482,7 @@
462482 configPath: options.config,
463483 organizationSlug: options.org,
464484 additionalRules: options.rule,
485+ additionalPrompts: options.prompt,
465486 toolPermissionOverrides: permissionOverrides,
466487 skipOnboarding: true,
467488 };
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/e2e/basic-commands.test.ts +1 −0
@@ -40,6 +40,7 @@
4040 expect(result.stdout).toContain("--readonly");
4141 expect(result.stdout).toContain("--auto");
4242 expect(result.stdout).toContain("--rule <rule>");
43+ expect(result.stdout).toContain("--prompt <prompt>");
4344 });
4445
4546 it("should show available commands", async () => {
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+}
modified extensions/cli/src/onboarding.ts +2 −2
@@ -7,7 +7,7 @@
77 import chalk from "chalk";
88 import * as readlineSync from "readline-sync";
99
10-import { processRule } from "./args.js";
10+import { processPromptOrRule } from "./args.js";
1111 import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
1212 import { initialize } from "./config.js";
1313 import { env } from "./env.js";
@@ -239,7 +239,7 @@
239239 const processedRules: string[] = [];
240240 for (const ruleSpec of rules) {
241241 try {
242- const processedRule = await processRule(ruleSpec);
242+ const processedRule = await processPromptOrRule(ruleSpec);
243243 processedRules.push(processedRule);
244244 } catch (error: any) {
245245 console.warn(
modified extensions/cli/src/services/ConfigService.test.ts +1 −1
@@ -73,7 +73,7 @@
7373 config: mockConfig as any,
7474 source: { type: "cli-flag", path: "/config.yaml" } as any,
7575 });
76- vi.mocked(args.processRule).mockImplementation(
76+ vi.mocked(args.processPromptOrRule).mockImplementation(
7777 async (rule) => `Processed: ${rule}`,
7878 );
7979
modified extensions/cli/src/services/ConfigService.ts +2 −2
@@ -1,7 +1,7 @@
11 import { AssistantUnrolled } from "@continuedev/config-yaml";
22 import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
33
4-import { processRule } from "../args.js";
4+import { processPromptOrRule } from "../args.js";
55 import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
66 import { logger } from "../util/logger.js";
77
@@ -155,7 +155,7 @@
155155
156156 for (const ruleSpec of rules) {
157157 try {
158- const processedRule = await processRule(ruleSpec);
158+ const processedRule = await processPromptOrRule(ruleSpec);
159159 processedRules.push(processedRule);
160160 } catch (error: any) {
161161 logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`);
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/shared-options.ts +11 −0
@@ -24,6 +24,16 @@
2424 },
2525 [] as string[],
2626 )
27+ .option(
28+ "--prompt <prompt>",
29+ "Add to the initial user message (can be a file path, hub slug, or string content). Can be specified multiple times.",
30+ (value: string, previous: string[] | undefined) => {
31+ const array = Array.isArray(previous) ? previous : [];
32+ array.push(value);
33+ return array;
34+ },
35+ [] as string[],
36+ )
2737 .option(
2838 "--allow <tool>",
2939 "Allow specified tool (overrides default policies). Can be specified multiple times.",
@@ -70,6 +80,7 @@
7080 "tools",
7181 "verbose",
7282 "rule",
83+ "prompt",
7384 "allow",
7485 "ask",
7586 "exclude",
modified extensions/cli/src/slashCommands.test.ts +205 −121
@@ -1,147 +1,231 @@
1-// Import after mocking
2-import { AssistantUnrolled } from "@continuedev/config-yaml";
3-import { afterEach, beforeEach, describe, expect, test, vi } 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- });
113154
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- });
121-
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);
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);
134180 });
135181
136- test("non-slash input should return null", async () => {
137- const result = await handleSlashCommands("regular input", mockAssistant);
138- expect(result).toBeNull();
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");
139201 });
140202
141- test("unknown slash command should return null", async () => {
142- const result = await handleSlashCommands("/unknown", 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+ );
143212
144- expect(result).toBeNull();
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");
145229 });
146230 });
147231 });
modified extensions/cli/src/slashCommands.ts +59 −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" });
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/systemMessage.test.ts +3 −3
@@ -11,11 +11,11 @@
1111 },
1212 }));
1313
14-// Mock processRule to avoid file system operations in tests
14+// Mock processPromptOrRule to avoid file system operations in tests
1515 vi.mock("./args.js", () => ({
16- processRule: vi
16+ processPromptOrRule: vi
1717 .fn()
18- .mockImplementation((rule: string) => Promise.resolve(rule)),
18+ .mockImplementation((spec: string) => Promise.resolve(spec)),
1919 }));
2020
2121 describe("constructSystemMessage", () => {
modified extensions/cli/src/systemMessage.ts +2 −2
@@ -5,7 +5,7 @@
55 import pkg from "ignore-walk";
66 import { Minimatch } from "minimatch";
77
8-import { processRule } from "./args.js";
8+import { processPromptOrRule } from "./args.js";
99 import { PermissionMode } from "./permissions/types.js";
1010 import { modeService } from "./services/ModeService.js";
1111 import { serviceContainer } from "./services/ServiceContainer.js";
@@ -153,7 +153,7 @@
153153 if (additionalRules && additionalRules.length > 0) {
154154 for (const ruleSpec of additionalRules) {
155155 try {
156- const processedRule = await processRule(ruleSpec);
156+ const processedRule = await processPromptOrRule(ruleSpec);
157157 processedRules.push(processedRule);
158158 } catch (error: any) {
159159 console.warn(
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/readFile.ts +7 −0
@@ -39,6 +39,13 @@
3939 const content = fs.readFileSync(args.filepath, "utf-8");
4040 // Mark this file as read for the edit tool
4141 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+
4249 return `Content of ${args.filepath}:\n${content}`;
4350 } catch (error) {
4451 return `Error reading file: ${
modified extensions/cli/src/ui/AppRoot.tsx +1 −0
@@ -9,6 +9,7 @@
99 initialPrompt?: string;
1010 resume?: boolean;
1111 additionalRules?: string[];
12+ additionalPrompts?: string[];
1213 }
1314
1415 /**
modified extensions/cli/src/ui/TUIChat.tsx +3 −0
@@ -36,6 +36,7 @@
3636 initialPrompt?: string;
3737 resume?: boolean;
3838 additionalRules?: string[];
39+ additionalPrompts?: string[];
3940 }
4041
4142 const TUIChat: React.FC<TUIChatProps> = ({
@@ -44,6 +45,7 @@
4445 initialPrompt,
4546 resume,
4647 additionalRules,
48+ additionalPrompts,
4749 }) => {
4850 // Check if we're in remote mode
4951 const isRemoteMode = useMemo(() => {
@@ -126,6 +128,7 @@
126128 initialPrompt,
127129 resume,
128130 additionalRules,
131+ additionalPrompts,
129132 onShowConfigSelector: () => navigateTo("config"),
130133 onShowModelSelector: () => navigateTo("model"),
131134 onShowMCPSelector: () => navigateTo("mcp"),
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 −69
@@ -7,10 +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 {
11- getAutoCompactMessage,
12- shouldAutoCompact,
13-} from "../../util/tokenizer.js";
1410 import { DisplayMessage } from "../types.js";
1511
1612 import { SlashCommandResult } from "./useChat.types.js";
@@ -281,13 +277,13 @@
281277 }
282278
283279 /**
284- * Handle auto-compaction when approaching context limit
280+ * Handle auto-compaction when approaching context limit - TUI wrapper
285281 */
286282 export async function handleAutoCompaction({
287283 chatHistory,
288284 model,
289285 llmApi,
290- compactionIndex,
286+ compactionIndex: _compactionIndex,
291287 setMessages,
292288 setChatHistory,
293289 setCompactionIndex,
@@ -295,69 +291,21 @@
295291 currentChatHistory: ChatCompletionMessageParam[];
296292 currentCompactionIndex: number | null;
297293 }> {
298- if (!model || !shouldAutoCompact(chatHistory, model)) {
299- return {
300- currentChatHistory: chatHistory,
301- currentCompactionIndex: compactionIndex,
302- };
303- }
304-
305- logger.info("Auto-compacting triggered in TUI mode");
306-
307- setMessages((prev) => [
308- ...prev,
309- {
310- role: "system",
311- content: getAutoCompactMessage(model),
312- 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,
313304 },
314- ]);
315-
316- try {
317- if (!llmApi) {
318- throw new Error("LLM API is not available for auto-compaction");
319- }
320-
321- // Compact the history WITHOUT the current user message
322- const result = await compactChatHistory(chatHistory, model, llmApi);
323-
324- // Update state
325- setChatHistory(result.compactedHistory);
326- setCompactionIndex(result.compactionIndex);
327-
328- // Save the compacted session
329- saveSession(result.compactedHistory);
330-
331- setMessages((prev) => [
332- ...prev,
333- {
334- role: "system",
335- content: "✓ Chat history auto-compacted successfully.",
336- messageType: "system" as const,
337- },
338- ]);
339-
340- return {
341- currentChatHistory: result.compactedHistory,
342- currentCompactionIndex: result.compactionIndex,
343- };
344- } catch (error: any) {
345- const errorMessage = `Auto-compaction error: ${formatError(error)}`;
346- logger.error(errorMessage);
347-
348- setMessages((prev) => [
349- ...prev,
350- {
351- role: "system",
352- content: `Warning: ${errorMessage}. Continuing without compaction...`,
353- messageType: "system" as const,
354- },
355- ]);
305+ });
356306
357- // Continue without compaction on error
358- return {
359- currentChatHistory: chatHistory,
360- currentCompactionIndex: compactionIndex,
361- };
362- }
307+ return {
308+ currentChatHistory: result.chatHistory,
309+ currentCompactionIndex: result.compactionIndex,
310+ };
363311 }
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/ui/hooks/useChat.ts +21 −3
@@ -42,6 +42,7 @@
4242 initialPrompt,
4343 resume,
4444 additionalRules,
45+ additionalPrompts,
4546 onShowConfigSelector,
4647 onShowModelSelector,
4748 onShowMCPSelector,
@@ -163,10 +164,27 @@
163164 useEffect(() => {
164165 // Only handle initial prompt after chat history is initialized
165166 // This prevents race conditions where the prompt runs before system message is loaded
166- if (initialPrompt && isChatHistoryInitialized) {
167- handleUserMessage(initialPrompt);
167+ if (
168+ (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) &&
169+ isChatHistoryInitialized
170+ ) {
171+ const processPrompts = async () => {
172+ const { processAndCombinePrompts } = await import(
173+ "../../util/promptProcessor.js"
174+ );
175+ const finalMessage = await processAndCombinePrompts(
176+ additionalPrompts,
177+ initialPrompt,
178+ );
179+
180+ if (finalMessage) {
181+ await handleUserMessage(finalMessage);
182+ }
183+ };
184+
185+ processPrompts().catch(console.error);
168186 }
169- }, [initialPrompt, isChatHistoryInitialized]);
187+ }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]);
170188
171189 const executeStreamingResponse = async (
172190 newHistory: ChatCompletionMessageParam[],
modified extensions/cli/src/ui/hooks/useChat.types.ts +1 −0
@@ -11,6 +11,7 @@
1111 initialPrompt?: string;
1212 resume?: boolean;
1313 additionalRules?: string[];
14+ additionalPrompts?: string[];
1415 onShowConfigSelector: () => void;
1516 onShowMCPSelector: () => void;
1617 onShowModelSelector?: () => void;
modified extensions/cli/src/ui/index.ts +3 −0
@@ -15,6 +15,7 @@
1515 configPath?: string;
1616 organizationSlug?: string;
1717 additionalRules?: string[];
18+ additionalPrompts?: string[];
1819 toolPermissionOverrides?: {
1920 allow?: string[];
2021 ask?: string[];
@@ -33,6 +34,7 @@
3334 configPath,
3435 organizationSlug,
3536 additionalRules,
37+ additionalPrompts,
3638 toolPermissionOverrides,
3739 skipOnboarding,
3840 customStdin,
@@ -64,6 +66,7 @@
6466 initialPrompt,
6567 resume,
6668 additionalRules,
69+ additionalPrompts,
6770 }),
6871 }),
6972 renderOptions,
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/promptProcessor.test.ts +127 −0
@@ -0,0 +1,127 @@
1+import { describe, it, expect, vi, beforeEach } from "vitest";
2+
3+import * as args from "../args.js";
4+
5+import { processAndCombinePrompts } from "./promptProcessor.js";
6+
7+// Mock the args module
8+vi.mock("../args.js", () => ({
9+ processPromptOrRule: vi.fn(),
10+}));
11+
12+// Mock the logger
13+vi.mock("./logger.js", () => ({
14+ logger: {
15+ warn: vi.fn(),
16+ },
17+}));
18+
19+describe("promptProcessor", () => {
20+ beforeEach(() => {
21+ vi.clearAllMocks();
22+ });
23+
24+ describe("processAndCombinePrompts", () => {
25+ it("should return initial prompt when no additional prompts", async () => {
26+ const result = await processAndCombinePrompts(undefined, "initial");
27+ expect(result).toBe("initial");
28+ });
29+
30+ it("should return initial prompt when empty additional prompts array", async () => {
31+ const result = await processAndCombinePrompts([], "initial");
32+ expect(result).toBe("initial");
33+ });
34+
35+ it("should return undefined when no prompts at all", async () => {
36+ const result = await processAndCombinePrompts();
37+ expect(result).toBeUndefined();
38+ });
39+
40+ it("should process single additional prompt without initial", async () => {
41+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
42+ mockProcessPromptOrRule.mockResolvedValue("processed prompt");
43+
44+ const result = await processAndCombinePrompts(["prompt1"]);
45+
46+ expect(mockProcessPromptOrRule).toHaveBeenCalledWith("prompt1");
47+ expect(result).toBe("processed prompt");
48+ });
49+
50+ it("should combine multiple processed prompts", async () => {
51+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
52+ mockProcessPromptOrRule
53+ .mockResolvedValueOnce("first prompt")
54+ .mockResolvedValueOnce("second prompt");
55+
56+ const result = await processAndCombinePrompts(["prompt1", "prompt2"]);
57+
58+ expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(2);
59+ expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(1, "prompt1");
60+ expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(2, "prompt2");
61+ expect(result).toBe("first prompt\n\nsecond prompt");
62+ });
63+
64+ it("should combine processed prompts with initial prompt", async () => {
65+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
66+ mockProcessPromptOrRule
67+ .mockResolvedValueOnce("processed1")
68+ .mockResolvedValueOnce("processed2");
69+
70+ const result = await processAndCombinePrompts(
71+ ["prompt1", "prompt2"],
72+ "initial",
73+ );
74+
75+ expect(result).toBe("processed1\n\nprocessed2\n\ninitial");
76+ });
77+
78+ it("should handle processing errors and continue with successful ones", async () => {
79+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
80+ mockProcessPromptOrRule
81+ .mockResolvedValueOnce("success1")
82+ .mockRejectedValueOnce(new Error("processing failed"))
83+ .mockResolvedValueOnce("success2");
84+
85+ const result = await processAndCombinePrompts(["good1", "bad", "good2"]);
86+
87+ expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(3);
88+ expect(result).toBe("success1\n\nsuccess2");
89+ });
90+
91+ it("should return initial prompt when all processing fails", async () => {
92+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
93+ mockProcessPromptOrRule
94+ .mockRejectedValueOnce(new Error("fail1"))
95+ .mockRejectedValueOnce(new Error("fail2"));
96+
97+ const result = await processAndCombinePrompts(
98+ ["bad1", "bad2"],
99+ "initial",
100+ );
101+
102+ expect(result).toBe("initial");
103+ });
104+
105+ it("should return undefined when all processing fails and no initial", async () => {
106+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
107+ mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed"));
108+
109+ const result = await processAndCombinePrompts(["bad"]);
110+
111+ expect(result).toBeUndefined();
112+ });
113+
114+ it("should warn when processing fails", async () => {
115+ const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule);
116+ mockProcessPromptOrRule.mockRejectedValue(new Error("test error"));
117+
118+ const { logger } = await import("./logger.js");
119+
120+ await processAndCombinePrompts(["bad-prompt"]);
121+
122+ expect(logger.warn).toHaveBeenCalledWith(
123+ 'Failed to process prompt "bad-prompt": test error',
124+ );
125+ });
126+ });
127+});
added extensions/cli/src/util/promptProcessor.ts +38 −0
@@ -0,0 +1,38 @@
1+import { processPromptOrRule } from "../args.js";
2+
3+import { logger } from "./logger.js";
4+
5+/**
6+ * Process additional prompts from --prompt flags and combine with initial prompt
7+ * @param additionalPrompts - Array of prompt specifications to process
8+ * @param initialPrompt - Optional initial prompt to combine with
9+ * @returns Combined prompt string or undefined if no prompts
10+ */
11+export async function processAndCombinePrompts(
12+ additionalPrompts?: string[],
13+ initialPrompt?: string,
14+): Promise<string | undefined> {
15+ if (!additionalPrompts || additionalPrompts.length === 0) {
16+ return initialPrompt;
17+ }
18+
19+ const processedPrompts: string[] = [];
20+
21+ for (const promptSpec of additionalPrompts) {
22+ try {
23+ const processed = await processPromptOrRule(promptSpec);
24+ processedPrompts.push(processed);
25+ } catch (error: any) {
26+ logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`);
27+ }
28+ }
29+
30+ if (processedPrompts.length === 0) {
31+ return initialPrompt;
32+ }
33+
34+ const combinedPrompts = processedPrompts.join("\n\n");
35+ return initialPrompt
36+ ? `${combinedPrompts}\n\n${initialPrompt}`
37+ : combinedPrompts;
38+}
modified extensions/cli/validate-aliases.mjs +8 −4
@@ -42,10 +42,14 @@
4242 }
4343
4444 // Look for package names in non-commented lines
45- // Match both @continuedev/* packages and simple package names like "core"
46- const packageMatch = line.match(/"(@continuedev\/[^"]+|[^"@\/]+)":/);
47- if (packageMatch) {
48- aliases.add(packageMatch[1]);
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]);
4953 }
5054 }
5155
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/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.83",
5+ "version": "1.3.1",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
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": {