Elffuss BraidHub

kikocis/continue public

main · 5.4 KiBRawPermalink
1import { Position } from "../..";
2import { ContextRetrievalService } from "../../autocomplete/context/ContextRetrievalService";
3import { getAllSnippetsWithoutRace } from "../../autocomplete/snippets/getAllSnippets";
4import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types";
5import { renderPrompt } from "../../autocomplete/templating";
6import { GetLspDefinitionsFunction } from "../../autocomplete/types";
7import { HelperVars } from "../../autocomplete/util/HelperVars";
8import {
9 AutocompleteInput,
10 RecentlyEditedRange,
11} from "../../autocomplete/util/types";
12import { ConfigHandler } from "../../config/ConfigHandler";
13import { IDE, ILLM } from "../../index";
14import { isSecurityConcern } from "../../indexing/ignore";
15import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
16
17/**
18 * Gets the formatted autocomplete context string that would be used for autocomplete at the given position.
19 * This function mimics the context generation pipeline from the autocomplete system without triggering
20 * an actual completion.
21 *
22 * @param filepath - The file path where context is being requested
23 * @param pos - The position in the file where context is being requested
24 * @param ide - The IDE interface for file system operations
25 * @param configHandler - The config handler to load user configuration
26 * @param getDefinitionsFromLsp - Function to get LSP definitions (can be a no-op function if not needed)
27 * @param autocompleteModel - Optional autocomplete model to use (if not provided, uses configured autocomplete model)
28 * @param recentlyEditedRanges - Recently edited ranges (defaults to empty array)
29 * @param recentlyVisitedRanges - Recently visited ranges (if not provided, will fetch current live data like real autocomplete)
30 * @param maxPromptTokens - Optional override for maximum number of tokens (if not provided, uses config)
31 * @param manuallyPassFileContents - Optional file contents to use instead of reading from disk (should match current editor state)
32 * @returns Promise that resolves to the formatted context string
33 */
34export const getAutocompleteContext = async (
35 filepath: string,
36 pos: Position,
37 ide: IDE,
38 configHandler: ConfigHandler,
39 getDefinitionsFromLsp: GetLspDefinitionsFunction = async () => [],
40 recentlyEditedRanges: RecentlyEditedRange[],
41 recentlyVisitedRanges: AutocompleteCodeSnippet[],
42 maxPromptTokens: number,
43 manuallyPassFileContents: string,
44 autocompleteModel?: ILLM | string,
45 // eslint-disable-next-line max-params
46): Promise<string> => {
47 if (!recentlyEditedRanges) recentlyEditedRanges = [];
48 if (!recentlyVisitedRanges) recentlyVisitedRanges = [];
49
50 const input: AutocompleteInput = {
51 isUntitledFile: false,
52 completionId: `context-fetch-${Date.now()}`,
53 filepath,
54 pos,
55 recentlyVisitedRanges,
56 recentlyEditedRanges,
57 manuallyPassFileContents,
58 };
59
60 const { config } = await configHandler.loadConfig();
61 if (!config) {
62 throw new Error("No config available");
63 }
64
65 if (isSecurityConcern(input.filepath)) {
66 throw new Error("File is a security concern, autocomplete disabled");
67 }
68
69 // Use provided autocomplete model or fall back to configured autocomplete model
70 let finalModel: ILLM;
71 let modelNameForTemplating: string;
72
73 if (autocompleteModel) {
74 if (typeof autocompleteModel === "string") {
75 // Try to find the model in config first
76 const foundModel = config.modelsByRole.autocomplete.find(
77 (m) => m.title === autocompleteModel,
78 );
79 if (foundModel) {
80 finalModel = foundModel;
81 modelNameForTemplating = foundModel.model;
82 } else {
83 // Model not found in config, but we can still use it for template selection
84 const configuredModel = config.selectedModelByRole.autocomplete;
85 if (!configuredModel) {
86 throw new Error(
87 "No autocomplete model configured and provided model not found in config",
88 );
89 }
90 finalModel = configuredModel;
91 modelNameForTemplating = autocompleteModel; // Use the provided string for template selection
92 }
93 } else {
94 finalModel = autocompleteModel;
95 modelNameForTemplating = autocompleteModel.model;
96 }
97 } else {
98 const configuredModel = config.selectedModelByRole.autocomplete;
99 if (!configuredModel) {
100 throw new Error("No autocomplete model configured and no model provided");
101 }
102 finalModel = configuredModel;
103 modelNameForTemplating = configuredModel.model;
104 }
105
106 const options = {
107 ...DEFAULT_AUTOCOMPLETE_OPTS,
108 ...config.tabAutocompleteOptions,
109 ...finalModel.autocompleteOptions,
110 ...(maxPromptTokens && { maxPromptTokens }),
111 };
112
113 if (finalModel.promptTemplates?.autocomplete) {
114 options.template = finalModel.promptTemplates.autocomplete as string;
115 }
116
117 const helper = await HelperVars.create(
118 input,
119 options,
120 modelNameForTemplating,
121 ide,
122 );
123
124 const contextRetrievalService = new ContextRetrievalService(ide);
125
126 await contextRetrievalService.initializeForFile(filepath);
127
128 const [snippetPayload, workspaceDirs] = await Promise.all([
129 getAllSnippetsWithoutRace({
130 helper,
131 ide: ide,
132 getDefinitionsFromLsp: getDefinitionsFromLsp,
133 contextRetrievalService: contextRetrievalService,
134 }),
135 ide.getWorkspaceDirs(),
136 ]);
137
138 const { prompt, prefix, suffix, completionOptions } = renderPrompt({
139 snippetPayload,
140 workspaceDirs,
141 helper,
142 });
143
144 return prefix;
145};