Elffuss BraidHub

kikocis/continue public

bdbad06b302d · 23.4 KiBRawPermalink
1import * as child_process from "node:child_process";
2import { exec } from "node:child_process";
3
4import { Range } from "core";
5import { EXTENSION_NAME } from "core/control-plane/env";
6import { GetGhTokenArgs } from "core/protocol/ide";
7import { editConfigFile, getConfigJsonPath } from "core/util/paths";
8import * as URI from "uri-js";
9import * as vscode from "vscode";
10
11import { executeGotoProvider } from "./autocomplete/lsp";
12import { Repository } from "./otherExtensions/git";
13import { SecretStorage } from "./stubs/SecretStorage";
14import { VsCodeIdeUtils } from "./util/ideUtils";
15import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
16import { VsCodeWebviewProtocol } from "./webviewProtocol";
17
18import type {
19 ContinueRcJson,
20 FileStatsMap,
21 FileType,
22 IDE,
23 IdeInfo,
24 IdeSettings,
25 IndexTag,
26 Location,
27 Problem,
28 RangeInFile,
29 TerminalOptions,
30 Thread,
31} from "core";
32
33class VsCodeIde implements IDE {
34 ideUtils: VsCodeIdeUtils;
35 secretStorage: SecretStorage;
36 private lastFileSaveTimestamp: number = Date.now();
37
38 constructor(
39 private readonly vscodeWebviewProtocolPromise: Promise<VsCodeWebviewProtocol>,
40 private readonly context: vscode.ExtensionContext,
41 ) {
42 this.ideUtils = new VsCodeIdeUtils();
43 this.secretStorage = new SecretStorage(context);
44 }
45
46 public updateLastFileSaveTimestamp(): void {
47 this.lastFileSaveTimestamp = Date.now();
48 }
49
50 public getLastFileSaveTimestamp(): number {
51 return this.lastFileSaveTimestamp;
52 }
53
54 async readSecrets(keys: string[]): Promise<Record<string, string>> {
55 const secretValuePromises = keys.map((key) => this.secretStorage.get(key));
56 const secretValues = await Promise.all(secretValuePromises);
57
58 return keys.reduce(
59 (acc, key, index) => {
60 if (secretValues[index] === undefined) {
61 return acc;
62 }
63
64 acc[key] = secretValues[index];
65 return acc;
66 },
67 {} as Record<string, string>,
68 );
69 }
70
71 async writeSecrets(secrets: { [key: string]: string }): Promise<void> {
72 for (const [key, value] of Object.entries(secrets)) {
73 await this.secretStorage.store(key, value);
74 }
75 }
76
77 async fileExists(uri: string): Promise<boolean> {
78 try {
79 const stat = await this.ideUtils.stat(vscode.Uri.parse(uri));
80 return stat !== null;
81 } catch (error) {
82 if (error instanceof vscode.FileSystemError) {
83 return false;
84 }
85 throw error;
86 }
87 }
88
89 async gotoDefinition(location: Location): Promise<RangeInFile[]> {
90 const result = await executeGotoProvider({
91 uri: vscode.Uri.parse(location.filepath),
92 line: location.position.line,
93 character: location.position.character,
94 name: "vscode.executeDefinitionProvider",
95 });
96
97 return result;
98 }
99
100 onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
101 vscode.window.onDidChangeActiveTextEditor((editor) => {
102 if (editor) {
103 callback(editor.document.uri.toString());
104 }
105 });
106 }
107
108 private authToken: string | undefined;
109 private askedForAuth = false;
110
111 async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
112 // Saved auth token
113 if (this.authToken) {
114 return this.authToken;
115 }
116
117 // Try to ask silently
118 const session = await vscode.authentication.getSession("github", [], {
119 silent: true,
120 });
121
122 if (session) {
123 this.authToken = session.accessToken;
124 return this.authToken;
125 }
126
127 try {
128 if (args.force) {
129 this.askedForAuth = true;
130 this.authToken = await vscode.authentication
131 .getSession("github", [], { createIfNone: true })
132 .then((session) => session.accessToken);
133 return this.authToken;
134 }
135
136 // If we haven't asked yet, give explanation of what is happening and why
137 // But don't wait to return this immediately
138 // We will use a callback to refresh the config
139 if (!this.askedForAuth) {
140 vscode.window
141 .showInformationMessage(
142 "Continue will request read access to your GitHub email so that we can prevent abuse of the free trial. If you prefer not to sign in, you can use Continue with your own API keys or local model.",
143 "Sign in",
144 "Use API key / local model",
145 "Learn more",
146 )
147 .then(async (selection) => {
148 if (selection === "Use API key / local model") {
149 await vscode.commands.executeCommand(
150 "continue.continueGUIView.focus",
151 );
152 (await this.vscodeWebviewProtocolPromise).request(
153 "openOnboardingCard",
154 undefined,
155 );
156
157 // Remove free trial models
158 editConfigFile(
159 (config) => {
160 let tabAutocompleteModel = undefined;
161 if (Array.isArray(config.tabAutocompleteModel)) {
162 tabAutocompleteModel = config.tabAutocompleteModel.filter(
163 (model) => model.provider !== "free-trial",
164 );
165 } else if (
166 config.tabAutocompleteModel?.provider === "free-trial"
167 ) {
168 tabAutocompleteModel = undefined;
169 }
170
171 return {
172 ...config,
173 models: config.models.filter(
174 (model) => model.provider !== "free-trial",
175 ),
176 tabAutocompleteModel,
177 };
178 },
179 (config) => {
180 return {
181 ...config,
182 models: config.models?.filter(
183 (model) =>
184 !(
185 "provider" in model && model.provider === "free-trial"
186 ),
187 ),
188 };
189 },
190 );
191 } else if (selection === "Learn more") {
192 vscode.env.openExternal(
193 vscode.Uri.parse(
194 "https://docs.continue.dev/reference/Model%20Providers/freetrial",
195 ),
196 );
197 } else if (selection === "Sign in") {
198 const session = await vscode.authentication.getSession(
199 "github",
200 [],
201 {
202 createIfNone: true,
203 },
204 );
205 if (session) {
206 this.authToken = session.accessToken;
207 }
208 }
209 });
210 this.askedForAuth = true;
211 return undefined;
212 }
213
214 const session = await vscode.authentication.getSession("github", [], {
215 silent: this.askedForAuth,
216 createIfNone: !this.askedForAuth,
217 });
218 if (session) {
219 this.authToken = session.accessToken;
220 return session.accessToken;
221 } else if (!this.askedForAuth) {
222 // User cancelled the login prompt
223 // Explain that they can avoid the prompt by removing free trial models from config.json
224 vscode.window
225 .showInformationMessage(
226 "We'll only ask you to log in if using the free trial. To avoid this prompt, make sure to remove free trial models from your config.json",
227 "Remove for me",
228 "Open Assistant configuration",
229 )
230 .then((selection) => {
231 if (selection === "Remove for me") {
232 editConfigFile(
233 (configJson) => {
234 configJson.models = configJson.models.filter(
235 (model) => model.provider !== "free-trial",
236 );
237 configJson.tabAutocompleteModel = undefined;
238 return configJson;
239 },
240 (config) => {
241 config.models = config.models?.filter(
242 (model) =>
243 !("provider" in model && model.provider === "free-trial"),
244 );
245 return config;
246 },
247 );
248 } else if (selection === "Open Assistant configuration") {
249 this.openFile(getConfigJsonPath());
250 }
251 });
252 }
253 } catch (error) {
254 console.error("Failed to get GitHub authentication session:", error);
255 }
256 return undefined;
257 }
258
259 showToast: IDE["showToast"] = async (...params) => {
260 const [type, message, ...otherParams] = params;
261 const { showErrorMessage, showWarningMessage, showInformationMessage } =
262 vscode.window;
263
264 switch (type) {
265 case "error":
266 return showErrorMessage(message, "Show logs").then((selection) => {
267 if (selection === "Show logs") {
268 vscode.commands.executeCommand("workbench.action.toggleDevTools");
269 }
270 });
271 case "info":
272 return showInformationMessage(message, ...otherParams);
273 case "warning":
274 return showWarningMessage(message, ...otherParams);
275 }
276 };
277
278 async getRepoName(dir: string): Promise<string | undefined> {
279 const repo = await this.getRepo(dir);
280 const remotes = repo?.state.remotes;
281 if (!remotes) {
282 return undefined;
283 }
284 const remote =
285 remotes?.find((r: any) => r.name === "origin") ?? remotes?.[0];
286 if (!remote) {
287 return undefined;
288 }
289 const ownerAndRepo = remote.fetchUrl
290 ?.replace(".git", "")
291 .split("/")
292 .slice(-2);
293 return ownerAndRepo?.join("/");
294 }
295
296 async getTags(artifactId: string): Promise<IndexTag[]> {
297 const workspaceDirs = await this.getWorkspaceDirs();
298
299 const branches = await Promise.all(
300 workspaceDirs.map((dir) => this.getBranch(dir)),
301 );
302
303 const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
304 directory,
305 branch: branches[i],
306 artifactId,
307 }));
308
309 return tags;
310 }
311
312 getIdeInfo(): Promise<IdeInfo> {
313 return Promise.resolve({
314 ideType: "vscode",
315 name: vscode.env.appName,
316 version: vscode.version,
317 remoteName: vscode.env.remoteName || "local",
318 extensionVersion:
319 vscode.extensions.getExtension("continue.continue")?.packageJSON
320 .version,
321 });
322 }
323
324 readRangeInFile(fileUri: string, range: Range): Promise<string> {
325 return this.ideUtils.readRangeInFile(
326 vscode.Uri.parse(fileUri),
327 new vscode.Range(
328 new vscode.Position(range.start.line, range.start.character),
329 new vscode.Position(range.end.line, range.end.character),
330 ),
331 );
332 }
333
334 async getFileStats(files: string[]): Promise<FileStatsMap> {
335 const pathToLastModified: FileStatsMap = {};
336 await Promise.all(
337 files.map(async (file) => {
338 const stat = await this.ideUtils.stat(vscode.Uri.parse(file), false /* No need to catch ENOPRO exceptions */);
339 pathToLastModified[file] = {
340 lastModified: stat!.mtime,
341 size: stat!.size,
342 };
343 }),
344 );
345
346 return pathToLastModified;
347 }
348
349 async getRepo(dir: string): Promise<Repository | undefined> {
350 return this.ideUtils.getRepo(vscode.Uri.parse(dir));
351 }
352
353 async isTelemetryEnabled(): Promise<boolean> {
354 const globalEnabled = vscode.env.isTelemetryEnabled;
355 const continueEnabled: boolean =
356 (await vscode.workspace
357 .getConfiguration(EXTENSION_NAME)
358 .get("telemetryEnabled")) ?? true;
359 return globalEnabled && continueEnabled;
360 }
361
362 getUniqueId(): Promise<string> {
363 return Promise.resolve(vscode.env.machineId);
364 }
365
366 async getDiff(includeUnstaged: boolean): Promise<string[]> {
367 return await this.ideUtils.getDiff(includeUnstaged);
368 }
369
370 async getClipboardContent() {
371 return this.context.workspaceState.get("continue.copyBuffer", {
372 text: "",
373 copiedAt: new Date("1900-01-01").toISOString(),
374 });
375 }
376
377 async getTerminalContents(): Promise<string> {
378 return await this.ideUtils.getTerminalContents(1);
379 }
380
381 async getDebugLocals(threadIndex: number): Promise<string> {
382 return await this.ideUtils.getDebugLocals(threadIndex);
383 }
384
385 async getTopLevelCallStackSources(
386 threadIndex: number,
387 stackDepth: number,
388 ): Promise<string[]> {
389 return await this.ideUtils.getTopLevelCallStackSources(
390 threadIndex,
391 stackDepth,
392 );
393 }
394 async getAvailableThreads(): Promise<Thread[]> {
395 return await this.ideUtils.getAvailableThreads();
396 }
397
398 async getWorkspaceConfigs() {
399 const workspaceDirs =
400 vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
401 const configs: ContinueRcJson[] = [];
402 for (const workspaceDir of workspaceDirs) {
403 const files = await this.ideUtils.readDirectory(workspaceDir);
404 if (files === null) {//Unlikely, but just in case...
405 continue;
406 }
407 for (const [filename, type] of files) {
408 if (
409 (type === vscode.FileType.File ||
410 type === vscode.FileType.SymbolicLink) &&
411 filename === ".continuerc.json"
412 ) {
413 const contents = await this.readFile(
414 vscode.Uri.joinPath(workspaceDir, filename).toString(),
415 );
416 configs.push(JSON.parse(contents));
417 }
418 }
419 }
420 return configs;
421 }
422
423 async getWorkspaceDirs(): Promise<string[]> {
424 return this.ideUtils.getWorkspaceDirectories().map((uri) => uri.toString());
425 }
426
427 async writeFile(fileUri: string, contents: string): Promise<void> {
428 await vscode.workspace.fs.writeFile(
429 vscode.Uri.parse(fileUri),
430 Buffer.from(contents),
431 );
432 }
433
434 async showVirtualFile(title: string, contents: string): Promise<void> {
435 this.ideUtils.showVirtualFile(title, contents);
436 }
437
438 async openFile(fileUri: string): Promise<void> {
439 await this.ideUtils.openFile(vscode.Uri.parse(fileUri));
440 }
441
442 async showLines(
443 fileUri: string,
444 startLine: number,
445 endLine: number,
446 ): Promise<void> {
447 const range = new vscode.Range(
448 new vscode.Position(startLine, 0),
449 new vscode.Position(endLine, 0),
450 );
451 openEditorAndRevealRange(vscode.Uri.parse(fileUri), range).then(
452 (editor) => {
453 // Select the lines
454 editor.selection = new vscode.Selection(
455 new vscode.Position(startLine, 0),
456 new vscode.Position(endLine, 0),
457 );
458 },
459 );
460 }
461
462 async runCommand(
463 command: string,
464 options: TerminalOptions = { reuseTerminal: true },
465 ): Promise<void> {
466 let terminal: vscode.Terminal | undefined;
467 if (vscode.window.terminals.length && options.reuseTerminal) {
468 if (options.terminalName) {
469 terminal = vscode.window.terminals.find(
470 (t) => t?.name === options.terminalName,
471 );
472 } else {
473 terminal = vscode.window.activeTerminal ?? vscode.window.terminals[0];
474 }
475 }
476
477 if (!terminal) {
478 terminal = vscode.window.createTerminal(options?.terminalName);
479 }
480 terminal.show();
481 terminal.sendText(command, false);
482 }
483
484 async saveFile(fileUri: string): Promise<void> {
485 await this.ideUtils.saveFile(vscode.Uri.parse(fileUri));
486 }
487
488 private static MAX_BYTES = 100000;
489
490 async readFile(fileUri: string): Promise<string> {
491 try {
492 const uri = vscode.Uri.parse(fileUri);
493
494 // First, check whether it's a notebook document
495 // Need to iterate over the cells to get full contents
496 const notebook =
497 vscode.workspace.notebookDocuments.find((doc) =>
498 URI.equal(doc.uri.toString(), uri.toString()),
499 ) ??
500 (uri.path.endsWith("ipynb")
501 ? await vscode.workspace.openNotebookDocument(uri)
502 : undefined);
503 if (notebook) {
504 return notebook
505 .getCells()
506 .map((cell) => cell.document.getText())
507 .join("\n\n");
508 }
509
510 // Check whether it's an open document
511 const openTextDocument = vscode.workspace.textDocuments.find((doc) =>
512 URI.equal(doc.uri.toString(), uri.toString()),
513 );
514 if (openTextDocument !== undefined) {
515 return openTextDocument.getText();
516 }
517
518 const fileStats = await this.ideUtils.stat(uri);
519 if (fileStats === null || fileStats.size > 10 * VsCodeIde.MAX_BYTES) {
520 return "";
521 }
522
523 const bytes = await this.ideUtils.readFile(uri);
524 if (bytes === null) {
525 return "";
526 }
527
528 // Truncate the buffer to the first MAX_BYTES
529 const truncatedBytes = bytes.slice(0, VsCodeIde.MAX_BYTES);
530 const contents = new TextDecoder().decode(truncatedBytes);
531 return contents;
532 } catch (e) {
533 return "";
534 }
535 }
536
537 async openUrl(url: string): Promise<void> {
538 await vscode.env.openExternal(vscode.Uri.parse(url));
539 }
540
541 async getOpenFiles(): Promise<string[]> {
542 return this.ideUtils.getOpenFiles().map((uri) => uri.toString());
543 }
544
545 async getCurrentFile() {
546 if (!vscode.window.activeTextEditor) {
547 return undefined;
548 }
549 return {
550 isUntitled: vscode.window.activeTextEditor.document.isUntitled,
551 path: vscode.window.activeTextEditor.document.uri.toString(),
552 contents: vscode.window.activeTextEditor.document.getText(),
553 };
554 }
555
556 async getPinnedFiles(): Promise<string[]> {
557 const tabArray = vscode.window.tabGroups.all[0].tabs;
558
559 return tabArray
560 .filter((t) => t.isPinned)
561 .map((t) => (t.input as vscode.TabInputText).uri.toString());
562 }
563
564 runRipgrepQuery(dirUri: string, args: string[]) {
565 const relativeDir = vscode.Uri.parse(dirUri).fsPath;
566 const ripGrepUri = vscode.Uri.joinPath(
567 getExtensionUri(),
568 "out/node_modules/@vscode/ripgrep/bin/rg",
569 );
570 const p = child_process.spawn(ripGrepUri.fsPath, args, {
571 cwd: relativeDir,
572 });
573 let output = "";
574
575 p.stdout.on("data", (data) => {
576 output += data.toString();
577 });
578
579 return new Promise<string>((resolve, reject) => {
580 p.on("error", reject);
581 p.on("close", (code) => {
582 if (code === 0) {
583 resolve(output);
584 } else if (code === 1) {
585 // No matches
586 resolve("No matches found");
587 } else {
588 reject(new Error(`Process exited with code ${code}`));
589 }
590 });
591 });
592 }
593
594 async getFileResults(pattern: string): Promise<string[]> {
595 const MAX_FILE_RESULTS = 200;
596 if (vscode.env.remoteName) {
597 // TODO better tests for this remote search implementation
598 // throw new Error("Ripgrep not supported, this workspace is remote");
599
600 // IMPORTANT: findFiles automatically accounts for .gitignore
601 const ignoreFiles = await vscode.workspace.findFiles(
602 "**/.continueignore",
603 null,
604 );
605
606 const ignoreGlobs: Set<string> = new Set();
607 for (const file of ignoreFiles) {
608 const content = await this.ideUtils.readFile(file);
609 if (content === null) {
610 continue;
611 }
612 const filePath = vscode.workspace.asRelativePath(file);
613 const fileDir = filePath
614 .replace(/\\/g, "/")
615 .replace(/\/$/, "")
616 .split("/")
617 .slice(0, -1)
618 .join("/");
619
620 const patterns = Buffer.from(content)
621 .toString()
622 .split("\n")
623 .map((line) => line.trim())
624 .filter(
625 (line) => line && !line.startsWith("#") && !pattern.startsWith("!"),
626 );
627 // VSCode does not support negations
628
629 patterns
630 // Handle prefix
631 .map((pattern) => {
632 const normalizedPattern = pattern.replace(/\\/g, "/");
633
634 if (normalizedPattern.startsWith("/")) {
635 if (fileDir) {
636 return `{/,}${normalizedPattern}`;
637 } else {
638 return `${fileDir}/${normalizedPattern.substring(1)}`;
639 }
640 } else {
641 if (fileDir) {
642 return `${fileDir}/${normalizedPattern}`;
643 } else {
644 return `**/${normalizedPattern}`;
645 }
646 }
647 })
648 // Handle suffix
649 .map((pattern) => {
650 return pattern.endsWith("/") ? `${pattern}**/*` : pattern;
651 })
652 .forEach((pattern) => {
653 ignoreGlobs.add(pattern);
654 });
655 }
656
657 const ignoreGlobsArray = Array.from(ignoreGlobs);
658
659 const results = await vscode.workspace.findFiles(
660 pattern,
661 ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null,
662 MAX_FILE_RESULTS,
663 );
664 return results.map((result) => vscode.workspace.asRelativePath(result));
665 } else {
666 const results: string[] = [];
667 for (const dir of await this.getWorkspaceDirs()) {
668 const dirResults = await this.runRipgrepQuery(dir, [
669 "--files",
670 "--iglob",
671 pattern,
672 "--ignore-file",
673 ".continueignore",
674 "--ignore-file",
675 ".gitignore",
676 ]);
677
678 results.push(dirResults);
679 }
680
681 return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS);
682 }
683 }
684
685 async getSearchResults(query: string): Promise<string> {
686 if (vscode.env.remoteName) {
687 throw new Error("Ripgrep not supported, this workspace is remote");
688 }
689 const results: string[] = [];
690 for (const dir of await this.getWorkspaceDirs()) {
691 const dirResults = await this.runRipgrepQuery(dir, [
692 "-i", // Case-insensitive search
693 "--ignore-file",
694 ".continueignore",
695 "--ignore-file",
696 ".gitignore",
697 "-C",
698 "2", // Show 2 lines of context
699 "--heading", // Only show filepath once per result
700 "-e",
701 query, // Pattern to search for
702 ".", // Directory to search in
703 ]);
704
705 results.push(dirResults);
706 }
707
708 return results.join("\n");
709 }
710
711 async getProblems(fileUri?: string | undefined): Promise<Problem[]> {
712 const uri = fileUri
713 ? vscode.Uri.parse(fileUri)
714 : vscode.window.activeTextEditor?.document.uri;
715 if (!uri) {
716 return [];
717 }
718 return vscode.languages.getDiagnostics(uri).map((d) => {
719 return {
720 filepath: uri.toString(),
721 range: {
722 start: {
723 line: d.range.start.line,
724 character: d.range.start.character,
725 },
726 end: { line: d.range.end.line, character: d.range.end.character },
727 },
728 message: d.message,
729 };
730 });
731 }
732
733 async subprocess(command: string, cwd?: string): Promise<[string, string]> {
734 return new Promise((resolve, reject) => {
735 exec(command, { cwd }, (error, stdout, stderr) => {
736 if (error) {
737 console.warn(error);
738 reject(stderr);
739 }
740 resolve([stdout, stderr]);
741 });
742 });
743 }
744
745 async getBranch(dir: string): Promise<string> {
746 return this.ideUtils.getBranch(vscode.Uri.parse(dir));
747 }
748
749 async getGitRootPath(dir: string): Promise<string | undefined> {
750 const root = await this.ideUtils.getGitRoot(vscode.Uri.parse(dir));
751 return root?.toString();
752 }
753
754 async listDir(dir: string): Promise<[string, FileType][]> {
755 const entries = await this.ideUtils.readDirectory(vscode.Uri.parse(dir));
756 return entries === null? [] : entries as any;
757 }
758
759 private getIdeSettingsSync(): IdeSettings {
760 const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
761 const remoteConfigServerUrl = settings.get<string | undefined>(
762 "remoteConfigServerUrl",
763 undefined,
764 );
765 const ideSettings: IdeSettings = {
766 remoteConfigServerUrl,
767 remoteConfigSyncPeriod: settings.get<number>(
768 "remoteConfigSyncPeriod",
769 60,
770 ),
771 userToken: settings.get<string>("userToken", ""),
772 continueTestEnvironment: "production",
773 pauseCodebaseIndexOnStart: settings.get<boolean>(
774 "pauseCodebaseIndexOnStart",
775 false,
776 ),
777 };
778 return ideSettings;
779 }
780
781 async getIdeSettings(): Promise<IdeSettings> {
782 const ideSettings = this.getIdeSettingsSync();
783 return ideSettings;
784 }
785}
786
787export { VsCodeIde };