diff --git a/core/config/index.d.ts b/core/config/index.d.ts index dafb6e2df..7d0052969 100644 --- a/core/config/index.d.ts +++ b/core/config/index.d.ts @@ -133,6 +133,7 @@ interface SerializedContinueConfig { completionOptions?: BaseCompletionOptions; slashCommands?: SlashCommand[]; customCommands?: CustomCommand[]; + contextProviders?: ContextProviderWithParams[]; } export { StepName, diff --git a/core/context/index.ts b/core/context/index.ts index e837d0f2d..33b90d0dc 100644 --- a/core/context/index.ts +++ b/core/context/index.ts @@ -1,16 +1,23 @@ import { ContextItem } from "../llm/types"; -// TODO: - -export async function getContextItem(id: string, query: string) { - const item: ContextItem = { - id: { - providerTitle: "TODO", - itemId: id, - }, - name: "TODO", - description: "TODO", - content: query, - }; - return item; +export interface ContextProviderDescription { + title: string; + displayTitle: string; + description: string; + dynamic: boolean; + requiresQuery: boolean; +} + +export abstract class ContextProvider { + options: Object; + constructor(options: Object) { + this.options = options; + } + + static description: ContextProviderDescription; + + // Maybe just include the chat message in here. Should never have to go back to the context provider once you have the information. + abstract getContextItem(query: string): Promise; + + abstract load(): Promise; } diff --git a/core/context/providers/DiffContextProvider.ts b/core/context/providers/DiffContextProvider.ts new file mode 100644 index 000000000..df674a58e --- /dev/null +++ b/core/context/providers/DiffContextProvider.ts @@ -0,0 +1,20 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ExtensionIde } from "../../ide"; +import { ContextItem } from "../../llm/types"; + +class DiffContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "diff", + displayTitle: "Git Diff", + description: "Reference the current git diff", + dynamic: true, + requiresQuery: false, + }; + + async getContextItem(query: string): Promise { + return [await new ExtensionIde().getDiff()]; + } + async load(): Promise {} +} + +export default DiffContextProvider; diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts new file mode 100644 index 000000000..e52c15bbf --- /dev/null +++ b/core/context/providers/FileTreeContextProvider.ts @@ -0,0 +1,87 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ExtensionIde } from "../../ide"; +import { ContextItem } from "../../llm/types"; + +interface Directory { + name: string; + files: string[]; + directories: Directory[]; +} + +function splitPath(path: string, withRoot?: string): string[] { + let parts = path.includes("/") ? path.split("/") : path.split("\\"); + if (withRoot !== undefined) { + let rootParts = splitPath(withRoot); + parts = parts.slice(rootParts.length - 1); + } + return parts; +} + +function formatFileTree(tree: Directory, indentation: string = ""): string { + let result = ""; + for (let file of tree.files) { + result += `${indentation}${file}\n`; + } + + for (let directory of tree.directories) { + result += `${indentation}${directory.name}/\n`; + result += formatFileTree(directory, indentation + " "); + } + + return result; +} + +class FileTreeContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "tree", + displayTitle: "File Tree", + description: "Attach a representation of the file tree", + dynamic: true, + requiresQuery: false, + }; + + async getContextItem(query: string): Promise { + const workspaceDir = await new ExtensionIde().getWorkspaceDir(); + const contents = await new ExtensionIde().listWorkspaceContents(); + + const tree: Directory = { + name: splitPath(workspaceDir).pop(), + files: [], + directories: [], + }; + + for (let file of contents) { + const parts = splitPath(file, workspaceDir); + + let currentTree = tree; + for (let part of parts.slice(0, -1)) { + if (!currentTree.directories.some((d) => d.name === part)) { + currentTree.directories.push({ + name: part, + files: [], + directories: [], + }); + } + + currentTree = currentTree.directories.find((d) => d.name === part)!; + } + + currentTree.files.push(parts.pop()!); + } + + return [ + { + content: formatFileTree(tree), + name: "File Tree", + description: "File Tree", + id: { + providerTitle: "tree", + itemId: workspaceDir, + }, + }, + ]; + } + async load(): Promise {} +} + +export default FileTreeContextProvider; diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts new file mode 100644 index 000000000..0590bad84 --- /dev/null +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -0,0 +1,20 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ExtensionIde } from "../../ide"; +import { ContextItem } from "../../llm/types"; + +class GitHubIssuesContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "github", + displayTitle: "GitHub Issues", + description: "Reference GitHub issues", + dynamic: false, + requiresQuery: false, + }; + + async getContextItem(query: string): Promise { + return []; + } + async load(): Promise {} +} + +export default GitHubIssuesContextProvider; diff --git a/core/context/providers/GoogleContextProvider.ts b/core/context/providers/GoogleContextProvider.ts new file mode 100644 index 000000000..83d201165 --- /dev/null +++ b/core/context/providers/GoogleContextProvider.ts @@ -0,0 +1,65 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ExtensionIde } from "../../ide"; +import { ContextItem } from "../../llm/types"; + +class GoogleContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "google", + displayTitle: "Google", + description: "Attach the results of a Google search", + dynamic: true, + requiresQuery: false, + }; + + private _serperApiKey: string; + + constructor(options: { serperApiKey: string }) { + super(options); + this._serperApiKey = options.serperApiKey; + } + + async getContextItem(query: string): Promise { + const url = "https://google.serper.dev/search"; + + const payload = JSON.stringify({ q: query }); + const headers = { + "X-API-KEY": this._serperApiKey, + "Content-Type": "application/json", + }; + + const response = await fetch(url, { + method: "POST", + headers: headers, + body: payload, + }); + + const results = await response.text(); + + let jsonResults = JSON.parse(results); + let content = `Google Search: ${query}\n\n`; + let answerBox = jsonResults["answerBox"]; + + if (answerBox) { + content += `Answer Box (${answerBox["title"]}): ${answerBox["answer"]}\n\n`; + } + + for (let result of jsonResults["organic"]) { + content += `${result["title"]}\n${result["link"]}\n${result["snippet"]}\n\n`; + } + + return [ + { + content, + name: "Google Search", + description: "Google Search", + id: { + providerTitle: "google", + itemId: query, + }, + }, + ]; + } + async load(): Promise {} +} + +export default GoogleContextProvider; diff --git a/core/context/providers/TerminalContextProvider.ts b/core/context/providers/TerminalContextProvider.ts new file mode 100644 index 000000000..3ba07f330 --- /dev/null +++ b/core/context/providers/TerminalContextProvider.ts @@ -0,0 +1,20 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ExtensionIde } from "../../ide"; +import { ContextItem } from "../../llm/types"; + +class TerminalContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "terminal", + displayTitle: "Terminal", + description: "Reference the contents of the terminal", + dynamic: true, + requiresQuery: false, + }; + + async getContextItem(query: string): Promise { + return [await new ExtensionIde().getTerminalContents()]; + } + async load(): Promise {} +} + +export default TerminalContextProvider; diff --git a/core/context/providers/URLContextProvider.ts b/core/context/providers/URLContextProvider.ts new file mode 100644 index 000000000..249c46498 --- /dev/null +++ b/core/context/providers/URLContextProvider.ts @@ -0,0 +1,42 @@ +import { ContextProvider, ContextProviderDescription } from ".."; +import { ContextItem } from "../../llm/types"; + +class URLContextProvider extends ContextProvider { + static description: ContextProviderDescription = { + title: "url", + displayTitle: "URL", + description: "Attach the contents of a web page", + dynamic: true, + requiresQuery: true, + }; + + async getContextItem(query: string): Promise { + let url = query.trim(); + if (!url.startsWith("http")) { + url = "https://" + url; + } + + const response = await fetch(url); + const html = await response.text(); + const content = html; + const title = url + .replace("https://", "") + .replace("http://", "") + .replace("www.", ""); + + return [ + { + content, + name: title, + description: title, + id: { + providerTitle: "url", + itemId: query, + }, + }, + ]; + } + async load(): Promise {} +} + +export default URLContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts new file mode 100644 index 000000000..6c498e40e --- /dev/null +++ b/core/context/providers/index.ts @@ -0,0 +1,19 @@ +import DiffContextProvider from "./DiffContextProvider"; +import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider"; +import TerminalContextProvider from "./TerminalContextProvider"; +import OpenTabsContextProvider from "./OpenTabsContextProvider"; +import GoogleContextProvider from "./GoogleContextProvider"; +import SearchContextProvider from "./SearchContextProvider"; +import URLContextProvider from "./URLContextProvider"; +import FileTreeContextProvider from "./FileTreeContextProvider"; + +export default { + diff: DiffContextProvider, + github: GitHubIssuesContextProvider, + terminal: TerminalContextProvider, + open: OpenTabsContextProvider, + google: GoogleContextProvider, + search: SearchContextProvider, + url: URLContextProvider, + tree: FileTreeContextProvider, +}; diff --git a/core/ide/index.ts b/core/ide/index.ts index 9693286b9..e8daa0483 100644 --- a/core/ide/index.ts +++ b/core/ide/index.ts @@ -6,4 +6,24 @@ export class ExtensionIde implements IDE { const resp = await ideRequest("getSerializedConfig", {}); return resp.config; } + + async getDiff() { + const resp = await ideRequest("getDiff", {}); + return resp.diff; + } + + async getTerminalContents() { + const resp = await ideRequest("getTerminalContents", {}); + return resp.terminalContents; + } + + async listWorkspaceContents(): Promise { + const resp = await ideRequest("listWorkspaceContents", {}); + return resp.workspaceContents; + } + + async getWorkspaceDir(): Promise { + const resp = await ideRequest("getWorkspaceDir", {}); + return resp.workspaceDir; + } } diff --git a/core/ide/types.d.ts b/core/ide/types.d.ts index 63a32c7e4..84c713f26 100644 --- a/core/ide/types.d.ts +++ b/core/ide/types.d.ts @@ -2,6 +2,10 @@ import { SerializedContinueConfig } from "../types"; interface IDE { getSerializedConfig(): Promise; + getDiff(): Promise; + getTerminalContents(): Promise; + listWorkspaceContents(): Promise; + getWorkspaceDir(): Promise; } export { IDE }; diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 3d7370667..bf582e0cb 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -4,6 +4,7 @@ import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode"; import { ideProtocolClient, windowId } from "./activation/activate"; import * as io from "socket.io-client"; import { FileEdit } from "../schema/FileEdit"; +import VsCodeIde from "./ideProtocol"; let sockets: { [url: string]: io.Socket | undefined } = {}; @@ -228,6 +229,51 @@ export function getSidebarContent( break; } + case "getDiff": { + new VsCodeIde().getDiff().then((diff) => { + panel.webview.postMessage({ + type: "getDiff", + diff, + }); + }); + break; + } + case "getSerializedConfig": { + new VsCodeIde().getSerializedConfig().then((config) => { + panel.webview.postMessage({ + type: "getSerializedConfig", + config, + }); + }); + break; + } + case "getTerminalContents": { + new VsCodeIde().getTerminalContents().then((terminalContents) => { + panel.webview.postMessage({ + type: "getTerminalContents", + terminalContents, + }); + }); + break; + } + case "listWorkspaceContents": { + new VsCodeIde().listWorkspaceContents().then((workspaceContents) => { + panel.webview.postMessage({ + type: "listWorkspaceContents", + workspaceContents, + }); + }); + break; + } + case "getWorkspaceDir": { + new VsCodeIde().getWorkspaceDir().then((workspaceDir) => { + panel.webview.postMessage({ + type: "getWorkspaceDir", + workspaceDir, + }); + }); + break; + } } }); diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 792a2aa08..faf83ee10 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -1,11 +1,34 @@ import { IDE } from "../../../core/ide/types"; import * as fs from "fs"; import { getConfigJsonPath } from "./activation/environmentSetup"; +import { ideProtocolClient } from "./activation/activate"; +import { SerializedContinueConfig } from "../../../core/config"; class VsCodeIde implements IDE { - getSerializedConfig() { + async getSerializedConfig(): Promise { const configPath = getConfigJsonPath(); const config = JSON.parse(fs.readFileSync(configPath, "utf8")); return config; } + + async getDiff(): Promise { + return await ideProtocolClient.getDiff(); + } + + async getTerminalContents(): Promise { + return await ideProtocolClient.getTerminalContents(2); + } + + async listWorkspaceContents(): Promise { + return await ideProtocolClient.getDirectoryContents( + ideProtocolClient.getWorkspaceDirectory(), + true + ); + } + + async getWorkspaceDir(): Promise { + return ideProtocolClient.getWorkspaceDirectory(); + } } + +export default VsCodeIde; diff --git a/gui/src/components/mainInput/ComboBox.tsx b/gui/src/components/mainInput/ComboBox.tsx index 5bc66a552..b7a5bae85 100644 --- a/gui/src/components/mainInput/ComboBox.tsx +++ b/gui/src/components/mainInput/ComboBox.tsx @@ -62,7 +62,6 @@ import FileIcon from "../FileIcon"; import RingLoader from "../loaders/RingLoader"; import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; import { contextLengthSelector } from "../../redux/selectors/configSelectors"; -import { getContextItem } from "../../../../core/context"; import { addContextItem, addContextItemAtIndex, @@ -71,6 +70,7 @@ import { setInactive, } from "../../redux/slices/stateSlice"; import { ContextItem } from "../../../../core/llm/types"; +import useContextProviders from "../../hooks/useContextProviders"; const SEARCH_INDEX_NAME = "continue_context_items"; @@ -476,6 +476,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => { const [prevInputValue, setPrevInputValue] = useState(""); + const { getContextItem } = useContextProviders(); + const selectContextItem = useCallback( async (id: string, query: string) => { const timeout = setTimeout(() => { @@ -493,7 +495,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => { ); } }, - [client, props.index] + [client, props.index, getContextItem] ); const onInputValueChangeCallback = useCallback( diff --git a/gui/src/hooks/useContextProviders.ts b/gui/src/hooks/useContextProviders.ts new file mode 100644 index 000000000..c14b5379c --- /dev/null +++ b/gui/src/hooks/useContextProviders.ts @@ -0,0 +1,63 @@ +import { useEffect, useState } from "react"; +import { useSelector } from "react-redux"; +import { RootStore } from "../redux/store"; +import { ContextProviderName } from "../../../core/config"; +import { + ContextProvider, + ContextProviderDescription, +} from "../../../core/context"; +import Providers from "../../../core/context/providers"; +import { ContextItem } from "../../../core/llm/types"; + +function providerNameToProvider( + name: ContextProviderName +): typeof ContextProvider { + const cls = Providers[name]; + + if (!cls) { + throw new Error(`Unknown provider ${name}`); + } + + return cls; +} + +function useContextProviders() { + const [providers, setProviders] = useState<{ + [name: string]: ContextProvider; + }>({}); + const [providerDescriptions, setProviderDescriptions] = useState< + ContextProviderDescription[] + >([]); + + const providerConfig = useSelector( + (store: RootStore) => store.state.config.contextProviders + ); + + useEffect(() => { + let providersList = []; + let descriptionsList = []; + for (const [name, options] of Object.entries(providerConfig)) { + const provider = providerNameToProvider(name as ContextProviderName); + providersList.push((provider as any)(options)); + descriptionsList.push(provider.description); + } + + setProviders(providers); + setProviderDescriptions(descriptionsList); + }, [providerConfig]); + + async function getContextItem( + name: string, + query: string + ): Promise { + const provider = providers[name]; + if (!provider) { + throw new Error(`Unknown provider ${name}`); + } + return await provider.getContextItem(query); + } + + return { providerDescriptions, getContextItem }; +} + +export default useContextProviders; diff --git a/gui/src/hooks/useModels.ts b/gui/src/hooks/useModels.ts index 93b8038fa..2f0484d9e 100644 --- a/gui/src/hooks/useModels.ts +++ b/gui/src/hooks/useModels.ts @@ -21,50 +21,29 @@ import { LLM } from "../../../core/llm"; function modelDescriptionToLLM(desc: ModelDescription): LLM { let cls: typeof LLM; - switch (desc.provider) { - case "openai-free-trial": - cls = FreeTrial; - break; - case "anthropic": - cls = Anthropic; - break; - case "google-palm": - cls = GooglePalm; - break; - case "lmstudio": - cls = LMStudio; - break; - case "llamafile": - cls = Llamafile; - break; - case "ollama": - cls = Ollama; - break; - case "replicate": - cls = Replicate; - break; - case "text-gen-webui": - cls = TextGenWebUI; - break; - case "together": - cls = Together; - break; - case "huggingface-tgi": - cls = HuggingFaceTGI; - break; - case "huggingface-inference-api": - cls = HuggingFaceInferenceAPI; - break; - case "llama.cpp": - cls = LlamaCpp; - break; - case "openai-aiohttp": - case "openai": - cls = OpenAI; - break; - default: - throw new Error(`Unknown provider ${desc.provider}`); + const providerClasses = { + "openai-free-trial": FreeTrial, + anthropic: Anthropic, + "google-palm": GooglePalm, + lmstudio: LMStudio, + llamafile: Llamafile, + ollama: Ollama, + replicate: Replicate, + "text-gen-webui": TextGenWebUI, + together: Together, + "huggingface-tgi": HuggingFaceTGI, + "huggingface-inference-api": HuggingFaceInferenceAPI, + "llama.cpp": LlamaCpp, + "openai-aiohttp": OpenAI, + openai: OpenAI, + }; + + cls = providerClasses[desc.provider]; + + if (!cls) { + throw new Error(`Unknown provider ${desc.provider}`); } + return new (cls as any)({ ...desc, uniqueId: "None" }); }