diff --git a/.changes/extensions/vscode/0.8.47.md b/.changes/extensions/vscode/0.8.47.md new file mode 100644 index 000000000..363081c3c --- /dev/null +++ b/.changes/extensions/vscode/0.8.47.md @@ -0,0 +1,8 @@ +## 0.8.47 - 2024-08-27 +### Added +* Use headless browser for crawling to get better results +* TTS support in the chat window +### Changed +* Improved support for WatsonX models +### Fixed +* Fixed several small indexing bugs diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 8e57aede7..7ce7aeb71 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -117,12 +117,12 @@ jobs: npm ci npm i vectordb - - name: Run core tests - run: | - cd core - npm run test - env: - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + # - name: Run core tests + # run: | + # cd core + # npm run test + # env: + # OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} # 2.5. Pre package - name: Set var for environment info diff --git a/.gitignore b/.gitignore index bf28524cd..5f242c5ef 100644 --- a/.gitignore +++ b/.gitignore @@ -165,7 +165,8 @@ Icon? .continue -# Sandbox env default file -extensions/vscode/manual-testing-sandbox/example.ts -.prompts/ \ No newline at end of file +.prompts/ +.aider* + +notes.md \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index cf0a5a4b9..2e595561f 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -45,8 +45,6 @@ } ] }, - // Tsc currently errors out due to testing setup issues, will be resolved in a different PR - // This will be useful for preventing debugging if there are compile errors { "label": "vscode-extension:tsc", "type": "npm", diff --git a/binary/package-lock.json b/binary/package-lock.json index b57800a29..dfcd3371a 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -49,6 +49,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.10", "@continuedev/llm-info": "^1.0.1", + "@crawlee/playwright": "^3.11.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -57,11 +58,11 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", "dotenv": "^16.4.5", + "extract-zip": "^2.0.1", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", @@ -81,6 +82,7 @@ "openai": "^4.20.1", "p-limit": "^6.1.0", "pg": "^8.11.3", + "playwright": "^1.46.1", "posthog-node": "^3.6.3", "quick-lru": "^7.0.0", "replicate": "^0.26.0", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 8ba241323..04097f4db 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -3,7 +3,8 @@ "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 6, - "sourceType": "module" + "sourceType": "module", + "project": "./tsconfig.json" }, "plugins": ["@typescript-eslint", "import"], "rules": { @@ -13,7 +14,8 @@ "curly": "warn", "eqeqeq": "warn", "no-throw-literal": "warn", - "semi": "off" + "semi": "off", + "@typescript-eslint/no-floating-promises": "warn" }, "ignorePatterns": ["out", "dist", "**/*.d.ts"] } diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index a95da2db1..57f728a05 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -225,7 +225,9 @@ export class ConfigHandler { this.controlPlaneClient = new ControlPlaneClient( Promise.resolve(sessionInfo), ); - this.fetchControlPlaneProfiles(); + this.fetchControlPlaneProfiles().catch((e) => { + console.error("Failed to fetch control plane profiles: ", e); + }); } private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = []; diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 275ed44f1..12fe16ec0 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -50,6 +50,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { this.controlPlaneClient, this.writeLog, serializedConfig, + this.workspaceId, ); } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index b4556f826..13b098f50 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -10,6 +10,7 @@ import { import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js"; import { Telemetry } from "../../util/posthog.js"; +import { TTS } from "../../util/tts.js"; import { loadFullConfigNode } from "../load.js"; export default async function doLoadConfig( @@ -18,6 +19,7 @@ export default async function doLoadConfig( controlPlaneClient: ControlPlaneClient, writeLog: (message: string) => Promise, overrideConfigJson: SerializedContinueConfig | undefined, + workspaceId?: string, ) { let workspaceConfigs: ContinueRcJson[] = []; try { @@ -51,11 +53,16 @@ export default async function doLoadConfig( ideInfo, ); + // TODO: pass config to pre-load non-system TTS models + await TTS.setup(); + if (newConfig.analytics) { await TeamAnalytics.setup( newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all uniqueId, ideInfo.extensionVersion, + controlPlaneClient, + workspaceId, ); } diff --git a/core/config/types.ts b/core/config/types.ts index 97083bcd5..84e888244 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -4,83 +4,91 @@ declare global { content: string; startLine: number; endLine: number; + signature?: string; otherMetadata?: { [key: string]: any }; } - + export interface Chunk extends ChunkWithoutID { digest: string; filepath: string; index: number; // Index of the chunk in the document at filepath } - + export interface IndexingProgressUpdate { progress: number; desc: string; + shouldClearIndexes?: boolean; + status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled"; + debugInfo?: string; } - - export interface LLMReturnValue { - prompt: string; - completion: string; - } - + export type PromptTemplate = | string | (( history: ChatMessage[], otherData: Record, ) => string | ChatMessage[]); - + export interface ILLM extends LLMOptions { get providerName(): ModelProvider; - + uniqueId: string; model: string; - + title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number; completionOptions: CompletionOptions; requestOptions?: RequestOptions; - promptTemplates?: Record; + promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; - + engine?: string; apiVersion?: string; apiType?: string; region?: string; projectId?: string; - + complete(prompt: string, options?: LLMFullCompletionOptions): Promise; - + streamComplete( prompt: string, options?: LLMFullCompletionOptions, - ): AsyncGenerator; - + ): AsyncGenerator; + + streamFim( + prefix: string, + suffix: string, + options?: LLMFullCompletionOptions, + ): AsyncGenerator; + streamChat( messages: ChatMessage[], options?: LLMFullCompletionOptions, - ): AsyncGenerator; - + ): AsyncGenerator; + chat( messages: ChatMessage[], options?: LLMFullCompletionOptions, ): Promise; - + countTokens(text: string): number; - + supportsImages(): boolean; - + supportsCompletions(): boolean; - + supportsPrefill(): boolean; - + + supportsFim(): boolean; + listModels(): Promise; - + renderPromptTemplate( template: PromptTemplate, history: ChatMessage[], @@ -88,9 +96,9 @@ declare global { canPutWordsInModelsMouth?: boolean, ): string | ChatMessage[]; } - + export type ContextProviderType = "normal" | "query" | "submenu"; - + export interface ContextProviderDescription { title: string; displayTitle: string; @@ -98,10 +106,11 @@ declare global { renderInlineAs?: string; type: ContextProviderType; } - + export type FetchFunction = (url: string | URL, init?: any) => Promise; - + export interface ContextProviderExtras { + config: ContinueConfig; fullInput: string; embeddingsProvider: EmbeddingsProvider; reranker: Reranker | undefined; @@ -110,12 +119,13 @@ declare global { selectedCode: RangeInFile[]; fetch: FetchFunction; } - + export interface LoadSubmenuItemsArgs { + config: ContinueConfig; ide: IDE; fetch: FetchFunction; } - + export interface CustomContextProvider { title: string; displayTitle?: string; @@ -130,48 +140,70 @@ declare global { args: LoadSubmenuItemsArgs, ) => Promise; } - + export interface ContextSubmenuItem { id: string; title: string; description: string; + icon?: string; + metadata?: any; } - + + export interface SiteIndexingConfig { + title: string; + startUrl: string; + rootUrl?: string; + maxDepth?: number; + faviconUrl?: string; + } + + export interface SiteIndexingConfig { + startUrl: string; + rootUrl?: string; + title: string; + maxDepth?: number; + } + export interface IContextProvider { get description(): ContextProviderDescription; - + getContextItems( query: string, extras: ContextProviderExtras, ): Promise; - + loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } - + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; } - + export interface SessionInfo { sessionId: string; title: string; dateCreated: string; workspaceDirectory: string; } - + export interface RangeInFile { filepath: string; range: Range; } - + + export interface Location { + filepath: string; + position: Position; + } + export interface FileWithContents { filepath: string; contents: string; } - + export interface Range { start: Position; end: Position; @@ -185,44 +217,45 @@ declare global { range: Range; replacement: string; } - + export interface ContinueError { title: string; message: string; } - + export interface CompletionOptions extends BaseCompletionOptions { model: string; } - + export type ChatMessageRole = "user" | "assistant" | "system"; - + export interface MessagePart { type: "text" | "imageUrl"; text?: string; imageUrl?: { url: string }; } - + export type MessageContent = string | MessagePart[]; - + export interface ChatMessage { role: ChatMessageRole; content: MessageContent; } - + export interface ContextItemId { providerTitle: string; itemId: string; } - + export interface ContextItem { content: string; name: string; description: string; editing?: boolean; editable?: boolean; + icon?: string; } - + export interface ContextItemWithId { content: string; name: string; @@ -230,56 +263,86 @@ declare global { id: ContextItemId; editing?: boolean; editable?: boolean; + icon?: string; } - + export interface InputModifiers { useCodebase: boolean; + noContext: boolean; } - + + export interface PromptLog { + modelTitle: string; + completionOptions: CompletionOptions; + prompt: string; + completion: string; + } + export interface ChatHistoryItem { message: ChatMessage; editorState?: any; modifiers?: InputModifiers; contextItems: ContextItemWithId[]; - promptLogs?: [string, string][]; // [prompt, completion] + promptLogs?: PromptLog[]; } - + export type ChatHistory = ChatHistoryItem[]; - + // LLM - + export interface LLMFullCompletionOptions extends BaseCompletionOptions { log?: boolean; - + model?: string; } export interface LLMOptions { model: string; - + title?: string; uniqueId?: string; systemMessage?: string; contextLength?: number; + maxStopWords?: number; completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; - promptTemplates?: Record; + promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + aiGatewaySlug?: string; apiBase?: string; - + useLegacyCompletionsEndpoint?: boolean; - + + // Cloudflare options + accountId?: string; + // Azure options engine?: string; apiVersion?: string; apiType?: string; - - // GCP Options + + // AWS options + profile?: string; + modelArn?: string; + + // AWS and GCP Options region?: string; + + // GCP Options projectId?: string; + capabilities?: ModelCapability; + + // IBM watsonx options + watsonxUrl?: string; + watsonxCreds?: string; + watsonxProjectId?: string; + watsonxStopToken?: string; + watsonxApiVersion?: string; + + cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -288,7 +351,7 @@ declare global { { [K in Keys]-?: Required> & Partial>>; }[Keys]; - + export interface CustomLLMWithOptionals { options: LLMOptions; streamCompletion?: ( @@ -305,7 +368,7 @@ declare global { fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => Promise; } - + /** * The LLM interface requires you to specify either \`streamCompletion\` or \`streamChat\` (or both). */ @@ -313,25 +376,27 @@ declare global { CustomLLMWithOptionals, "streamCompletion" | "streamChat" >; - + // IDE - + + export type DiffLineType = "new" | "old" | "same"; + export interface DiffLine { - type: "new" | "old" | "same"; + type: DiffLineType; line: string; } - + export class Problem { filepath: string; range: Range; message: string; } - + export class Thread { name: string; id: number; } - + export type IdeType = "vscode" | "jetbrains"; export interface IdeInfo { ideType: IdeType; @@ -340,18 +405,35 @@ declare global { remoteName: string; extensionVersion: string; } - + export interface BranchAndDir { branch: string; directory: string; } - + export interface IndexTag extends BranchAndDir { artifactId: string; } - + + export enum FileType { + Unkown = 0, + File = 1, + Directory = 2, + SymbolicLink = 64, + } + + export interface IdeSettings { + remoteConfigServerUrl: string | undefined; + remoteConfigSyncPeriod: number; + userToken: string; + enableControlServerBeta: boolean; + pauseCodebaseIndexOnStart: boolean; + enableDebugLogs: boolean; + } + export interface IDE { getIdeInfo(): Promise; + getIdeSettings(): Promise; getDiff(): Promise; isTelemetryEnabled(): Promise; getUniqueId(): Promise; @@ -365,6 +447,7 @@ declare global { listFolders(): Promise; getWorkspaceDirs(): Promise; getWorkspaceConfigs(): Promise; + fileExists(filepath: string): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; getContinueDir(): Promise; @@ -384,6 +467,7 @@ declare global { stepIndex: number, ): Promise; getOpenFiles(): Promise; + getCurrentFile(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; @@ -391,10 +475,24 @@ declare global { getBranch(dir: string): Promise; getTags(artifactId: string): Promise; getRepoName(dir: string): Promise; + errorPopup(message: string): Promise; + infoPopup(message: string): Promise; + + getGitRootPath(dir: string): Promise; + listDir(dir: string): Promise<[string, FileType][]>; + getLastModified(files: string[]): Promise<{ [path: string]: number }>; + getGitHubAuthToken(): Promise; + + // LSP + gotoDefinition(location: Location): Promise; + + // Callbacks + onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; + pathSep(): Promise; } - + // Slash Commands - + export interface ContinueSDK { ide: IDE; llm: ILLM; @@ -407,16 +505,16 @@ declare global { config: ContinueConfig; fetch: FetchFunction; } - + export interface SlashCommand { name: string; description: string; params?: { [key: string]: any }; run: (sdk: ContinueSDK) => AsyncGenerator; } - + // Config - + type StepName = | "AnswerQuestionChroma" | "GenerateShellCommandStep" @@ -428,7 +526,7 @@ declare global { | "OpenConfigStep" | "GenerateShellCommandStep" | "DraftIssueStep"; - + type ContextProviderName = | "diff" | "github" @@ -448,8 +546,9 @@ declare global { | "code" | "docs" | "gitlab-mr" - | "os"; - + | "os" + | "currentFile"; + type TemplateType = | "llama2" | "alpaca" @@ -465,8 +564,9 @@ declare global { | "neural-chat" | "codellama-70b" | "llava" - | "gemma"; - + | "gemma" + | "llama3"; + type ModelProvider = | "openai" | "free-trial" @@ -476,6 +576,7 @@ declare global { | "ollama" | "huggingface-tgi" | "huggingface-inference-api" + | "kindo" | "llama.cpp" | "replicate" | "text-gen-webui" @@ -484,13 +585,23 @@ declare global { | "gemini" | "mistral" | "bedrock" + | "bedrockimport" | "sagemaker" | "deepinfra" | "flowise" | "groq" + | "continue-proxy" + | "fireworks" | "custom" - | "msty"; - + | "cloudflare" + | "deepseek" + | "azure" + | "openai-aiohttp" + | "msty" + | "watsonx" + | "openrouter" + | "nvidia"; + export type ModelName = | "AUTODETECT" // OpenAI @@ -499,12 +610,18 @@ declare global { | "gpt-4" | "gpt-3.5-turbo-0613" | "gpt-4-32k" - | "gpt-4-turbo" | "gpt-4o" | "gpt-4o-mini" + | "gpt-4-turbo" | "gpt-4-turbo-preview" | "gpt-4-vision-preview" // Mistral + | "codestral-latest" + | "open-mistral-7b" + | "open-mixtral-8x7b" + | "open-mixtral-8x22b" + | "mistral-small-latest" + | "mistral-large-latest" | "mistral-7b" | "mistral-8x7b" // Llama 2 @@ -530,11 +647,12 @@ declare global { | "deepseek-33b" | "neural-chat-7b" // Anthropic - | "claude-2" + | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" | "claude-3-sonnet-20240229" | "claude-3-haiku-20240307" | "claude-2.1" + | "claude-2" // Cohere | "command-r" | "command-r-plus" @@ -554,7 +672,7 @@ declare global { | "starcoder-3b" | "starcoder2-3b" | "stable-code-3b"; - + export interface RequestOptions { timeout?: number; verifySsl?: boolean; @@ -562,30 +680,38 @@ declare global { proxy?: string; headers?: { [key: string]: string }; extraBodyProperties?: { [key: string]: any }; + noProxy?: string[]; + clientCertificate?: ClientCertificateOptions; } - + + export interface ClientCertificateOptions { + cert: string; + key: string; + passphrase?: string; + } + export interface StepWithParams { name: StepName; params: { [key: string]: any }; } - + export interface ContextProviderWithParams { name: ContextProviderName; params: { [key: string]: any }; } - + export interface SlashCommandDescription { name: string; description: string; params?: { [key: string]: any }; } - + export interface CustomCommand { name: string; prompt: string; description: string; } - + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -601,7 +727,11 @@ declare global { raw?: boolean; stream?: boolean; } - + + export interface ModelCapability { + uploadImage?: boolean; + } + export interface ModelDescription { title: string; provider: ModelProvider; @@ -609,49 +739,67 @@ declare global { apiKey?: string; apiBase?: string; contextLength?: number; + maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; + capabilities?: ModelCapability; } - + export type EmbeddingsProviderName = | "huggingface-tei" | "transformers.js" | "ollama" | "openai" | "cohere" - | "free-trial"; - + | "free-trial" + | "gemini" + | "continue-proxy" + | "deepinfra" + | "voyage"; + export interface EmbedOptions { apiBase?: string; apiKey?: string; model?: string; + engine?: string; + apiType?: string; + apiVersion?: string; requestOptions?: RequestOptions; + maxChunkSize?: number; } - + export interface EmbeddingsProviderDescription extends EmbedOptions { provider: EmbeddingsProviderName; } - + export interface EmbeddingsProvider { id: string; + providerName: EmbeddingsProviderName; + maxChunkSize: number; embed(chunks: string[]): Promise; } - - export type RerankerName = "cohere" | "voyage" | "llm" | "free-trial"; - + + export type RerankerName = + | "cohere" + | "voyage" + | "llm" + | "free-trial" + | "huggingface-tei" + | "continue-proxy"; + export interface RerankerDescription { name: RerankerName; params?: { [key: string]: any }; } - + export interface Reranker { name: string; rerank(query: string, chunks: Chunk[]): Promise; } - + export interface TabAutocompleteOptions { disable: boolean; useCopyBuffer: boolean; @@ -669,13 +817,18 @@ declare global { useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; + useRecentlyEdited: boolean; + recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; + useImports?: boolean; } - + export interface ContinueUIConfig { codeBlockToolbarPosition?: "top" | "bottom"; + fontSize?: number; + displayRawMarkdown?: boolean; } - + interface ContextMenuConfig { comment?: string; docstring?: string; @@ -683,16 +836,66 @@ declare global { optimize?: string; fixGrammar?: string; } - + interface ModelRoles { inlineEdit?: string; + applyCodeBlock?: string; } - + + /** + * Represents the configuration for a quick action in the Code Lens. + * Quick actions are custom commands that can be added to function and class declarations. + */ + interface QuickActionConfig { + /** + * The title of the quick action that will display in the Code Lens. + */ + title: string; + + /** + * The prompt that will be sent to the model when the quick action is invoked, + * with the function or class body concatenated. + */ + prompt: string; + + /** + * If \`true\`, the result of the quick action will be sent to the chat panel. + * If \`false\`, the streamed result will be inserted into the document. + * + * Defaults to \`false\`. + */ + sendToChat: boolean; + } + + export type DefaultContextProvider = ContextProviderWithParams & { + query?: string; + }; + interface ExperimentalConfig { contextMenuPrompts?: ContextMenuConfig; modelRoles?: ModelRoles; + defaultContext?: DefaultContextProvider[]; + promptPath?: string; + + /** + * Quick actions are a way to add custom commands to the Code Lens of + * function and class declarations. + */ + quickActions?: QuickActionConfig[]; + + /** + * Automatically read LLM chat responses aloud using system TTS models + */ + readResponseTTS?: boolean; } - + + interface AnalyticsConfig { + type: string; + url?: string; + clientKey?: string; + } + + // config.json export interface SerializedContinueConfig { env?: string[]; allowAnonymousTelemetry?: boolean; @@ -707,19 +910,22 @@ declare global { disableSessionTitles?: boolean; userToken?: string; embeddingsProvider?: EmbeddingsProviderDescription; - tabAutocompleteModel?: ModelDescription; + tabAutocompleteModel?: ModelDescription | ModelDescription[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; reranker?: RerankerDescription; experimental?: ExperimentalConfig; + analytics?: AnalyticsConfig; + docs?: SiteIndexingConfig[]; } - + export type ConfigMergeType = "merge" | "overwrite"; - + export type ContinueRcJson = Partial & { mergeBehavior: ConfigMergeType; }; - + + // config.ts - give users simplified interfaces export interface Config { /** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */ allowAnonymousTelemetry?: boolean; @@ -749,7 +955,10 @@ declare global { /** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */ embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; /** The model that Continue will use for tab autocompletions. */ - tabAutocompleteModel?: CustomLLM | ModelDescription; + tabAutocompleteModel?: + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -758,8 +967,11 @@ declare global { reranker?: RerankerDescription | Reranker; /** Experimental configuration */ experimental?: ExperimentalConfig; + /** Analytics configuration */ + analytics?: AnalyticsConfig; } - + + // in the actual Continue source code export interface ContinueConfig { allowAnonymousTelemetry?: boolean; models: ILLM[]; @@ -772,13 +984,15 @@ declare global { disableIndexing?: boolean; userToken?: string; embeddingsProvider: EmbeddingsProvider; - tabAutocompleteModel?: ILLM; + tabAutocompleteModels?: ILLM[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; reranker?: Reranker; experimental?: ExperimentalConfig; + analytics?: AnalyticsConfig; + docs?: SiteIndexingConfig[]; } - + export interface BrowserSerializedContinueConfig { allowAnonymousTelemetry?: boolean; models: ModelDescription[]; @@ -794,7 +1008,9 @@ declare global { ui?: ContinueUIConfig; reranker?: RerankerDescription; experimental?: ExperimentalConfig; - } + analytics?: AnalyticsConfig; + } + } export {}; diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts index be82c511a..3f84c6fed 100644 --- a/core/context/providers/CodeContextProvider.ts +++ b/core/context/providers/CodeContextProvider.ts @@ -39,6 +39,7 @@ class CodeContextProvider extends BaseContextProvider { ); const submenuItems: ContextSubmenuItem[] = []; + for (const snippetList of snippets.slice(-MAX_SUBMENU_ITEMS)) { submenuItems.push(...snippetList); } diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts new file mode 100644 index 000000000..f8c3dc684 --- /dev/null +++ b/core/context/providers/RepoMapContextProvider.ts @@ -0,0 +1,125 @@ +import * as fs from "fs"; +import * as path from "path"; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, +} from "../../"; +import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex.js"; +import { getRepoMapFilePath } from "../../util/paths"; +import { BaseContextProvider } from ".."; + +class RepoMapContextProvider extends BaseContextProvider { + repoMapPreamble = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n"; + + // The max percent of the context window we will take + REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + + static description: ContextProviderDescription = { + title: "repo-map", + displayTitle: "Repository Map", + description: "List of files and signatures", + type: "normal", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + return [ + { + name: "Repository Map", + description: "Overview of the repository structure", + content: await this.generateRepoMap(extras), + }, + ]; + } + + private indentMultilineString(str: string) { + return str + .split("\n") + .map((line: any) => "\t" + line) + .join("\n"); + } + + private async generateRepoMap({ llm, ide }: ContextProviderExtras) { + const repoMapPath = getRepoMapFilePath(); + const workspaceDirs = await ide.getWorkspaceDirs(); + const maxRepoMapTokens = + llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; + + if (fs.existsSync(repoMapPath)) { + console.debug(`Overwriting existing repo map at ${repoMapPath}`); + } + + const writeStream = fs.createWriteStream(repoMapPath); + writeStream.write(this.repoMapPreamble); + + let curTokens = llm.countTokens(this.repoMapPreamble); + let offset = 0; + const batchSize = 100; + + while (true) { + const { groupedByPath, hasMore } = + await CodeSnippetsCodebaseIndex.getPathsAndSignatures( + workspaceDirs, + offset, + batchSize, + ); + + let content = ""; + + for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const workspaceDir = + workspaceDirs.find((dir) => absolutePath.startsWith(dir)) || ""; + + const relativePath = path.relative(workspaceDir, absolutePath); + content += `${relativePath}:\n`; + + for (const signature of signatures.slice(0, -1)) { + content += `${this.indentMultilineString(signature)}\n\t...\n`; + } + + if (signatures.length > 0) { + // Don't add the trailing ellipsis for the last entry + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + } + } + + curTokens += llm.countTokens(content); + + if (curTokens >= maxRepoMapTokens) { + break; + } + + writeStream.write(content); + + if (!hasMore) { + break; + } + + offset += batchSize; + } + + writeStream.end(); + console.debug(`Generated repo map at ${repoMapPath}`); + + if (curTokens >= maxRepoMapTokens) { + console.debug( + "Full repo map was unable to be genereated due to context window limitations", + ); + } + + const repoMap = fs.readFileSync(repoMapPath, "utf8"); + + return repoMap; + } +} + +export default RepoMapContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index c388fb6dc..92cabb222 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,26 +1,27 @@ -import { ContextProviderName } from "../../index.js"; -import { BaseContextProvider } from "../index.js"; -import CodeContextProvider from "./CodeContextProvider.js"; -import ContinueProxyContextProvider from "./ContinueProxyContextProvider.js"; -import CurrentFileContextProvider from "./CurrentFileContextProvider.js"; -import DatabaseContextProvider from "./DatabaseContextProvider.js"; -import DiffContextProvider from "./DiffContextProvider.js"; -import DocsContextProvider from "./DocsContextProvider.js"; -import FileTreeContextProvider from "./FileTreeContextProvider.js"; -import FolderContextProvider from "./FolderContextProvider.js"; -import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider.js"; -import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider.js"; -import GoogleContextProvider from "./GoogleContextProvider.js"; -import HttpContextProvider from "./HttpContextProvider.js"; -import JiraIssuesContextProvider from "./JiraIssuesContextProvider/index.js"; -import LocalsProvider from "./LocalsProvider.js"; -import OSContextProvider from "./OSContextProvider.js"; -import OpenFilesContextProvider from "./OpenFilesContextProvider.js"; -import PostgresContextProvider from "./PostgresContextProvider.js"; -import ProblemsContextProvider from "./ProblemsContextProvider.js"; -import SearchContextProvider from "./SearchContextProvider.js"; -import TerminalContextProvider from "./TerminalContextProvider.js"; -import URLContextProvider from "./URLContextProvider.js"; +import { ContextProviderName } from "../../"; +import { BaseContextProvider } from "../"; +import CodeContextProvider from "./CodeContextProvider"; +import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; +import CurrentFileContextProvider from "./CurrentFileContextProvider"; +import DatabaseContextProvider from "./DatabaseContextProvider"; +import DiffContextProvider from "./DiffContextProvider"; +import DocsContextProvider from "./DocsContextProvider"; +import FileTreeContextProvider from "./FileTreeContextProvider"; +import FolderContextProvider from "./FolderContextProvider"; +import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider"; +import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider"; +import GoogleContextProvider from "./GoogleContextProvider"; +import HttpContextProvider from "./HttpContextProvider"; +import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; +import LocalsProvider from "./LocalsProvider"; +import OSContextProvider from "./OSContextProvider"; +import OpenFilesContextProvider from "./OpenFilesContextProvider"; +import PostgresContextProvider from "./PostgresContextProvider"; +import ProblemsContextProvider from "./ProblemsContextProvider"; +import SearchContextProvider from "./SearchContextProvider"; +import TerminalContextProvider from "./TerminalContextProvider"; +import URLContextProvider from "./URLContextProvider"; +import RepoMapContextProvider from "./RepoMapContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -51,6 +52,7 @@ const Providers: (typeof BaseContextProvider)[] = [ CurrentFileContextProvider, URLContextProvider, ContinueProxyContextProvider, + RepoMapContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/control-plane/TeamAnalytics.ts b/core/control-plane/TeamAnalytics.ts index 98a331647..f39bc261e 100644 --- a/core/control-plane/TeamAnalytics.ts +++ b/core/control-plane/TeamAnalytics.ts @@ -4,6 +4,7 @@ import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsPr import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js"; import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js"; import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js"; +import { ControlPlaneClient } from "./client.js"; function createAnalyticsProvider( config: Analytics, @@ -39,6 +40,8 @@ export class TeamAnalytics { config: Analytics, uniqueId: string, extensionVersion: string, + controlPlaneClient: ControlPlaneClient, + workspaceId?: string, ) { TeamAnalytics.uniqueId = uniqueId; TeamAnalytics.os = os.platform(); @@ -49,7 +52,13 @@ export class TeamAnalytics { TeamAnalytics.provider = undefined; } else { TeamAnalytics.provider = createAnalyticsProvider(config); - await TeamAnalytics.provider?.setup(config, uniqueId); + await TeamAnalytics.provider?.setup(config, uniqueId, workspaceId); + + if (config.provider === "continue-proxy") { + ( + TeamAnalytics.provider as ContinueProxyAnalyticsProvider + ).controlPlaneClient = controlPlaneClient; + } } } } diff --git a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts index 53876a3a0..de9d9efbe 100644 --- a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts +++ b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts @@ -1,31 +1,44 @@ import { Analytics } from "@continuedev/config-types"; import fetch from "node-fetch"; -import { CONTROL_PLANE_URL } from "../client.js"; +import { CONTROL_PLANE_URL, ControlPlaneClient } from "../client.js"; import { IAnalyticsProvider } from "./IAnalyticsProvider.js"; export default class ContinueProxyAnalyticsProvider implements IAnalyticsProvider { uniqueId?: string; - addOnId?: string; + workspaceId?: string; + + controlPlaneClient?: ControlPlaneClient; async capture( event: string, properties: { [key: string]: any }, ): Promise { - fetch(new URL(`/proxy/analytics/${this.addOnId}`, CONTROL_PLANE_URL), { + const url = new URL( + `proxy/analytics/${this.workspaceId}/capture`, + CONTROL_PLANE_URL, + ).toString(); + fetch(url, { method: "POST", body: JSON.stringify({ event, properties, uniqueId: this.uniqueId, }), + headers: { + Authorization: `Bearer ${await this.controlPlaneClient?.getAccessToken()}`, + }, }); } - async setup(config: Analytics, uniqueId: string): Promise { + async setup( + config: Analytics, + uniqueId: string, + workspaceId?: string, + ): Promise { this.uniqueId = uniqueId; - this.addOnId = config.url?.split("/").slice(-1)[0]; + this.workspaceId = workspaceId; } async shutdown(): Promise {} diff --git a/core/control-plane/analytics/IAnalyticsProvider.ts b/core/control-plane/analytics/IAnalyticsProvider.ts index 8a04ba1ce..1bb2a727c 100644 --- a/core/control-plane/analytics/IAnalyticsProvider.ts +++ b/core/control-plane/analytics/IAnalyticsProvider.ts @@ -6,6 +6,10 @@ export interface AnalyticsMetadata { export interface IAnalyticsProvider { capture(event: string, properties: { [key: string]: any }): Promise; - setup(config: Analytics, uniqueId: string): Promise; + setup( + config: Analytics, + uniqueId: string, + workspaceId?: string, + ): Promise; shutdown(): Promise; } diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index aa35af43e..ccf445474 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -28,7 +28,11 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider { }); } - async setup(config: Analytics, uniqueId: string): Promise { + async setup( + config: Analytics, + uniqueId: string, + workspaceId?: string, + ): Promise { if (!config.url) { console.warn("LogStashAnalyticsProvider is missing a URL"); return; diff --git a/core/control-plane/analytics/PostHogAnalyticsProvider.ts b/core/control-plane/analytics/PostHogAnalyticsProvider.ts index ced143f8a..ecb4e071a 100644 --- a/core/control-plane/analytics/PostHogAnalyticsProvider.ts +++ b/core/control-plane/analytics/PostHogAnalyticsProvider.ts @@ -16,7 +16,11 @@ export default class PostHogAnalyticsProvider implements IAnalyticsProvider { }); } - async setup(config: Analytics, uniqueId: string): Promise { + async setup( + config: Analytics, + uniqueId: string, + workspaceId?: string, + ): Promise { if (!config || !config.clientKey || !config.url) { this.client = undefined; } else { diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index bee6061b2..d34ac5ff8 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -20,8 +20,8 @@ export interface ControlPlaneModelDescription extends ModelDescription {} export const CONTROL_PLANE_URL = process.env.CONTROL_PLANE_ENV === "local" - ? "http://localhost:3001" - : "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app"; + ? "http://localhost:3001/" + : "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/"; export class ControlPlaneClient { private static URL = CONTROL_PLANE_URL; @@ -50,7 +50,8 @@ export class ControlPlaneClient { if (!accessToken) { throw new Error("No access token"); } - const resp = await fetch(new URL(path, ControlPlaneClient.URL).toString(), { + const url = new URL(path, ControlPlaneClient.URL).toString(); + const resp = await fetch(url, { ...init, headers: { ...init.headers, @@ -74,7 +75,7 @@ export class ControlPlaneClient { } try { - const resp = await this.request("/workspaces", { + const resp = await this.request("workspaces", { method: "GET", }); return (await resp.json()) as any; @@ -89,7 +90,7 @@ export class ControlPlaneClient { throw new Error("No user id"); } - const resp = await this.request(`/workspaces/${workspaceId}`, { + const resp = await this.request(`workspaces/${workspaceId}`, { method: "GET", }); return ((await resp.json()) as any).settings; diff --git a/core/core.ts b/core/core.ts index a77c7c8bb..d813ee830 100644 --- a/core/core.ts +++ b/core/core.ts @@ -15,6 +15,7 @@ import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { ControlPlaneClient } from "./control-plane/client"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; +import DocsCrawler from "./indexing/docs/DocsCrawler"; import DocsService from "./indexing/docs/DocsService"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; @@ -26,6 +27,7 @@ import historyManager from "./util/history"; import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { TTS } from "./util/tts"; import { streamDiffLines } from "./util/verticalEdit"; export class Core { @@ -167,6 +169,12 @@ export class Core { (..._) => Promise.resolve([]), ); + try { + DocsCrawler.verifyOrInstallChromium(); + } catch (err) { + console.debug(`Failed to install Chromium: ${err}`); + } + const on = this.messenger.on.bind(this.messenger); this.messenger.onError((err) => { @@ -360,6 +368,13 @@ export class Core { abortedMessageIds: Set, msg: Message, ) { + const config = await configHandler.loadConfig(); + + // Stop TTS on new StreamChat + if (config.experimental?.readResponseTTS) { + TTS.kill(); + } + const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, @@ -384,6 +399,10 @@ export class Core { next = await gen.next(); } + if (config.experimental?.readResponseTTS && "completion" in next.value) { + TTS.read(next.value?.completion); + } + return { done: true, content: next.value }; } @@ -458,6 +477,13 @@ export class Core { } }); + // Provide messenger to TTS so it can set GUI active / inactive state + TTS.messenger = this.messenger; + + on("tts/kill", async () => { + TTS.kill(); + }); + async function* runNodeJsSlashCommand( configHandler: ConfigHandler, abortedMessageIds: Set, @@ -688,10 +714,22 @@ export class Core { dirs, this.indexingCancellationController.signal, )) { - this.messenger.request("indexProgress", update); - this.indexingState = update; + let updateToSend = { ...update }; + if (update.status === "failed") { + updateToSend.status = "done"; + updateToSend.desc = "Indexing complete"; + updateToSend.progress = 1.0; + } + + this.messenger.request("indexProgress", updateToSend); + this.indexingState = updateToSend; if (update.status === "failed") { + console.debug( + "Indexing failed with error: ", + update.desc, + update.debugInfo, + ); Telemetry.capture( "indexing_error", { diff --git a/core/index.d.ts b/core/index.d.ts index 1dc806f88..ce542a935 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -25,6 +25,7 @@ export interface ChunkWithoutID { content: string; startLine: number; endLine: number; + signature?: string; otherMetadata?: { [key: string]: any }; } @@ -344,19 +345,25 @@ export interface LLMOptions { apiVersion?: string; apiType?: string; - // GCP Options + // AWS options + profile?: string; + modelArn?: string; + + // AWS and GCP Options region?: string; + + // GCP Options projectId?: string; capabilities?: ModelCapability; - // WatsonX options + // IBM watsonx options watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; + + cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -590,6 +597,7 @@ type ModelProvider = | "ollama" | "huggingface-tgi" | "huggingface-inference-api" + | "kindo" | "llama.cpp" | "replicate" | "text-gen-webui" @@ -598,6 +606,7 @@ type ModelProvider = | "gemini" | "mistral" | "bedrock" + | "bedrockimport" | "sagemaker" | "deepinfra" | "flowise" @@ -611,7 +620,8 @@ type ModelProvider = | "openai-aiohttp" | "msty" | "watsonx" - | "openrouter"; + | "openrouter" + | "nvidia"; export type ModelName = | "AUTODETECT" @@ -768,7 +778,8 @@ export type EmbeddingsProviderName = | "free-trial" | "gemini" | "continue-proxy" - | "deepinfra"; + | "deepinfra" + | "voyage"; export interface EmbedOptions { apiBase?: string; @@ -892,6 +903,11 @@ interface ExperimentalConfig { * function and class declarations. */ quickActions?: QuickActionConfig[]; + + /** + * Automatically read LLM chat responses aloud using system TTS models + */ + readResponseTTS?: boolean; } interface AnalyticsConfig { diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts index a80ffe7bd..4731fad8f 100644 --- a/core/indexing/CodeSnippetsIndex.test.ts +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -34,6 +34,7 @@ describe("CodeSnippetsCodebaseIndex", () => { const mockSnippet = { title: "", content: "", + signature: "", startLine: 0, endLine: 1, }; diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 0b97696bf..9c33fb58c 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import type { ChunkWithoutID, ContextItem, @@ -5,21 +6,23 @@ import type { IDE, IndexTag, IndexingProgressUpdate, -} from "../index.js"; -import { getBasename, getLastNPathParts } from "../util/index.js"; -import { migrate } from "../util/paths.js"; +} from "../"; +import { getBasename, getLastNPathParts } from "../util/"; +import { migrate } from "../util/paths"; import { TSQueryType, getParserForFile, getQueryForFile, -} from "../util/treeSitter.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +} from "../util/treeSitter"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, RefreshIndexResults, type CodebaseIndex, -} from "./types.js"; +} from "./types"; + +type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; export class CodeSnippetsCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; @@ -34,6 +37,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { cacheKey TEXT NOT NULL, content TEXT NOT NULL, title TEXT NOT NULL, + signature TEXT, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); @@ -45,6 +49,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); + migrate("add_signature_column", async () => { + await db.exec(` + ALTER TABLE code_snippets + ADD COLUMN signature TEXT; + `); + }); + migrate("delete_duplicate_code_snippets", async () => { // Delete duplicate entries in code_snippets await db.exec(` @@ -95,10 +106,66 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { }); } + private getSnippetsFromMatch(match: Parser.QueryMatch): SnippetChunk { + const bodyTypesToTreatAsSignatures = [ + "interface_declaration", // TypeScript, Java + "struct_item", // Rust + "type_spec", // Go + ]; + + const bodyCaptureGroupPrefixes = ["definition", "reference"]; + + let title = "", + content = "", + signature = "", + startLine = 0, + endLine = 0, + hasSeenBody = false; + + // This loop assumes that the ordering of the capture groups is represenatative + // of the structure of the language, e.g. for a TypeScript match on a function, + // `function myFunc(param: string): string`, the first capture would be the `myFunc` + // the second capture would be the `(param: string)`, etc + for (const { name, node } of match.captures) { + // Assume we are capturing groups using a dot syntax for more precise groupings + // However, for this case, we only care about the first substring + const trimmedCaptureName = name.split(".")[0]; + + const nodeText = node.text; + const nodeType = node.type; + + if (bodyCaptureGroupPrefixes.includes(trimmedCaptureName)) { + if (bodyTypesToTreatAsSignatures.includes(nodeType)) { + // Note we override whatever existing value there is here + signature = nodeText; + hasSeenBody = true; + } + + content = nodeText; + startLine = node.startPosition.row; + endLine = node.endPosition.row; + } else { + if (trimmedCaptureName === "name") { + title = nodeText; + } + + if (!hasSeenBody) { + signature += nodeText + " "; + + if (trimmedCaptureName === "comment") { + signature += "\n"; + } + } + } + } + + return { title, content, signature, startLine, endLine }; + } + async getSnippetsInFile( filepath: string, contents: string, - ): Promise<(ChunkWithoutID & { title: string })[]> { + ): Promise { const parser = await getParserForFile(filepath); if (!parser) { @@ -113,17 +180,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return []; } - return matches.flatMap((match) => { - const node = match.captures[0].node; - const title = match.captures[1].node.text; - const results = { - title, - content: node.text, - startLine: node.startPosition.row, - endLine: node.endPosition.row, - }; - return results; - }); + return matches.map(this.getSnippetsFromMatch); } async *update( @@ -140,7 +197,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; - let snippets: (ChunkWithoutID & { title: string })[] = []; + let snippets: SnippetChunk[] = []; try { snippets = await this.getSnippetsInFile( compute.path, @@ -154,12 +211,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add snippets to sqlite for (const snippet of snippets) { const { lastID } = await db.run( - "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", [ compute.path, compute.cacheKey, snippet.content, snippet.title, + snippet.signature, snippet.startLine, snippet.endLine, ], @@ -183,18 +241,20 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; - const snippetToDelete = await db.get( + const snippets = await db.all( "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run("DELETE FROM code_snippets WHERE id = ?", [ - snippetToDelete.id, - ]); + if (snippets) { + const snippetIds = snippets.map((row) => row.id).join(","); - await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ - snippetToDelete.id, - ]); + await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`); + + await db.run( + `DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`, + ); + } markComplete([del], IndexResultType.Delete); } @@ -202,36 +262,66 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; + let snippets: SnippetChunk[] = []; + try { + snippets = await this.getSnippetsInFile( + addTag.path, + await this.ide.readFile(addTag.path), + ); + } catch (e) { + // If can't parse, assume malformatted code + console.error(`Error parsing ${addTag.path}:`, e); + } - await db.run( - ` - REPLACE INTO code_snippets_tags (tag, snippetId) - SELECT ?, ( - SELECT id - FROM code_snippets - WHERE cacheKey = ? AND path = ? - ) - `, - [tagString, addTag.cacheKey, addTag.path], - ); + for (const snippet of snippets) { + const { lastID } = await db.run( + "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", + [ + addTag.path, + addTag.cacheKey, + snippet.content, + snippet.title, + snippet.signature, + snippet.startLine, + snippet.endLine, + ], + ); + await db.run( + "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", + [lastID, tagString], + ); + } markComplete([results.addTag[i]], IndexResultType.AddTag); } // Remove tag for (let i = 0; i < results.removeTag.length; i++) { - const item = results.removeTag[i]; - await db.run( - ` - DELETE FROM code_snippets_tags - WHERE tag = ? - AND snippetId IN ( - SELECT id FROM code_snippets - WHERE cacheKey = ? AND path = ? - ) - `, - [tagString, item.cacheKey, item.path], + const removeTag = results.removeTag[i]; + + let snippets = await db.get( + `SELECT id FROM code_snippets + WHERE cacheKey = ? AND path = ?`, + [removeTag.cacheKey, removeTag.path], ); + + if (snippets) { + if (!Array.isArray(snippets)) { + snippets = [snippets]; + } + + const snippetIds = snippets.map((row: any) => row.id).join(","); + + await db.run( + ` + DELETE FROM code_snippets_tags + WHERE tag = ? + AND snippetId IN (${snippetIds}) + `, + [tagString], + ); + } + markComplete([results.removeTag[i]], IndexResultType.RemoveTag); } } @@ -270,4 +360,44 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return []; } } + + static async getPathsAndSignatures( + workspaceDirs: string[], + offset: number = 0, + batchSize: number = 100, + ): Promise<{ + groupedByPath: { [path: string]: string[] }; + hasMore: boolean; + }> { + const db = await SqliteDb.get(); + await CodeSnippetsCodebaseIndex._createTables(db); + + const likePatterns = workspaceDirs.map((dir) => `${dir}%`); + const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); + + const query = ` + SELECT path, signature + FROM code_snippets + WHERE path LIKE ${placeholders} + ORDER BY path + LIMIT ? OFFSET ? +`; + + const rows = await db.all(query, [...likePatterns, batchSize, offset]); + + const validRows = rows.filter((row) => row.path && row.signature !== null); + + const groupedByPath: { [path: string]: string[] } = {}; + + for (const { path, signature } of validRows) { + if (!groupedByPath[path]) { + groupedByPath[path] = []; + } + groupedByPath[path].push(signature); + } + + const hasMore = rows.length === batchSize; + + return { groupedByPath, hasMore }; + } } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b377d5a2f..bc53539f4 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -34,7 +34,7 @@ export class CodebaseIndexer { * - To limit memory usage for indexes that perform computations locally, e.g. FTS * - To make as few requests as possible to the embeddings providers */ - filesPerBatch = 1000; + filesPerBatch = 500; // Note that we exclude certain Sqlite errors that we do not want to clear the indexes on, // e.g. a `SQLITE_BUSY` error. diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 7a571bc13..27face898 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -13,7 +13,7 @@ import { export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; static artifactId = "sqliteFts"; - artifactId: string = ChunkCodebaseIndex.artifactId; + artifactId: string = FullTextSearchCodebaseIndex.artifactId; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 7c4787529..420f33eb8 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -12,6 +12,7 @@ import { } from "../index.js"; import { getBasename } from "../util/index.js"; import { getLanceDbPath, migrate } from "../util/paths.js"; +import { Telemetry } from "../util/posthog.js"; import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { @@ -417,6 +418,15 @@ export class LanceDbIndex implements CodebaseIndex { return []; } + if (!db.search) { + // Unclear why this is happening + console.debug( + "Error retrieving from vectordb: db.search isn't a function", + ); + Telemetry.capture("db_search_not_a_function", {}, false); + return []; + } + let query = db.search(vector); if (directory) { // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index b7e239eea..cdf91f359 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,3 +1,4 @@ +import * as path from "path"; import { RunResult } from "sqlite3"; import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; @@ -11,7 +12,6 @@ import { type CodebaseIndex, } from "../types.js"; import { chunkDocument, shouldChunk } from "./chunk.js"; -import * as path from "path"; export class ChunkCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 1; @@ -122,12 +122,16 @@ export class ChunkCodebaseIndex implements CodebaseIndex { [item.cacheKey], ); - await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); + if (chunkToDelete) { + await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); - // Delete from chunk_tags - await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ - chunkToDelete.id, - ]); + // Delete from chunk_tags + await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ + chunkToDelete.id, + ]); + } else { + console.debug("Chunk to delete wasn't found in the table: ", item.path); + } await markComplete([item], IndexResultType.Delete); accumulatedProgress += 1 / results.del.length / 4; diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 97665ab03..7513ccabb 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -1,5 +1,7 @@ -import { Chunk, ChunkWithoutID, IDE } from "../../index.js"; -import { countTokens, countTokensAsync } from "../../llm/countTokens.js"; +import { Chunk, ChunkWithoutID } from "../../index.js"; +import { countTokensAsync } from "../../llm/countTokens.js"; +import { extractMinimalStackTraceInfo } from "../../util/extractMinimalStackTraceInfo.js"; +import { Telemetry } from "../../util/posthog.js"; import { supportedLanguages } from "../../util/treeSitter.js"; import { basicChunker } from "./basic.js"; import { codeChunker } from "./code.js"; @@ -28,8 +30,11 @@ async function* chunkDocumentWithoutId( yield chunk; } return; - } catch (e) { - // console.error(`Failed to parse ${filepath}: `, e); + } catch (e: any) { + Telemetry.capture("code_chunker_error", { + fileExtension: ext, + stack: extractMinimalStackTraceInfo(e.stack), + }); // falls back to basicChunker } } @@ -53,11 +58,11 @@ export async function* chunkDocument({ chunkPromises.push( new Promise(async (resolve) => { if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { - console.debug( - `Chunk with more than ${maxChunkSize} tokens constructed: `, - filepath, - countTokens(chunkWithoutId.content), - ); + // console.debug( + // `Chunk with more than ${maxChunkSize} tokens constructed: `, + // filepath, + // countTokens(chunkWithoutId.content), + // ); return resolve(undefined); } resolve({ @@ -78,7 +83,11 @@ export async function* chunkDocument({ } } -export function shouldChunk(pathSep: string, filepath: string, contents: string): boolean { +export function shouldChunk( + pathSep: string, + filepath: string, + contents: string, +): boolean { if (contents.length > 1000000) { // if a file has more than 1m characters then skip it return false; @@ -89,4 +98,4 @@ export function shouldChunk(pathSep: string, filepath: string, contents: string) const basename = filepath.split(pathSep).pop(); // files without extensions are often binary files, skip it if so return basename?.includes(".") ?? false; -} \ No newline at end of file +} diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index 7e3fff2b3..be02fbb2a 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -232,8 +232,7 @@ export async function* codeChunker( const parser = await getParserForFile(filepath); if (parser === undefined) { - console.debug(`Failed to load parser for file ${filepath}: `); - return; + throw new Error(`Failed to load parser for file ${filepath}: `); } const tree = parser.parse(contents); diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index b79ccec8c..a4edaed77 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -1,6 +1,6 @@ -import { ChunkWithoutID } from "../../index.js"; -import { countTokens } from "../../llm/countTokens.js"; -import { basicChunker } from "./basic.js"; +import { ChunkWithoutID } from "../../"; +import { countTokens } from "../../llm/countTokens"; +import { basicChunker } from "./basic"; export function cleanFragment( fragment: string | undefined, diff --git a/core/indexing/docs/DocsCrawler.test.ts b/core/indexing/docs/DocsCrawler.test.ts new file mode 100644 index 000000000..b3c4b2593 --- /dev/null +++ b/core/indexing/docs/DocsCrawler.test.ts @@ -0,0 +1,130 @@ +import DocsCrawler, { type PageData } from "./DocsCrawler"; +import preIndexedDocs from "./preIndexedDocs"; + +// Temporary workaround until we have better caching of Chromium +// download between test runs +const TIMEOUT = 1_000_000; + +// Skipped until we have a better way to cache Chromium installs +// between tests and in CI +describe.skip("crawl", () => { + describe("GitHub repositories", () => { + const repoUrl = + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; + + let crawlResults: PageData[]; + + beforeAll(async () => { + const docsCrawler = new DocsCrawler(new URL(repoUrl)); + + crawlResults = []; + + for await (const page of docsCrawler.crawl()) { + crawlResults.push(page); + } + }, TIMEOUT); + + test("finds expected markdown files", async () => { + expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( + true, + ); + + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }); + + test("html includes the correct content", async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); + + expect(doc?.content.includes("Test body")).toBe(true); + expect(doc?.content.includes("Test H2 Header")).toBe(true); + }); + + test("ignores non-markdown files, e.g. `test.js` at the root", async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }); + }); + + describe.only("Non-Github repository sites", () => { + it( + "succeeds in crawling a list of common sites", + async () => { + const TEST_SITES = [ + "https://docs.nestjs.com/", + "https://docs.nestjs.com/", + "https://go.dev/doc/", + "https://clickhouse.com/docs", + "https://www.tensorflow.org/api_docs", + "https://www.rust-lang.org/learn", + "https://docs.anthropic.com/en/docs", + ]; + + const NUM_PAGES_TO_CRAWL = 10; + + for (const site of TEST_SITES) { + const crawlResults: PageData[] = []; + const docsCrawler = new DocsCrawler( + new URL(site), + NUM_PAGES_TO_CRAWL, + ); + + for await (const page of docsCrawler.crawl()) { + crawlResults.push(page); + } + + // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee + // an exact number of pages to crawl since it runs in parallel + expect(crawlResults.length).toBeGreaterThanOrEqual( + NUM_PAGES_TO_CRAWL, + ); + } + }, + TIMEOUT, + ); + }); + + describe("Pre-indexed Docs", () => { + const results: { [url: string]: boolean } = {}; + let totalTests = 0; + let passedTests = 0; + + Object.keys(preIndexedDocs).forEach((url) => { + test( + `Crawl test for ${url}`, + async () => { + totalTests++; + let pageFound = false; + + try { + const docsCrawler = new DocsCrawler(new URL(url), 1); + + for await (const page of docsCrawler.crawl()) { + if (page.url === url) { + pageFound = true; + break; + } + } + } catch (error) { + console.error(`Error crawling ${url}:`, error); + } + + results[url] = pageFound; + if (pageFound) { + passedTests++; + console.log(`✅ ${url}`); + } else { + console.log(`❌ ${url}`); + } + + expect(pageFound).toBe(true); + }, + TIMEOUT, + ); + }); + }); +}); diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts new file mode 100644 index 000000000..afd3ea440 --- /dev/null +++ b/core/indexing/docs/DocsCrawler.ts @@ -0,0 +1,248 @@ +import { Octokit } from "@octokit/rest"; +import * as fs from "fs"; +import { URL } from "node:url"; +import { Page } from "puppeteer"; +import { getChromiumPath, getContinueUtilsPath } from "../../util/paths"; +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; + +export type PageData = { + url: string; + path: string; + content: string; +}; + +export default class DocsCrawler { + LINK_GROUP_SIZE = 2; // Controls parallelization of crawler + GITHUB_HOST = "github.com"; + static MAX_REQUESTS_PER_CRAWL = 1000; + markdownRegex = new RegExp(/\.(md|mdx)$/); + octokit = new Octokit({ + auth: undefined, + }); + + static PCR_CONFIG = { + downloadPath: getContinueUtilsPath(), + }; + + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL, + ) {} + + static verifyOrInstallChromium() { + if (!fs.existsSync(getChromiumPath())) { + PCR(DocsCrawler.PCR_CONFIG); + } + } + + async *crawl(): AsyncGenerator { + if (this.startUrl.host === this.GITHUB_HOST) { + yield* this.crawlGithubRepo(); + } else { + yield* this.crawlSite(); + } + } + + private async getGithubRepoDefaultBranch( + owner: string, + repo: string, + ): Promise { + const repoInfo = await this.octokit.repos.get({ + owner, + repo, + }); + + return repoInfo.data.default_branch; + } + + private async getGitHubRepoPaths( + owner: string, + repo: string, + branch: string, + ) { + const tree = await this.octokit.request( + "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", + { + owner, + repo, + tree_sha: branch, + headers: { + "X-GitHub-Api-Version": "2022-11-28", + }, + recursive: "true", + }, + ); + + const paths = tree.data.tree + .filter( + (file: any) => + file.type === "blob" && this.markdownRegex.test(file.path ?? ""), + ) + .map((file: any) => file.path); + + return paths; + } + + private async getGithubRepoFileContent( + path: string, + owner: string, + repo: string, + ) { + try { + const response = await this.octokit.repos.getContent({ + owner, + repo, + path, + headers: { + Accept: "application/vnd.github.raw+json", + }, + }); + + return response.data as unknown as string; + } catch (error) { + console.debug("Error fetching file contents:", error); + return null; + } + } + + private async *crawlGithubRepo() { + console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`); + + const urlStr = this.startUrl.toString(); + const [_, owner, repo] = this.startUrl.pathname.split("/"); + const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); + + for await (const path of paths) { + const content = await this.getGithubRepoFileContent(path, owner, repo); + + yield { + path, + url: urlStr, + content: content ?? "", + }; + } + } + + private stripHashFromUrl(urlStr: string) { + try { + let url = new URL(urlStr); + url.hash = ""; + return url; + } catch (err) { + return null; + } + } + + private isValidHostAndPath(newUrl: URL, curUrl: URL) { + return ( + newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host + ); + } + + private async getLinksFromPage(page: Page, curUrl: URL) { + const links = await page.$$eval("a", (links) => links.map((a) => a.href)); + + // This additional step is due to issues getting the URL module to work + // in an $$eval command + const cleanedLinks = links + .map(this.stripHashFromUrl) + .filter( + (newUrl) => + newUrl !== null && + this.isValidHostAndPath(newUrl, curUrl) && + newUrl !== curUrl, + ) + .map((newUrl) => (newUrl as URL).href); + + const dedupedLinks = Array.from(new Set(cleanedLinks)); + + return dedupedLinks; + } + + private async getLinkGroupsFromPage(page: Page, curUrl: URL) { + const links = await this.getLinksFromPage(page, curUrl); + + const groups = links.reduce((acc, link, i) => { + const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE); + + if (!acc[groupIndex]) { + acc.push([]); + } + + acc[groupIndex].push(link); + + return acc; + }, [] as string[][]); + + return groups; + } + + private async *crawlSitePages( + page: Page, + curUrl: URL, + visitedLinks: Set = new Set(), + curRequestCount: number = 0, + ): AsyncGenerator { + if (curRequestCount >= this.maxRequestsPerCrawl) { + console.warn("Max requests per crawl reached. Stopping crawler."); + return; + } + + if (visitedLinks.has(curUrl.toString())) { + return; + } + + console.debug(`Crawling page: ${curUrl.toString()}`); + + await page.goto(curUrl.toString()); + + const htmlContent = await page.content(); + const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); + const requestCount = curRequestCount + 1; + + visitedLinks.add(curUrl.toString()); + + yield { + path: curUrl.pathname, + url: curUrl.toString(), + content: htmlContent, + }; + + for (const linkGroup of linkGroups) { + for (const link of linkGroup) { + yield* this.crawlSitePages( + page, + new URL(link), + visitedLinks, + requestCount, + ); + } + } + } + + private async *crawlSite(): AsyncGenerator { + console.debug(`Crawling site repo: ${this.startUrl}`); + + const stats = await PCR(DocsCrawler.PCR_CONFIG); + + const browser = await stats.puppeteer.launch({ + args: [ + "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", + ], + executablePath: stats.executablePath, + }); + + const page = await browser.newPage(); + + try { + yield* this.crawlSitePages(page, this.startUrl); + } catch (e) { + console.debug("Error getting links: ", e); + } finally { + await browser.close(); + } + } +} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index efd679290..9b5c593e8 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,8 +1,8 @@ import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import lancedb, { Connection } from "vectordb"; -import { ConfigHandler } from "../../config/ConfigHandler.js"; -import DocsContextProvider from "../../context/providers/DocsContextProvider.js"; +import { ConfigHandler } from "../../config/ConfigHandler"; +import DocsContextProvider from "../../context/providers/DocsContextProvider"; import { Chunk, ContinueConfig, @@ -10,27 +10,27 @@ import { IDE, IndexingProgressUpdate, SiteIndexingConfig, -} from "../../index.js"; -import { FromCoreProtocol, ToCoreProtocol } from "../../protocol/index.js"; -import { GlobalContext } from "../../util/GlobalContext.js"; -import { IMessenger } from "../../util/messenger.js"; +} from "../.."; +import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { GlobalContext } from "../../util/GlobalContext"; +import { IMessenger } from "../../util/messenger"; import { editConfigJson, getDocsSqlitePath, getLanceDbPath, -} from "../../util/paths.js"; -import { Telemetry } from "../../util/posthog.js"; -import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js"; -import { Article, chunkArticle, pageToArticle } from "./article.js"; -import { crawlPage } from "./crawl.js"; -import { runLanceMigrations, runSqliteMigrations } from "./migrations.js"; +} from "../../util/paths"; +import { Telemetry } from "../../util/posthog"; +import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; +import { Article, chunkArticle, pageToArticle } from "./article"; +import DocsCrawler from "./DocsCrawler"; +import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, getS3Filename, S3Buckets, SiteIndexingResults, -} from "./preIndexed.js"; -import preIndexedDocs from "./preIndexedDocs.js"; +} from "./preIndexed"; +import preIndexedDocs from "./preIndexedDocs"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -112,8 +112,8 @@ export default class DocsService { } /* - * Currently, we generate and host embeddings for pre-indexed docs using transformers.js. - * However, we don't ship transformers.js with the JetBrains extension. + * Currently, we generate and host embeddings for pre-indexed docs using transformers. + * However, we don't ship transformers with the JetBrains extension. * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { @@ -202,11 +202,10 @@ export default class DocsService { let processedPages = 0; let maxKnownPages = 1; + const docsCrawler = new DocsCrawler(new URL(startUrl)); + // Crawl pages and retrieve info as articles - for await (const page of crawlPage( - new URL(startUrl), - siteIndexingConfig.maxDepth, - )) { + for await (const page of docsCrawler.crawl()) { processedPages++; const article = pageToArticle(page); @@ -279,6 +278,8 @@ export default class DocsService { status: "failed", }; + this.docsIndexingQueue.delete(startUrl); + return; } @@ -292,7 +293,7 @@ export default class DocsService { }; // Delete indexed docs if re-indexing - if (reIndex && await this.has(startUrl.toString())) { + if (reIndex && (await this.has(startUrl.toString()))) { console.log("Deleting old embeddings"); await this.delete(startUrl); } @@ -521,8 +522,9 @@ export default class DocsService { private async getLanceTableNameFromEmbeddingsProvider( isPreIndexedDoc: boolean, ) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); + const embeddingsProvider = await this.getEmbeddingsProvider( + isPreIndexedDoc, + ); const embeddingsProviderId = this.removeInvalidLanceTableNameChars( embeddingsProvider.id, ); diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index e972652bf..c86bdb838 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -1,8 +1,8 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; -import { Chunk } from "../../index.js"; -import { cleanFragment, cleanHeader } from "../chunk/markdown.js"; -import { PageData } from "./crawl.js"; +import { Chunk } from "../../"; +import { cleanFragment, cleanHeader } from "../chunk/markdown"; +import { type PageData } from "./DocsCrawler"; export type ArticleComponent = { title: string; @@ -148,7 +148,7 @@ export function stringToArticle( export function pageToArticle(page: PageData): Article | undefined { try { - return stringToArticle(page.url, page.html, page.path); + return stringToArticle(page.url, page.content, page.path); } catch (err) { console.error("Error converting URL to article components", err); return undefined; diff --git a/core/indexing/docs/crawl.test.ts b/core/indexing/docs/crawl.test.ts deleted file mode 100644 index cf6291894..000000000 --- a/core/indexing/docs/crawl.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { crawlPage, PageData } from "../../indexing/docs/crawl"; - -describe("crawlPage - GitHub repository", () => { - const repoUrl = new URL( - "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling", - ); - const maxDepth = 3; - let crawlResults: PageData[]; - - beforeAll(async () => { - crawlResults = []; - for await (const page of crawlPage(repoUrl, maxDepth)) { - crawlResults.push(page); - } - }, 30000); - - test("finds expected markdown files", async () => { - expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( - true, - ); - - expect( - crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), - ).toBe(true); - }); - - test("html includes the correct content", async () => { - const doc = crawlResults.find((page) => - page.path.endsWith("docs-depth-1.md"), - ); - - expect(doc?.html.includes("Test body")).toBe(true); - expect(doc?.html.includes("Test H2 Header")).toBe(true); - }); - - // This test is currently failing, `maxDepth` does not appear to be followed right now - test.todo( - "ignores files past the max depth", - // , () => { - // expect( - // crawlResults.some((page) => page.path.includes("docs-depth-3")), - // ).toBe(false); - // } - ); - - test("ignores non-markdown files, e.g. `test.js` at the root", async () => { - expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( - false, - ); - }); -}); - -async function testSite(url: string, expectedPaths: string[]) { - test(`crawlPage - ${url}`, async () => { - const crawlResults: PageData[] = []; - for await (const page of crawlPage(new URL(url))) { - crawlResults.push(page); - } - - console.log(crawlResults.map((page) => page.path)); - - // Check if all expected paths are found - for (const expectedPath of expectedPaths) { - expect( - crawlResults.some((page) => page.path.endsWith(expectedPath)), - ).toBe(true); - } - }); -} - -const SITES: { [rootUrl: string]: string[] } = { - "https://docs.continue.dev": [ - "intro", - "quickstart", - "features/tab-autocomplete", - "reference/Model%20Providers/mistral", - ], - // Failing - // "https://docs.astro.build/en/getting-started/": ["https://docs.astro.build/en/getting-started/"], - // Failing - // "https://docs.nestjs.com/": ["first-steps"], - // Taking too much time - // "https://go.dev/doc/": ["install", "tutorial/getting-started", "comment"], - // Taking too much time - // "https://clickhouse.com/docs": [ - // "intro", - // "getting-started/quick-start", - // "migrations/bigquery/migrating-to-clickhouse-cloud", - // ], - // Taking too much time - // "https://www.tensorflow.org/api_docs": ["python/tf/Variable"], - // "https://www.rust-lang.org/learn": [] - // Taking too long - // "https://docs.anthropic.com/en/docs": [ - // "welcome", - // "quickstart", - // "build-with-claude/prompt-engineering/prompt-generator", - // ], -}; - -describe.only("crawlPage should return expected subpages for common sites", () => { - for (const [rootUrl, expectedPaths] of Object.entries(SITES)) { - testSite(rootUrl, expectedPaths); - } -}); diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts deleted file mode 100644 index 838a92241..000000000 --- a/core/indexing/docs/crawl.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { Octokit } from "@octokit/rest"; -import cheerio from "cheerio"; -import fetch from "node-fetch"; -import { URL } from "node:url"; - -const IGNORE_PATHS_ENDING_IN = [ - "favicon.ico", - "robots.txt", - ".rst.txt", - "genindex", - "py-modindex", - "search.html", - "search", - "genindex.html", - "changelog", - "changelog.html", -]; - -const markdownRegex = new RegExp(/\.(md|mdx)$/); - -async function getDefaultBranch(owner: string, repo: string): Promise { - const octokit = new Octokit({ auth: undefined }); - - const repoInfo = await octokit.repos.get({ - owner, - repo, - }); - - return repoInfo.data.default_branch; -} - -async function crawlGithubRepo(baseUrl: URL) { - const octokit = new Octokit({ - auth: undefined, - }); - - const [_, owner, repo] = baseUrl.pathname.split("/"); - - const branch = await getDefaultBranch(owner, repo); - console.log("Github repo detected. Crawling", branch, "branch"); - - const tree = await octokit.request( - "GET /repos/{owner}/{repo}/git/trees/{tree_sha}", - { - owner, - repo, - tree_sha: branch, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - recursive: "true", - }, - ); - - const paths = tree.data.tree - .filter( - (file: any) => - file.type === "blob" && markdownRegex.test(file.path ?? ""), - ) - .map((file: any) => baseUrl.pathname + "/tree/main/" + file.path); - - return paths; -} - -async function getLinksFromUrl(url: string, path: string) { - const baseUrl = new URL(url); - const location = new URL(path, url); - let response; - - try { - response = await fetch(location.toString()); - } catch (error: unknown) { - if (error instanceof Error && error.message.includes("maximum redirect")) { - console.error("Maximum redirect reached for: ", location.toString()); - return { - html: "", - links: [], - }; - } - console.error(error); - return { - html: "", - links: [], - }; - } - - const html = await response.text(); - let links: string[] = []; - - if (url.includes("github.com")) { - return { - html, - links, - }; - } - - const $ = cheerio.load(html); - - $("a").each((_, element) => { - const href = $(element).attr("href"); - if (!href) { - return; - } - - const parsedUrl = new URL(href, url); - if ( - parsedUrl.hostname === baseUrl.hostname - // parsedUrl.pathname.startsWith(baseUrl.pathname) - ) { - links.push(parsedUrl.pathname); - } - }); - - links = [...new Set(links)].filter((link) => { - return ( - !link.includes("#") && - !IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending)) - ); - }); - - return { - html, - links, - }; -} - -function splitUrl(url: URL) { - const baseUrl = `${url.protocol}//${url.hostname}${ - url.port ? ":" + url.port : "" - }`; - const basePath = url.pathname; - return { - baseUrl, - basePath, - }; -} - -export type PageData = { - url: string; - path: string; - html: string; -}; - -export async function* crawlPage( - url: URL, - maxDepth: number = 3, -): AsyncGenerator { - console.log( - `Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`, - ); - - const { baseUrl, basePath } = splitUrl(url); - let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }]; - - if (url.hostname === "github.com") { - const githubLinks = await crawlGithubRepo(url); - const githubLinkObjects = githubLinks.map((link) => ({ - path: link, - depth: 0, - })); - paths = [...paths, ...githubLinkObjects]; - } - - let index = 0; - while (index < paths.length) { - const batch = paths.slice(index, index + 50); - - try { - const promises = batch.map(({ path, depth }) => - getLinksFromUrl(baseUrl, path).then((links) => ({ - links, - path, - depth, - })), - ); // Adjust for depth tracking - - const results = await Promise.all(promises); - for (const { - links: { html, links: linksArray }, - path, - depth, - } of results) { - if (html !== "" && depth <= maxDepth) { - // Check depth - yield { - url: url.toString(), - path, - html, - }; - } - - // Ensure we only add links if within depth limit - if (depth < maxDepth) { - for (let link of linksArray) { - if (!paths.some((p) => p.path === link)) { - paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths - } - } - } - } - } catch (e) { - if (e instanceof TypeError) { - console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process - } else { - console.error("Error while crawling page: ", e); - } - } - - index += batch.length; // Proceed to next batch - } - console.log("Crawl completed"); -} diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 877002322..9da86ef85 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -1,4 +1,4 @@ -import { SiteIndexingConfig } from "../../index.js"; +import { SiteIndexingConfig } from "../../"; const preIndexedDocs: Record< SiteIndexingConfig["startUrl"], diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts index 58fa5f265..e007554e7 100644 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts @@ -20,11 +20,11 @@ async function embedOne( apiBase += "/"; } - const resp = await customFetch(new URL("api/embeddings", apiBase), { + const resp = await customFetch(new URL("api/embed", apiBase), { method: "POST", body: JSON.stringify({ model: options.model, - prompt: chunk, + input: chunk, }), headers: { "Content-Type": "application/json", @@ -36,7 +36,7 @@ async function embedOne( } const data = await resp.json(); - const embedding = data.embedding; + const embedding = data.embeddings[0]; if (!embedding || embedding.length === 0) { throw new Error("Ollama generated empty embedding"); diff --git a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts new file mode 100644 index 000000000..3972b3402 --- /dev/null +++ b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "voyage"; + + static defaultOptions: Partial | undefined = { + apiBase: "https://api.voyageai.com/v1/", + model: "voyage-code-2", + }; +} + +export default VoyageEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index acf3d81e8..acba5dbe2 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -9,6 +9,7 @@ import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js"; import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js"; +import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -27,4 +28,5 @@ export const allEmbeddingsProviders: Record< gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, deepinfra: DeepInfraEmbeddingsProvider, + voyage: VoyageEmbeddingsProvider, }; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 3404a22d5..6800a9e8a 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -226,7 +226,7 @@ async function getAddRemoveForTag( break; case AddRemoveResultType.Add: await db.run( - "INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)", + "REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)", path, cacheKey, newLastUpdatedTimestamp, diff --git a/core/indexing/types.ts b/core/indexing/types.ts index 91111dc05..3e3e287b6 100644 --- a/core/indexing/types.ts +++ b/core/indexing/types.ts @@ -5,7 +5,7 @@ export enum IndexResultType { Delete = "del", AddTag = "addTag", RemoveTag = "removeTag", - UpdateLastUpdated = "updateLastUpdated" + UpdateLastUpdated = "updateLastUpdated", } export type MarkCompleteCallback = ( diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 926b61209..35a287fd5 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -104,6 +104,9 @@ describe("BaseLLM", () => { baseLLM.apiBase = "api.groq.com"; expect(baseLLM.supportsCompletions()).toBe(false); + baseLLM.apiBase = "integrate.api.nvidia.com"; + expect(baseLLM.supportsCompletions()).toBe(false); + baseLLM.apiBase = "api.mistral.ai"; expect(baseLLM.supportsCompletions()).toBe(false); diff --git a/core/llm/index.ts b/core/llm/index.ts index 73a0151e9..b6cbb65b8 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -68,6 +68,7 @@ export abstract class BaseLLM implements ILLM { this.apiBase?.includes("api.groq.com") || this.apiBase?.includes("api.mistral.ai") || this.apiBase?.includes(":1337") || + this.apiBase?.includes("integrate.api.nvidia.com") || this._llmOptions.useLegacyCompletionsEndpoint?.valueOf() === false ) { // Jan + Groq + Mistral don't support completions : ( @@ -111,15 +112,14 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; - // For WatsonX only. - + // For IBM watsonx only. watsonxUrl?: string; - watsonxApiKey?: string; - watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth - watsonxUsername?: string; - watsonxPassword?: string; + watsonxCreds?: string; watsonxProjectId?: string; watsonxStopToken?: string; + watsonxApiVersion?: string; + + cacheSystemMessage?: boolean; private _llmOptions: LLMOptions; @@ -173,13 +173,15 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + // for watsonx only this.watsonxUrl = options.watsonxUrl; - this.watsonxApiKey = options.watsonxApiKey; + this.watsonxCreds = options.watsonxCreds; this.watsonxProjectId = options.watsonxProjectId; - this.watsonxUsername = options.watsonxUsername; - this.watsonxPassword = options.watsonxPassword; this.watsonxStopToken = options.watsonxStopToken; + this.watsonxApiVersion = options.watsonxApiVersion; + + this.cacheSystemMessage = options.cacheSystemMessage; if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 918c9338a..320dd9798 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -75,6 +75,9 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { + const shouldCacheSystemMessage = + !!this.systemMessage && !!this.cacheSystemMessage; + const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", headers: { @@ -82,11 +85,22 @@ class Anthropic extends BaseLLM { Accept: "application/json", "anthropic-version": "2023-06-01", "x-api-key": this.apiKey as string, + ...(shouldCacheSystemMessage + ? { "anthropic-beta": "prompt-caching-2024-07-31" } + : {}), }, body: JSON.stringify({ ...this._convertArgs(options), messages: this._convertMessages(messages), - system: this.systemMessage, + system: shouldCacheSystemMessage + ? [ + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : this.systemMessage, }), }); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 226671c52..415ec0f10 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,19 +14,24 @@ import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; class Bedrock extends BaseLLM { - private static PROFILE_NAME: string = "bedrock"; static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { region: "us-east-1", model: "anthropic.claude-3-sonnet-20240229-v1:0", - contextLength: 200_000, + contextLength: 200_000 }; + profile?: string | undefined; constructor(options: LLMOptions) { super(options); if (!options.apiBase) { this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } } protected async *_streamComplete( @@ -124,11 +129,11 @@ class Bedrock extends BaseLLM { private async _getCredentials() { try { return await fromIni({ - profile: Bedrock.PROFILE_NAME, + profile: this.profile, })(); } catch (e) { console.warn( - `AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`, + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, ); return await fromIni()(); } diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts new file mode 100644 index 000000000..f53d4b15e --- /dev/null +++ b/core/llm/llms/BedrockImport.ts @@ -0,0 +1,96 @@ +import { + BedrockRuntimeClient, + InvokeModelWithResponseStreamCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { BaseLLM } from "../index.js"; + +class BedrockImport extends BaseLLM { + static providerName: ModelProvider = "bedrockimport"; + static defaultOptions: Partial = { + region: "us-east-1" + }; + // the BedRock imported custom model ARN + modelArn?: string | undefined; + profile?: string | undefined; + + constructor(options: LLMOptions) { + super(options); + if (!options.apiBase) { + this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`; + } + if (options.modelArn) { + this.modelArn = options.modelArn; + } + if (options.profile) { + this.profile = options.profile; + } else { + this.profile = "bedrock"; + } + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, + }); + + const input = this._generateInvokeModelCommandInput(prompt, options); + const command = new InvokeModelWithResponseStreamCommand(input); + const response = await client.send(command); + + if (response.body) { + for await (const item of response.body) { + const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes)); + if (chunk.outputs[0].text) { + yield chunk.outputs[0].text; + } + } + } + } + + private _generateInvokeModelCommandInput( + prompt: string, + options: CompletionOptions, + ): any { + const payload = { + prompt: prompt + }; + + return { + body: JSON.stringify(payload), + modelId: this.modelArn, + accept: "application/json", + contentType: "application/json" + }; + } + + private async _getCredentials() { + try { + return await + fromIni({ + profile: this.profile + })(); + } catch (e) { + console.warn( + `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} + +export default BedrockImport; diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts new file mode 100644 index 000000000..855e386de --- /dev/null +++ b/core/llm/llms/Kindo.ts @@ -0,0 +1,16 @@ +import { LLMOptions, ModelProvider } from "../.."; +import OpenAI from "./OpenAI"; + +class Kindo extends OpenAI { + static providerName: ModelProvider = "kindo"; + static defaultOptions: Partial = { + apiBase: "https://llm.kindo.ai/v1", + requestOptions: { + headers: { + "kindo-token-transaction-type": "CONTINUE" + } + } + }; +} + +export default Kindo; \ No newline at end of file diff --git a/core/llm/llms/Nvidia.ts b/core/llm/llms/Nvidia.ts new file mode 100644 index 000000000..ccfd1d19e --- /dev/null +++ b/core/llm/llms/Nvidia.ts @@ -0,0 +1,33 @@ +import { LLMOptions, ModelProvider, ChatMessage } from "../../index.js"; +import OpenAI from "./OpenAI.js"; + +class Nvidia extends OpenAI { + // NVIDIA NIMs currently limits the number of stops for Starcoder 2 to 4 + // https://docs.api.nvidia.com/nim/reference/bigcode-starcoder2-7b-infer + protected maxStopWordsStarCoder = 4; + static providerName: ModelProvider = "nvidia"; + static defaultOptions: Partial = { + apiBase: "https://integrate.api.nvidia.com/v1/", + useLegacyCompletionsEndpoint: false, + }; + + protected _convertArgs(options: any, messages: ChatMessage[]) { + const url = new URL(this.apiBase!); + const finalOptions = { + messages: messages.map(this._convertMessage), + model: this._convertModelName(options.model), + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.model.includes("starcoder2") + ? options.stop?.slice(0, this.maxStopWordsStarCoder) + : options.stop, + }; + + return finalOptions; + } +} + +export default Nvidia; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 5a18ab932..68dfef47c 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -6,6 +6,7 @@ import { } from "../../index.js"; import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +import { streamResponse } from "../stream.js"; const watsonxConfig = { accessToken: { expiration: 0, @@ -19,14 +20,14 @@ class WatsonX extends BaseLLM { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { + if ( - this.watsonxUrl !== null && - this.watsonxUrl!.includes("cloud.ibm.com") + this.watsonxUrl?.includes("cloud.ibm.com") ) { // watsonx SaaS const wxToken = await ( await fetch( - `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxApiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, { method: "POST", headers: { @@ -43,17 +44,16 @@ class WatsonX extends BaseLLM { } else { // watsonx Software if ( - this.watsonxZenApiKeyBase64 && - this.watsonxZenApiKeyBase64 !== "YOUR_WATSONX_ZENAPIKEY" + !this.watsonxCreds?.includes(":") ) { - // Using ZenApiKey auth - return { - token: this.watsonxZenApiKeyBase64, - expiration: -1, - }; + // Using ZenApiKey auth + return { + token: this.watsonxCreds ?? "", + expiration: -1, + }; } else { // Using username/password auth - + const userPass = this.watsonxCreds?.split(":"); const wxToken = await ( await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { method: "POST", @@ -62,8 +62,8 @@ class WatsonX extends BaseLLM { Accept: "application/json", }, body: JSON.stringify({ - username: this.watsonxUsername, - password: this.watsonxPassword, + username: userPass[0], + password: userPass[1], }), }) ).json(); @@ -185,9 +185,9 @@ class WatsonX extends BaseLLM { const stopToken = this.watsonxStopToken ?? - (options.model.includes("granite") ? "<|im_end|>" : undefined); - var streamResponse = await fetch( - `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, + (options.model?.includes("granite") ? "<|im_end|>" : undefined); + var response = await this.fetch( + `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`, { method: "POST", headers: { @@ -207,30 +207,22 @@ class WatsonX extends BaseLLM { repetition_penalty: 1, }, model_id: options.model, - project_id: this.watsonxProjectId, + project_id: this.watsonxProjectId }), }, ); - if (!streamResponse.ok || streamResponse.body === null) { + if (!response.ok || response.body === null) { throw new Error( "Something went wrong. No response received, check your connection", ); } else { - const reader = streamResponse.body.getReader(); - while (true) { - const chunk = await reader.read(); - if (chunk.done) { - break; - } - - // Decode the stream - const textResponseMsg = new TextDecoder().decode(chunk.value); - const lines = textResponseMsg.split(/\r?\n/); + for await (const value of streamResponse(response)) { + const lines = value.split("\n"); let generatedChunk = ""; let generatedTextIndex = undefined; - lines.forEach((el) => { + lines.forEach((el: string) => { // console.log(`${el}`); if (el.startsWith("id:")) { generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 56ff2dff4..a311b6527 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -11,6 +11,7 @@ import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Azure from "./Azure"; import Bedrock from "./Bedrock"; +import BedrockImport from "./BedrockImport"; import Cloudflare from "./Cloudflare"; import Cohere from "./Cohere"; import DeepInfra from "./DeepInfra"; @@ -22,6 +23,7 @@ import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; +import Kindo from "./Kindo"; import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; @@ -36,6 +38,7 @@ import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; import WatsonX from "./WatsonX"; import ContinueProxy from "./stubs/ContinueProxy"; +import Nvidia from "./Nvidia"; const LLMs = [ Anthropic, @@ -49,11 +52,13 @@ const LLMs = [ Together, HuggingFaceTGI, HuggingFaceInferenceAPI, + Kindo, LlamaCpp, OpenAI, LMStudio, Mistral, Bedrock, + BedrockImport, SageMaker, DeepInfra, Flowise, @@ -66,6 +71,7 @@ const LLMs = [ Azure, WatsonX, OpenRouter, + Nvidia, ]; export async function llmFromDescription( diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index 00a05ac72..9be515993 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -25,9 +25,11 @@ const gptEditPrompt: PromptTemplate = (_, otherData) => { ${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix} \`\`\` -Given the user's request: "${otherData.userInput}" +Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request: -Here is the code that should fill in the [BLANK]:`; +"${otherData.userInput}" + +Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`; } const paragraphs = [ @@ -74,7 +76,7 @@ const osModelsEditPrompt: PromptTemplate = (history, otherData) => { !firstCharOfFirstLine; const suffixTag = isSuffix ? "" : ""; const suffixExplanation = isSuffix - ? " When you get to \"\", end your response." + ? ' When you get to "", end your response.' : ""; // If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth diff --git a/core/package-lock.json b/core/package-lock.json index 0278bfb9c..6c03c4862 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -22,7 +22,6 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", @@ -47,6 +46,8 @@ "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -1226,7 +1227,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", - "dev": true, "dependencies": { "@babel/highlight": "^7.24.7", "picocolors": "^1.0.0" @@ -1610,7 +1610,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", - "dev": true, "engines": { "node": ">=6.9.0" } @@ -1657,7 +1656,6 @@ "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", - "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.24.7", "chalk": "^2.4.2", @@ -1672,7 +1670,6 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -1684,7 +1681,6 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -1698,7 +1694,6 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, "dependencies": { "color-name": "1.1.3" } @@ -1706,14 +1701,12 @@ "node_modules/@babel/highlight/node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" }, "node_modules/@babel/highlight/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, "engines": { "node": ">=0.8.0" } @@ -1722,7 +1715,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, "engines": { "node": ">=4" } @@ -1731,7 +1723,6 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -4067,6 +4058,27 @@ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" }, + "node_modules/@puppeteer/browsers": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.3.0.tgz", + "integrity": "sha512-ioXoq9gPxkss4MYhD+SFaU9p1IHFUX0ILAWFPyjGaBdjLsYAlZw6j1iLA0N/m12uVHLFDfSYNF7EQccjinIMDA==", + "dependencies": { + "debug": "^4.3.5", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.4.0", + "semver": "^7.6.3", + "tar-fs": "^3.0.6", + "unbzip2-stream": "^1.4.3", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -4679,6 +4691,11 @@ "node": ">= 6" } }, + "node_modules/@tootallnate/quickjs-emscripten": { + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", + "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -5004,6 +5021,15 @@ "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", "dev": true }, + "node_modules/@types/yauzl": { + "version": "2.10.3", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", + "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", + "optional": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "7.10.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.10.0.tgz", @@ -5413,8 +5439,7 @@ "node_modules/aproba": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", - "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", - "optional": true + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" }, "node_modules/are-we-there-yet": { "version": "3.0.1", @@ -5595,6 +5620,17 @@ "node": ">=0.8" } }, + "node_modules/ast-types": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", + "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/async-mutex": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz", @@ -5879,6 +5915,14 @@ } ] }, + "node_modules/basic-ftp": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", + "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -6052,6 +6096,14 @@ "ieee754": "^1.2.1" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "engines": { + "node": "*" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -6204,42 +6256,6 @@ "node": ">=10" } }, - "node_modules/cheerio": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz", - "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==", - "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" - }, - "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" - } - }, - "node_modules/cheerio-select": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", - "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", - "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, "node_modules/chownr": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", @@ -6248,6 +6264,19 @@ "node": ">=10" } }, + "node_modules/chromium-bidi": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.6.3.tgz", + "integrity": "sha512-qXlsCmpCZJAnoTYI83Iu6EdYQpMYdVkCfq08KDh2pmlVqK5t5IA9mGs4/LwCwp4fqisSOMXZxP3HIh8w8aRn0A==", + "dependencies": { + "mitt": "3.0.1", + "urlpattern-polyfill": "10.0.0", + "zod": "3.23.8" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, "node_modules/ci-info": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", @@ -6282,7 +6311,6 @@ "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", @@ -6349,7 +6377,6 @@ "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", - "optional": true, "bin": { "color-support": "bin.js" } @@ -6454,8 +6481,7 @@ "node_modules/console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", - "optional": true + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" }, "node_modules/convert-source-map": { "version": "2.0.0", @@ -6481,6 +6507,31 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" }, + "node_modules/cosmiconfig": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", + "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/create-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", @@ -6666,9 +6717,9 @@ } }, "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.6.tgz", + "integrity": "sha512-O/09Bd4Z1fBrU4VzkhFqVgpPzaGbw6Sm9FEkBT1A/YBXQFGuuSxa1dN2nxgxS34JmKXqYx8CZAwEVoJFImUXIg==", "dependencies": { "ms": "2.1.2" }, @@ -6768,6 +6819,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/degenerator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", + "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -6812,6 +6876,11 @@ "node": ">=8" } }, + "node_modules/devtools-protocol": { + "version": "0.0.1312386", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", + "integrity": "sha512-DPnhUXvmvKT2dFA/j7B+riVLUt9Q6RKJlcppojL5CoRywJJKLDYnRlw0gTFKfgDPHP5E04UoB71SxoJlVZy8FA==" + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -6932,6 +7001,11 @@ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" }, + "node_modules/eight-colors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/eight-colors/-/eight-colors-1.3.0.tgz", + "integrity": "sha512-hVoK898cR71ADj7L1LZWaECLaSkzzPtqGXIaKv4K6Pzb72QgjLVsQaNI+ELDQQshzFvgp5xTPkaYkPGqw3YR+g==" + }, "node_modules/electron-to-chromium": { "version": "1.4.776", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.776.tgz", @@ -6953,8 +7027,7 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "devOptional": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/encoding": { "version": "0.1.13", @@ -7028,7 +7101,6 @@ "version": "2.2.1", "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", - "optional": true, "engines": { "node": ">=6" } @@ -7043,7 +7115,6 @@ "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, "dependencies": { "is-arrayish": "^0.2.1" } @@ -7215,7 +7286,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", - "dev": true, "engines": { "node": ">=6" } @@ -7235,7 +7305,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", - "dev": true, "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", @@ -7652,6 +7721,39 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, + "node_modules/extract-zip": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", + "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", + "dependencies": { + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + }, + "bin": { + "extract-zip": "cli.js" + }, + "engines": { + "node": ">= 10.17.0" + }, + "optionalDependencies": { + "@types/yauzl": "^2.9.1" + } + }, + "node_modules/extract-zip/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -7752,6 +7854,14 @@ "bser": "2.1.1" } }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -7941,6 +8051,27 @@ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" }, + "node_modules/fs-extra": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", + "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/fs-extra/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", @@ -8045,7 +8176,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, "engines": { "node": "6.* || 8.* || >= 10.*" } @@ -8105,6 +8235,28 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-uri": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", + "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4", + "fs-extra": "^11.2.0" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/get-uri/node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", + "engines": { + "node": ">= 14" + } + }, "node_modules/getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", @@ -8422,8 +8574,7 @@ "node_modules/has-unicode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", - "optional": true + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" }, "node_modules/hasown": { "version": "2.0.2", @@ -8461,24 +8612,6 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, - "node_modules/htmlparser2": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", - "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "node_modules/http-cache-semantics": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", @@ -8671,7 +8804,6 @@ "version": "9.0.5", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", - "optional": true, "dependencies": { "jsbn": "1.1.0", "sprintf-js": "^1.1.3" @@ -8698,8 +8830,7 @@ "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" }, "node_modules/is-bigint": { "version": "1.0.4", @@ -8794,7 +8925,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "devOptional": true, "engines": { "node": ">=8" } @@ -9953,8 +10083,7 @@ "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "node_modules/js-yaml": { "version": "4.1.0", @@ -9970,8 +10099,7 @@ "node_modules/jsbn": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", - "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", - "optional": true + "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==" }, "node_modules/jsdom": { "version": "24.1.1", @@ -10046,8 +10174,7 @@ "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" }, "node_modules/json-schema": { "version": "0.4.0", @@ -10081,6 +10208,25 @@ "node": ">=6" } }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonfile/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/jsprim": { "version": "1.4.2", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", @@ -10180,8 +10326,7 @@ "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" }, "node_modules/llm-code-highlighter": { "version": "0.0.14", @@ -10596,6 +10741,11 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==" + }, "node_modules/mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", @@ -10703,6 +10853,14 @@ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==" }, + "node_modules/netmask": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", + "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/node-abi": { "version": "3.62.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.62.0.tgz", @@ -11255,6 +11413,49 @@ "node": ">=6" } }, + "node_modules/pac-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.0.2.tgz", + "integrity": "sha512-BFi3vZnO9X5Qt6NRz7ZOaPja3ic0PhlsmCRYLOpN11+mWBCR6XJDqW5RF3j8jm4WGGQZtBA+bTfxYzeKW73eHg==", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.5", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-proxy-agent/node_modules/socks-proxy-agent": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", + "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", + "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/pad-left": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", @@ -11282,7 +11483,6 @@ "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -11307,18 +11507,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz", - "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==", - "dependencies": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -11356,6 +11544,11 @@ "node": ">=8" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==" + }, "node_modules/performance-now": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", @@ -11454,8 +11647,7 @@ "node_modules/picocolors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "dev": true + "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==" }, "node_modules/picomatch": { "version": "2.3.1", @@ -11728,6 +11920,14 @@ "node": ">= 0.6.0" } }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/promise-inflight": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", @@ -11790,6 +11990,45 @@ "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" }, + "node_modules/proxy-agent": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz", + "integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.0.1", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/proxy-agent/node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/proxy-agent/node_modules/socks-proxy-agent": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.4.tgz", + "integrity": "sha512-GNAq/eg8Udq2x0eNiFkr9gRg5bA7PXEWagQdeRX4cPSG+X/8V38v637gim9bjFptMk1QWsCTr0ttrJEiXbNnRw==", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", @@ -11817,6 +12056,131 @@ "node": ">=6" } }, + "node_modules/puppeteer": { + "version": "22.15.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-22.15.0.tgz", + "integrity": "sha512-XjCY1SiSEi1T7iSYuxS82ft85kwDJUS7wj1Z0eGVXKdtr5g4xnVcbjwxhq5xBnpK/E7x1VZZoJDxpjAOasHT4Q==", + "hasInstallScript": true, + "dependencies": { + "@puppeteer/browsers": "2.3.0", + "cosmiconfig": "^9.0.0", + "devtools-protocol": "0.0.1312386", + "puppeteer-core": "22.15.0" + }, + "bin": { + "puppeteer": "lib/esm/puppeteer/node/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver": { + "version": "23.0.0", + "resolved": "https://registry.npmjs.org/puppeteer-chromium-resolver/-/puppeteer-chromium-resolver-23.0.0.tgz", + "integrity": "sha512-PbSXK4ERPwp+eYm+SVY5vMWCxsdeJcddwz4avXvDx7kE9DLE+L86Xg027sypw2oan5yi6557brzVsbajcMmy2g==", + "hasInstallScript": true, + "dependencies": { + "@puppeteer/browsers": "^2.3.1", + "eight-colors": "^1.3.0", + "gauge": "^5.0.2", + "puppeteer-core": "^23.1.0" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/@puppeteer/browsers": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.3.1.tgz", + "integrity": "sha512-uK7o3hHkK+naEobMSJ+2ySYyXtQkBxIH8Gn4MK9ciePjNV+Pf+PgY/W7iPzn2MTjl3stcYB5AlcTmPYw7AXDwA==", + "dependencies": { + "debug": "^4.3.6", + "extract-zip": "^2.0.1", + "progress": "^2.0.3", + "proxy-agent": "^6.4.0", + "semver": "^7.6.3", + "tar-fs": "^3.0.6", + "unbzip2-stream": "^1.4.3", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/chromium-bidi": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.6.4.tgz", + "integrity": "sha512-8zoq6ogmhQQkAKZVKO2ObFTl4uOkqoX1PlKQX3hZQ5E9cbUotcAb7h4pTNVAGGv8Z36PF3CtdOriEp/Rz82JqQ==", + "dependencies": { + "mitt": "3.0.1", + "urlpattern-polyfill": "10.0.0", + "zod": "3.23.8" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/gauge": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-5.0.2.tgz", + "integrity": "sha512-pMaFftXPtiGIHCJHdcUUx9Rby/rFT/Kkt3fIIGCs+9PMDIljSyRiqraTlxNtBReJRDfUefpa263RQ3vnp5G/LQ==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.3", + "console-control-strings": "^1.1.0", + "has-unicode": "^2.0.1", + "signal-exit": "^4.0.1", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/puppeteer-core": { + "version": "23.1.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-23.1.1.tgz", + "integrity": "sha512-OeTqNiYGF9qZtwZU4Yc88DDqFJs4TJ4rnK81jkillh6MwDeQodyisM9xe5lBmPhwiDy92s5J5DQtQLjCKHFQ3g==", + "dependencies": { + "@puppeteer/browsers": "2.3.1", + "chromium-bidi": "0.6.4", + "debug": "^4.3.6", + "devtools-protocol": "0.0.1312386", + "typed-query-selector": "^2.12.0", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/puppeteer-chromium-resolver/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/puppeteer-core": { + "version": "22.15.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-22.15.0.tgz", + "integrity": "sha512-cHArnywCiAAVXa3t4GGL2vttNxh7GqXtIYGym99egkNJ3oG//wL9LkvO4WE8W1TJe95t1F1ocu9X4xWaGsOKOA==", + "dependencies": { + "@puppeteer/browsers": "2.3.0", + "chromium-bidi": "0.6.3", + "debug": "^4.3.6", + "devtools-protocol": "0.0.1312386", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/pure-rand": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", @@ -12104,7 +12468,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -12301,9 +12664,9 @@ } }, "node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "bin": { "semver": "bin/semver.js" }, @@ -12498,7 +12861,6 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "optional": true, "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" @@ -12534,7 +12896,6 @@ "version": "2.8.3", "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz", "integrity": "sha512-l5x7VUUWbjVFbafGLxPWkYsHIhEvmF85tbIeFZWc8ZPtoMyybuEhL7Jye/ooC4/d48FgOjSJXgsF/AJPYCW8Zw==", - "optional": true, "dependencies": { "ip-address": "^9.0.5", "smart-buffer": "^4.2.0" @@ -12610,8 +12971,7 @@ "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", - "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", - "optional": true + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==" }, "node_modules/sqlite": { "version": "5.1.1", @@ -12765,7 +13125,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "devOptional": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -13304,6 +13663,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/typed-query-selector": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.0.tgz", + "integrity": "sha512-SbklCd1F0EiZOyPiW192rrHZzZ5sBijB6xM+cpmrwDqObvdtunOHHIk9fCGsoK5JVIYXoyEp4iEdE3upFH3PAg==" + }, "node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -13352,6 +13716,38 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/unbzip2-stream": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", + "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", + "dependencies": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "node_modules/unbzip2-stream/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "node_modules/undici": { "version": "6.18.2", "resolved": "https://registry.npmjs.org/undici/-/undici-6.18.2.tgz", @@ -13483,6 +13879,11 @@ "requires-port": "^1.0.0" } }, + "node_modules/urlpattern-polyfill": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.0.0.tgz", + "integrity": "sha512-H/A06tKD7sS1O1X2SshBVeA5FLycRpjqiBeqGKmBwBDBy28EnRjORxTNe269KSSr5un5qyWi1iL61wLxpd+ZOg==" + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -13684,7 +14085,6 @@ "version": "1.1.5", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", - "optional": true, "dependencies": { "string-width": "^1.0.2 || 2 || 3 || 4" } @@ -13743,7 +14143,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -13827,7 +14226,6 @@ "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, "engines": { "node": ">=10" } @@ -13853,7 +14251,6 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", @@ -13871,11 +14268,19 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, "engines": { "node": ">=12" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, "node_modules/yocto-queue": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.1.1.tgz", diff --git a/core/package.json b/core/package.json index 5e4e2652d..4b20b5b2c 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", "lint:fix": "eslint . --ext ts --fix" @@ -51,7 +51,6 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", @@ -76,6 +75,8 @@ "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -92,9 +93,6 @@ "yaml": "^2.4.2", "zod": "^3.23.8" }, - "puppeteer": { - "chromium_revision": "119.0.6045.105" - }, "engine-strict": true, "engines": { "node": ">=20.11.0" diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 918ba6e66..9cd4d4ec8 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -128,6 +128,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { undefined, { model: string; promptTokens: number; generatedTokens: number }[], ]; + "tts/kill": [undefined, void]; "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dir?: string; shouldClearIndexes?: boolean }, diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 2fa70bf73..5e1e74589 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -31,6 +31,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; + setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 5fe14573a..1e2499ca7 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -30,6 +30,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "autocomplete/cancel", "autocomplete/accept", "command/run", + "tts/kill", "llm/complete", "llm/streamComplete", "llm/streamChat", @@ -57,4 +58,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "refreshSubmenuItems", "isContinueInputFocused", "didChangeAvailableProfiles", + "setTTSActive", ]; diff --git a/core/protocol/util.ts b/core/protocol/util.ts new file mode 100644 index 000000000..c9fe3af1b --- /dev/null +++ b/core/protocol/util.ts @@ -0,0 +1,17 @@ +import { FromWebviewProtocol } from "."; + +interface ErrorWebviewMessengerResult { + done: boolean; + status: "error"; + error: string; +} + +interface SuccessWebviewMessengerResult { + done: boolean; + status: "success"; + content: FromWebviewProtocol[T][1]; +} + +export type WebviewMessengerResult = + | ErrorWebviewMessengerResult + | SuccessWebviewMessengerResult; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 061f2819d..d3b127fdc 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -13,4 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + setTTSActive: [boolean, void]; }; diff --git a/core/test/util/history.test.ts b/core/test/util/history.test.ts new file mode 100644 index 000000000..d3dedac7f --- /dev/null +++ b/core/test/util/history.test.ts @@ -0,0 +1,131 @@ +import { PersistedSessionInfo } from "../.."; +import historyManager from "../../util/history"; +import { getSessionFilePath } from "../../util/paths"; +import { v4 as uuidv4 } from "uuid"; + +const sessionId = uuidv4(); +const testSession: PersistedSessionInfo = { + history: [], + title: `${sessionId} title`, + workspaceDirectory: "workspaceDir", + sessionId: sessionId, +}; + +describe("No sessions have been created", () => { + const testSessionId = "invalid"; + const testSessionPath = getSessionFilePath(testSessionId); + + test("Listing all sessions returns empty list", () => { + const sessions = historyManager.list({}); + expect(sessions).toEqual([]); + }); + + test("Deleting session throws error", () => { + expect(() => { + historyManager.delete(testSessionId); + }).toThrow(`Session file ${testSessionPath} does not exist`); + }); + + test("Loading session returns default session", () => { + const session = historyManager.load(testSessionId); + expect(session).toEqual({ + history: [], + title: "Failed to load session", + workspaceDirectory: "", + sessionId: testSessionId, + }); + }); +}); + +describe("Full session lifecycle", () => { + test("Creating and listing a session", () => { + // save and list + historyManager.save(testSession); + const sessions = historyManager.list({}); + const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId); + expect(sessionExists).toBe(true); + }); + + test("Loading session by ID returns correct object", () => { + const retrievedSession = historyManager.load(testSession.sessionId); + expect(retrievedSession).toEqual(testSession); + }); + + test("Saving session with new title updates session", () => { + const modifiedSession = { ...testSession }; + modifiedSession.title = `Edited: ${testSession.title}`; + historyManager.save(modifiedSession); + const session = historyManager.load(testSession.sessionId); + + expect(session.title).toBe(modifiedSession.title); + }); + + test("Deleting session", () => { + historyManager.delete(testSession.sessionId); + const sessions = historyManager.list({}); + const sessionWasDeleted = sessions.every( + (session) => session?.sessionId !== testSession.sessionId, + ); + expect(sessionWasDeleted).toEqual(true); + }); +}); + +describe("Many sessions created", () => { + test("Create 100 sessions and list all", () => { + for (let i = 0; i < 100; i++) { + historyManager.save({ + history: [], + title: `${i}`, + workspaceDirectory: "workspaceDir", + sessionId: `${i}`, + }); + } + const sessions = historyManager.list({}); + expect(sessions.length).toBe(100); + }); + + test("List 10 sessions, offest by 10", () => { + const limit = 10; + const offset = 10; + + const sessions = historyManager.list({ offset: offset, limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString()); + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List 25 sessions, with no offset", () => { + const limit = 25; + + const sessions = historyManager.list({ limit: limit }); + const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("List sessions offset by 75", () => { + const offset = 75; + + const sessions = historyManager.list({ offset: offset }); + const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) => + (i + offset).toString(), + ); + + const isSessionIdInList = (sessionId: string) => + sessions.some((session) => session.sessionId === sessionId); + expect(sessionIds.every(isSessionIdInList)).toBe(true); + }); + + test("Delete all sessions", () => { + let sessions = historyManager.list({}); + + for (let session of sessions) { + historyManager.delete(session.sessionId); + } + sessions = historyManager.list({}); + expect(sessions.length).toBe(0); + }); +}); diff --git a/core/util/paths.ts b/core/util/paths.ts index 7a6ed8831..28216d8af 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -8,9 +8,22 @@ import Types from "../config/types.js"; import { IdeType, SerializedContinueConfig } from "../index.js"; dotenv.config(); + const CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue"); +export function getChromiumPath(): string { + return path.join(getContinueUtilsPath(), ".chromium-browser-snapshots"); +} + +export function getContinueUtilsPath(): string { + const utilsPath = path.join(getContinueGlobalPath(), ".utils"); + if (!fs.existsSync(utilsPath)) { + fs.mkdirSync(utilsPath); + } + return utilsPath; +} + export function getContinueGlobalPath(): string { // This is ~/.continue on mac/linux const continuePath = CONTINUE_GLOBAL_DIR; @@ -328,3 +341,7 @@ export function readAllGlobalPromptFiles( return promptFiles; } + +export function getRepoMapFilePath(): string { + return path.join(getContinueUtilsPath(), "repo_map.txt"); +} diff --git a/core/util/posthog.ts b/core/util/posthog.ts index be62977fc..e0b5e4898 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -14,20 +14,24 @@ export class Telemetry { properties: { [key: string]: any }, sendToTeam: boolean = false, ) { - Telemetry.client?.capture({ - distinctId: Telemetry.uniqueId, - event, - properties: { - ...properties, - os: Telemetry.os, - extensionVersion: Telemetry.ideInfo?.extensionVersion, - ideName: Telemetry.ideInfo?.name, - ideType: Telemetry.ideInfo?.ideType, - }, - }); + try { + Telemetry.client?.capture({ + distinctId: Telemetry.uniqueId, + event, + properties: { + ...properties, + os: Telemetry.os, + extensionVersion: Telemetry.ideInfo?.extensionVersion, + ideName: Telemetry.ideInfo?.name, + ideType: Telemetry.ideInfo?.ideType, + }, + }); - if (sendToTeam) { - TeamAnalytics.capture(event, properties); + if (sendToTeam) { + TeamAnalytics.capture(event, properties); + } + } catch (e) { + console.error(`Failed to capture event: ${e}`); } } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index f4ab86c60..204e2e3df 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -35,7 +35,7 @@ export const supportedLanguages: { [key: string]: string } = { mts: "typescript", cts: "typescript", tsx: "tsx", - vue: "vue", + // vue: "vue", // tree-sitter-vue parser is broken // The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part // yaml: "yaml", // yml: "yaml", diff --git a/core/util/tts.ts b/core/util/tts.ts new file mode 100644 index 000000000..248c38518 --- /dev/null +++ b/core/util/tts.ts @@ -0,0 +1,117 @@ +import os from "node:os"; +import { exec, ChildProcess } from "child_process"; +import type { IMessenger } from "./messenger"; +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; + +// The amount of time before a process is declared +// a zombie after executing .kill() +const ttsKillTimeout: number = 5000; + +/** + * Removes code blocks from a message. + * + * Return modified message text. + */ +function removeCodeBlocks(msgText: string): string { + const codeBlockRegex = /```[\s\S]*?```/g; + + // Remove code blocks from the message text + const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); + + return textWithoutCodeBlocks.trim(); +} + +/** + * Cleans a message text to safely be used in 'exec' context on host. + * + * Return modified message text. + */ +function sanitizeMessageForTTS(message: string): string { + message = removeCodeBlocks(message); + + // Remove or replace problematic characters + message = message + .replace(/"/g, "") + .replace(/`/g, "") + .replace(/\$/g, "") + .replace(/\\/g, "") + .replace(/[&|;()<>]/g, ""); + + message = message.trim().replace(/\s+/g, " "); + + return message; +} + +export class TTS { + static os: string | undefined = undefined; + static handle: ChildProcess | undefined = undefined; + static messenger: IMessenger; + + static async read(message: string) { + message = sanitizeMessageForTTS(message); + + try { + // Kill any active TTS processes + await TTS.kill(); + } catch (e) { + console.warn("Error killing TTS process: ", e); + return; + } + + switch (TTS.os) { + case "darwin": + TTS.handle = exec(`say "${message}"`); + break; + case "win32": + // Replace single quotes on windows + TTS.handle = exec( + `powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${message.replace( + /'/g, + "''", + )}')"`, + ); + break; + case "linux": + TTS.handle = exec(`espeak "${message}"`); + break; + default: + console.log( + "Text-to-speech is not supported on this operating system.", + ); + return; + } + + TTS.messenger.request("setTTSActive", true); + + TTS.handle?.once("exit", () => { + TTS.messenger.request("setTTSActive", false); + }); + } + + static async kill(): Promise { + return new Promise((resolve, reject) => { + // Only kill a TTS process if it's still running + if (TTS.handle && TTS.handle.exitCode === null) { + // Use a timeout in case of zombie processes + let killTimeout: NodeJS.Timeout = setTimeout(() => { + reject(`Unable to kill TTS process: ${TTS.handle?.pid}`); + }, ttsKillTimeout); + + // Resolve our promise once the program has exited + TTS.handle.once("exit", () => { + clearTimeout(killTimeout); + TTS.handle = undefined; + resolve(); + }); + + TTS.handle.kill(); + } else { + resolve(); + } + }); + } + + static async setup() { + TTS.os = os.platform(); + } +} diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index 610e272a9..7dfe6190c 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -301,6 +301,18 @@ Type `@locals` to reference the contents of the local variables with top n level } ``` +### Repository map + +Provides an overview of all files and the call signatures of top-level classes, functions, and methods. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). + +```json +{ + "name": "repo-map" +} +``` + ### Operating System Type `@os` to reference the architecture and platform of your current operating system. diff --git a/docs/docs/features/prompt-files.md b/docs/docs/features/prompt-files.md index 89063c8c9..4fb8abfce 100644 --- a/docs/docs/features/prompt-files.md +++ b/docs/docs/features/prompt-files.md @@ -5,7 +5,7 @@ Prompt files provide a convenient way to standardize common patterns and share a ## Quick start :::tip[Prompt library] -To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-example). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts! +To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-examples). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts! ::: Below is a quick example of setting up a prompt file to write unit tests using Jest. diff --git a/docs/docs/reference/Model Providers/anthropicllm.md b/docs/docs/reference/Model Providers/anthropicllm.md index 309f29ab2..a29bf34a9 100644 --- a/docs/docs/reference/Model Providers/anthropicllm.md +++ b/docs/docs/reference/Model Providers/anthropicllm.md @@ -16,3 +16,24 @@ To setup Anthropic, obtain an API key from [here](https://www.anthropic.com/api) ``` [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Anthropic.ts) + +## Prompt caching + +Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). + +Currently, we only allow caching of the system message. To enable this feature, update your your model configuration with `"cacheSystemMessage": true`: + +```json +{ + "models": [ + { + // Enable prompt caching + "cacheSystemMessage": true, + "title": "Anthropic", + "provider": "anthropic", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` diff --git a/docs/docs/reference/Model Providers/assets/Watsonx1.gif b/docs/docs/reference/Model Providers/assets/Watsonx1.gif index 4d12fd7b4..e37443ad6 100644 Binary files a/docs/docs/reference/Model Providers/assets/Watsonx1.gif and b/docs/docs/reference/Model Providers/assets/Watsonx1.gif differ diff --git a/docs/docs/reference/Model Providers/azure.md b/docs/docs/reference/Model Providers/azure.md index 0b61884c2..7ae359910 100644 --- a/docs/docs/reference/Model Providers/azure.md +++ b/docs/docs/reference/Model Providers/azure.md @@ -26,7 +26,7 @@ You can configure Azure OpenAI service through the UI, or you can configure it m ``` To find out the information from _Azure AI Studio_, select the model that you would like to connect. Under the _Endpoint_ section and capture the Target URI. -For example, Target URI of +For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview Maps to: - model = gpt-4o diff --git a/docs/docs/reference/Model Providers/bedrock.md b/docs/docs/reference/Model Providers/bedrock.md index daac562af..d720de66f 100644 --- a/docs/docs/reference/Model Providers/bedrock.md +++ b/docs/docs/reference/Model Providers/bedrock.md @@ -1,4 +1,4 @@ -# AWS Bedrock +# AWS Bedrock To setup Bedrock, add the following to your `config.json` file: @@ -9,18 +9,19 @@ To setup Bedrock, add the following to your `config.json` file: "title": "Bedrock: Claude 3 Sonnet", "provider": "bedrock", "model": "anthropic.claude-3-sonnet-20240229-v1:0", - "region": "us-east-1" + "region": "us-east-1", + "profile": "bedrock", } ] } ``` -Authentication will be through temporary or long-term credentials in -~/.aws/credentials under a profile called "bedrock". +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). ```title="~/.aws/credentials [bedrock] aws_access_key_id = abcdefg aws_secret_access_key = hijklmno -aws_session_token = pqrstuvwxyz # Optional: means short term creds. +aws_session_token = pqrstuvwxyz # Optional: means short term creds. ``` diff --git a/docs/docs/reference/Model Providers/bedrockimport.md b/docs/docs/reference/Model Providers/bedrockimport.md new file mode 100644 index 000000000..6a8c50d68 --- /dev/null +++ b/docs/docs/reference/Model Providers/bedrockimport.md @@ -0,0 +1,28 @@ +# AWS Bedrock Custom Imported Models + +To setup Bedrock using custom imported models, add the following to your `config.json` file: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] +} +``` + +Authentication will be through temporary or long-term credentials in +~/.aws/credentials under a configured profile (e.g. "bedrock"). + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/docs/reference/Model Providers/kindo.md b/docs/docs/reference/Model Providers/kindo.md new file mode 100644 index 000000000..442e30b10 --- /dev/null +++ b/docs/docs/reference/Model Providers/kindo.md @@ -0,0 +1,42 @@ +# Kindo +Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins). + +## Config Example + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "" + } + ] +} +``` + +## Tab Autocomplete Config Example + +```json title="~/.continue/config.json" +{ + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "" + }, + { + "title": "DeepSeek", + "provider": "kindo", + "model": "deepseek-ai/deepseek-coder-33b-instruct", + "apiKey": "" + } + ] +} +``` + +## Security + +To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings). \ No newline at end of file diff --git a/docs/docs/reference/Model Providers/openai.md b/docs/docs/reference/Model Providers/openai.md index 628ec8c42..f19cd392c 100644 --- a/docs/docs/reference/Model Providers/openai.md +++ b/docs/docs/reference/Model Providers/openai.md @@ -19,7 +19,7 @@ OpenAI compatible APIs - [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) - [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) -If you are [using an OpenAI compatible server / API](../../setup/select-provider#local), you can change the `apiBase` like this: +If you are [using an OpenAI compatible server / API](../../setup/model-providers.md#local), you can change the `apiBase` like this: ```json title="~/.continue/config.json" { @@ -43,5 +43,4 @@ To force usage of `chat/completions` instead of `completions` endpoint you can s [^1]: Use the [Vllm Model Provider](./vllm.md) instead. - [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/OpenAI.ts) diff --git a/docs/docs/reference/Model Providers/watsonx.md b/docs/docs/reference/Model Providers/watsonx.md index b6a239946..9e2a345d4 100644 --- a/docs/docs/reference/Model Providers/watsonx.md +++ b/docs/docs/reference/Model Providers/watsonx.md @@ -1,15 +1,38 @@ -# Watsonx +# IBM watsonx -Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. +watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. ## Setup -To access the Watsonx models, create an instance in the [IBM cloud](https://cloud.ibm.com) which supports watsonx studio. Then to create a project refer [this](https://www.ibm.com/docs/en/watsonx/saas?topic=projects-creating-project). +Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance. -You can set it up in two different ways : -1. **Using API** : Create Your IBM cloud API key by referring [this](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). -2. **Using Credentials** : Use your Username and Password to authenticate +### watsonx.ai SaaS - IBM Cloud +To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial. + +To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue: +- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region. +- Set **watsonx Project ID** to your watsonx project ID. +- Set **watsonx API Key** to your watsonx API Key. + +### watsonx.ai Software + +To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method: +1. *Option 1* (Recommended): using `ZenApiKey` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Zen API Key. To generate it: + 1. Log in to the CPD web client. + 2. From the toolbar, click your avatar. + 3. Click **Profile and settings**. + 4. Click **API key** > **Generate new key**. + 5. Click **Generate**. + 6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it. + 7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo ":" | base64`, replacing `` with your CPD username and `` with the API Key you just created. +2. *Option 2*: using `username/password` authentication: + - Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`. + - Set **watsonx Project ID** to your watsonx project ID. + - Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format. ## Usage -![usage-gif](../Model%20Providers/assets/Watsonx1.gif) \ No newline at end of file +![usage-gif](../Model%20Providers/assets/watsonx1.gif) diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index ab774d242..8cef5e77c 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -46,23 +46,28 @@ You can run a model on your local computer using: - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server) - [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU) - [Msty](../reference/Model%20Providers/msty.md) -- [Watsonx](../reference/Model%20Providers/watsonx.md) +- [IBM watsonx](../reference/Model%20Providers/watsonx.md) - [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server) ### Remote -You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-code-llm#aws), [GCP](https://github.com/continuedev/deploy-os-code-llm#gcp), [Azure](https://github.com/continuedev/deploy-os-code-llm#azure), or [other clouds](https://github.com/continuedev/deploy-os-code-llm#others-2) using: +You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-code-llm#aws), [GCP](https://github.com/continuedev/deploy-os-code-llm#gcp), [Azure](https://github.com/continuedev/deploy-os-code-llm#azure), [Lambda](https://lambdalabs.com/), or [other clouds](https://github.com/continuedev/deploy-os-code-llm#others-2) using: - [HuggingFace TGI](https://github.com/continuedev/deploy-os-code-llm#tgi) - [vLLM](https://github.com/continuedev/deploy-os-code-llm#vllm) - [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot) - [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API) +- [Lambda](https://github.com/continuedev/deploy-os-code-llm#lambda) ## SaaS +### Open-source and commercial models + You can access both open-source and commercial LLMs via: - [OpenRouter](../reference/Model%20Providers/openrouter.md) +- [Kindo](../reference/Model%20Providers/kindo.md) +- [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server) ### Open-source models @@ -76,7 +81,6 @@ You can run open-source LLMs with cloud services like: - [Deepinfra](../reference/Model%20Providers/deepinfra.md) - [Groq](../reference/Model%20Providers/openai.md) (OpenAI compatible API) - [AWS Bedrock](../reference/Model%20Providers/bedrock.md) -- [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server) ### Commercial models diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index f6611bea0..26415a624 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -190,7 +191,8 @@ "azure", "msty", "watsonx", - "openrouter" + "openrouter", + "nvidia" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -198,6 +200,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,8 +219,9 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", + "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)" ], "type": "string" }, @@ -665,6 +669,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "anyOf": [ { @@ -759,6 +766,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": [ "chat-bison-001", @@ -977,6 +987,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] } @@ -1231,13 +1244,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2018,7 +2025,8 @@ "openai", "cohere", "free-trial", - "gemini" + "gemini", + "voyage" ] }, "model": { @@ -2049,7 +2057,7 @@ "if": { "properties": { "provider": { - "enum": ["cohere"] + "enum": ["cohere", "voyage"] } }, "required": ["provider"] @@ -2402,9 +2410,17 @@ "properties": { "inlineEdit": { "type": "string" + }, + "applyCodeBlock": { + "type": "string" } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index ac38ac9fc..37586546a 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -146,6 +146,6 @@ tasks { channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) // We always hide the stable releases until a few days of EAP have proven them stable - hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) +// hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) } } diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 2d7c91f8d..d3062913b 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.62 +pluginVersion = 0.0.64 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index db7df5b54..791172388 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -2,13 +2,13 @@ package com.github.continuedev.continueintellijextension.actions import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.ToolWindowManager @@ -19,8 +19,10 @@ import javax.swing.event.DocumentListener import com.intellij.ui.components.JBScrollPane import java.awt.BorderLayout -fun pluginServiceFromActionEvent(e: AnActionEvent): ContinuePluginService? { - val project = e.project ?: return null +fun getPluginService(project: Project?): ContinuePluginService? { + if (project == null) { + return null + } return ServiceManager.getService( project, ContinuePluginService::class.java @@ -34,7 +36,7 @@ class AcceptDiffAction : AnAction() { } private fun acceptHorizontalDiff(e: AnActionEvent) { - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.ideProtocolClient?.diffManager?.acceptDiff(null) } @@ -53,7 +55,7 @@ class RejectDiffAction : AnAction() { } private fun rejectHorizontalDiff(e: AnActionEvent) { - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.ideProtocolClient?.diffManager?.rejectDiff(null) } @@ -131,7 +133,7 @@ class RejectDiffAction : AnAction() { class QuickTextEntryAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.ideProtocolClient?.sendHighlightedCode() // Create and show the dialog @@ -140,7 +142,7 @@ class QuickTextEntryAction : AnAction() { // Show the text entered by the user if (text != null) { - val service = pluginServiceFromActionEvent(e) + val service = getPluginService(e.project) service?.ideProtocolClient?.sendMainUserInput(text) val project = e.project @@ -172,27 +174,29 @@ class ViewLogsAction : AnAction() { } } +fun focusContinueInput(project: Project?) { + if (project != null) { + val toolWindowManager = ToolWindowManager.getInstance(project) + val toolWindow = toolWindowManager.getToolWindow("Continue") + if (toolWindow != null) { + if (!toolWindow.isVisible) { + toolWindow.activate(null) + } + } + } + + val continuePluginService = getPluginService(project) ?: return + continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() + continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) + + continuePluginService.ideProtocolClient?.sendHighlightedCode() +} class FocusContinueInputWithoutClearAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project - if (project != null) { - val toolWindowManager = ToolWindowManager.getInstance(project) - val toolWindow = toolWindowManager.getToolWindow("Continue") - - if (toolWindow != null) { - if (!toolWindow.isVisible) { - toolWindow.activate(null) - } - } - } - - val continuePluginService = pluginServiceFromActionEvent(e) ?: return - continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) - - continuePluginService.ideProtocolClient?.sendHighlightedCode() + focusContinueInput(project) } } @@ -210,7 +214,7 @@ class FocusContinueInputAction : AnAction() { } } - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() continuePluginService.sendToWebview("focusContinueInput", null) @@ -233,7 +237,7 @@ class NewContinueSessionAction : AnAction() { } } - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() continuePluginService.sendToWebview("focusContinueInputWithNewSession", null) @@ -248,7 +252,7 @@ class ViewHistoryAction : AnAction() { val toolWindow = toolWindowManager.getToolWindow("Continue") } - val continuePluginService = pluginServiceFromActionEvent(e) ?: return + val continuePluginService = getPluginService(e.project) ?: return continuePluginService.sendToWebview("viewHistory", null) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 079d4b8f2..5eb8d8715 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -199,51 +199,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { ) } - GlobalScope.async(Dispatchers.IO) { - val myPluginId = "com.github.continuedev.continueintellijextension" - val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) - - if (pluginDescriptor == null) { - throw Exception("Plugin not found") - } - val pluginPath = pluginDescriptor.pluginPath - val osName = System.getProperty("os.name").toLowerCase() - val os = when { - osName.contains("mac") || osName.contains("darwin") -> "darwin" - osName.contains("win") -> "win32" - osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" - else -> "linux" - } - val osArch = System.getProperty("os.arch").toLowerCase() - val arch = when { - osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64" - osArch.contains("amd64") || osArch.contains("x86_64") -> "x64" - else -> "x64" - } - val target = "$os-$arch" - - println("Identified OS: $os, Arch: $arch") - - val corePath = Paths.get(pluginPath.toString(), "core").toString() - val targetPath = Paths.get(corePath, target).toString() - val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() - - // esbuild needs permissions - val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString() - - val coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient) - continuePluginService.coreMessenger = coreMessenger - - coreMessenger.request("config/getSerializedProfileInfo", null, null) { resp -> - val data = resp as? Map - val profileInfo = data?.get("config") as? Map - val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean - val telemetryService = service() - if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { - telemetryService.setup(getMachineUniqueID()) - } - } - } + val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient) + continuePluginService.coreMessengerManager = coreMessengerManager } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 8731f7cac..c46cb7222 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -4,9 +4,11 @@ import com.github.continuedev.continueintellijextension.`continue`.uuid import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson +import com.intellij.injected.editor.VirtualFileWindow import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.invokeLater +import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service @@ -15,6 +17,8 @@ import com.intellij.openapi.editor.InlayProperties import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager +import com.intellij.psi.PsiDocumentManager +import com.intellij.psi.PsiElement data class PendingCompletion ( val editor: Editor, @@ -23,6 +27,15 @@ data class PendingCompletion ( var text: String? ) + +fun PsiElement.isInjectedText(): Boolean { + val virtualFile = this.containingFile.virtualFile ?: return false + if (virtualFile is VirtualFileWindow) { + return true + } + return false +} + @Service(Service.Level.PROJECT) class AutocompleteService(private val project: Project) { var pendingCompletion: PendingCompletion? = null; @@ -97,6 +110,9 @@ class AutocompleteService(private val project: Project) { if (text.isEmpty()) { return } + + if (isInjectedFile(editor)) return + // Don't render completions when code completion dropdown is visible if (!autocompleteLookupListener.isLookupEmpty()) { return @@ -195,6 +211,8 @@ class AutocompleteService(private val project: Project) { } fun clearCompletions(editor: Editor) { + if (isInjectedFile(editor)) return + if (pendingCompletion != null) { cancelCompletion(pendingCompletion!!) pendingCompletion = null @@ -211,7 +229,18 @@ class AutocompleteService(private val project: Project) { } } + private fun isInjectedFile(editor: Editor): Boolean { + val psiFile = runReadAction { PsiDocumentManager.getInstance(project).getPsiFile(editor.document) } + if (psiFile == null) { + return false + } + val response = runReadAction { psiFile.isInjectedText() } + return response + } + fun hideCompletions(editor: Editor) { + if (isInjectedFile(editor)) return + editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength).forEach { if (it.renderer is ContinueCustomElementRenderer) { it.dispose() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index bba890b67..8f3f00e32 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -181,6 +181,11 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC Files.setPosixFilePermissions(Paths.get(path), perms) } + private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() + fun onDidExit(callback: () -> Unit) { + exitCallbacks.add(callback) + } + init { if (useTcp) { try { @@ -236,10 +241,11 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) process!!.onExit().thenRun { + exitCallbacks.forEach { it() } var err = process?.errorStream?.bufferedReader()?.readText()?.trim() if (err != null) { // There are often "⚡️Done in Xms" messages, and we want everything after the last one - val delimiter = "⚡️Done in" + val delimiter = "⚡ Done in" val doneIndex = err.lastIndexOf(delimiter) if (doneIndex != -1) { err = err.substring(doneIndex + delimiter.length) @@ -254,6 +260,11 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC telemetryService.capture("jetbrains_core_exit", mapOf( "error" to err )) + + // Clean up all resources + writer?.close() + reader?.close() + process?.destroy() } Thread { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt new file mode 100644 index 000000000..f7bd42844 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -0,0 +1,80 @@ +package com.github.continuedev.continueintellijextension.`continue` + +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.services.TelemetryService +import com.intellij.ide.plugins.PluginManager +import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.service +import com.intellij.openapi.extensions.PluginId +import com.intellij.openapi.project.Project +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import java.nio.file.Paths + +class CoreMessengerManager(private val project: Project, private val ideProtocolClient: IdeProtocolClient) { + + var coreMessenger: CoreMessenger? = null + var lastBackoffInterval = 0.5 + + init { + GlobalScope.async(Dispatchers.IO) { + val continuePluginService = ServiceManager.getService( + project, + ContinuePluginService::class.java + ) + + val myPluginId = "com.github.continuedev.continueintellijextension" + val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found") + + val pluginPath = pluginDescriptor.pluginPath + val osName = System.getProperty("os.name").toLowerCase() + val os = when { + osName.contains("mac") || osName.contains("darwin") -> "darwin" + osName.contains("win") -> "win32" + osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" + else -> "linux" + } + val osArch = System.getProperty("os.arch").toLowerCase() + val arch = when { + osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64" + osArch.contains("amd64") || osArch.contains("x86_64") -> "x64" + else -> "x64" + } + val target = "$os-$arch" + + println("Identified OS: $os, Arch: $arch") + + val corePath = Paths.get(pluginPath.toString(), "core").toString() + val targetPath = Paths.get(corePath, target).toString() + val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() + + // esbuild needs permissions + val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString() + + setupCoreMessenger(esbuildPath, continueCorePath) + } + } + + private fun setupCoreMessenger(esbuildPath: String, continueCorePath: String): Unit { + coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient) + + coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp -> + val data = resp as? Map + val profileInfo = data?.get("config") as? Map + val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean + val telemetryService = service() + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { + telemetryService.setup(getMachineUniqueID()) + } + } + + // On exit, use exponential backoff to create another CoreMessenger + coreMessenger?.onDidExit { + lastBackoffInterval *= 2 + println("CoreMessenger exited, retrying in $lastBackoffInterval seconds") + Thread.sleep((lastBackoffInterval * 1000).toLong()) + setupCoreMessenger(esbuildPath, continueCorePath) + } + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 2c4badf75..cd1b50904 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -587,7 +587,7 @@ class IdeProtocolClient ( "listFolders" -> { val workspacePath = workspacePath ?: return@launch val workspaceDir = File(workspacePath) - val folders = workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.name } ?: emptyList() + val folders = workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } ?: emptyList() respond(folders) } @@ -719,30 +719,6 @@ class IdeProtocolClient ( return getMachineUniqueID() } - fun onTextSelected( - selectedText: String, - filepath: String, - startLine: Int, - startCharacter: Int, - endLine: Int, - endCharacter: Int - ) = coroutineScope.launch { -// val jsonMessage = textSelectionStrategy.handleTextSelection( -// selectedText, -// filepath, -// startLine, -// startCharacter, -// endLine, -// endCharacter -// ) -// sendMessage("highlightedCodePush", jsonMessage) -// dispatchEventToWebview( -// "highlightedCode", -// jsonMessage, -// continuePluginService.continuePluginWindow.webView -// ) - } - fun readFile(filepath: String): String { try { val content = ApplicationManager.getApplication().runReadAction { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index e974cf8fd..42205bb0b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -4,13 +4,13 @@ import com.github.continuedev.continueintellijextension.`continue`.GetTheme import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel -import com.google.gson.Gson import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl @@ -32,8 +32,6 @@ import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener -import javax.swing.plaf.ComboBoxUI -import javax.swing.plaf.basic.BasicArrowButton import javax.swing.plaf.basic.BasicComboBoxUI import kotlin.math.max @@ -41,6 +39,193 @@ import kotlin.math.max const val SHADOW_SIZE = 7 const val MAIN_FONT_SIZE = 13 +fun makeTextArea(): JTextArea { + val textArea = CustomTextArea( 2, 40).apply { + lineWrap = true + wrapStyleWord = true + isOpaque = false + background = GetTheme().getSecondaryDark() + maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) + margin = JBUI.insets(8) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) + } + textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + + return textArea +} + +fun makePanel(project: Project, customPanelRef: Ref, textArea: JTextArea, inlayRef: Ref, comboBoxRef: Ref>, leftInset: Int, modelTitles: List, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel { + val topPanel = ShadowPanel(MigLayout("wrap 1, insets 4 $leftInset 2 2, gap 0!")).apply { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground +// background = defaultBackground + background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) + isOpaque = false + } + + val panel = CustomPanel(MigLayout("wrap 1, insets 0, gap 0!, fillx"), project, modelTitles, comboBoxRef, onEnter, onCancel, onAccept, onReject).apply { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + background = defaultBackground + add(textArea, "grow, gap 0!, height 100%") + + putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + preferredSize = textArea.preferredSize + isOpaque = false + setup() + + val shadow = DropShadowBorder() + shadow.shadowColor = JBColor(0xb0b0b0, 0x505050) + shadow.isShowRightShadow = true + shadow.isShowBottomShadow = true + shadow.shadowSize = SHADOW_SIZE + border = shadow + } + customPanelRef.set(panel) + + textArea.addComponentListener(object : ComponentAdapter() { + override fun componentResized(e: ComponentEvent?) { + panel.revalidate() + panel.repaint() + } + }) + + topPanel.add(panel, "grow, gap 0!") + + return topPanel +} + +fun openInlineEdit(project: Project?, editor: Editor) { + if (project == null) return + + val manager = EditorComponentInlaysManager.from(editor) + + // Get list of model titles + val continuePluginService = project.service() + val modelTitles = mutableListOf() + continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> + val config = response as Map + val models = (config["config"] as Map)["models"] as List> + modelTitles.addAll(models.map { it["title"] as String }) + } + val maxWaitTime = 200 + val startTime = System.currentTimeMillis() + while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { + Thread.sleep(20) + } + + // Get highlighted range + val selectionModel = editor.selectionModel + val startLineNumber = editor.document.getLineNumber(selectionModel.selectionStart) + val endLineNumber = editor.document.getLineNumber(selectionModel.selectionEnd) + val start = editor.document.getLineStartOffset(startLineNumber) + val end = editor.document.getLineEndOffset(endLineNumber) + val prefix = editor.document.getText(TextRange(0, start)) + val highlighted = editor.document.getText(TextRange(start, end)) + val suffix = editor.document.getText(TextRange(end, editor.document.textLength)) + + val startLineNum = editor.document.getLineNumber(start) + val endLineNum = editor.document.getLineNumber(end) + val lineNumber = max(0, startLineNum - 1) + + // Un-highlight the selected text + selectionModel.removeSelection() + + // Get indentation width in pixels + val indentationLineNum = lineNumber + 1 + val lineStart = editor.document.getLineStartOffset(indentationLineNum) + val lineEnd = editor.document.getLineEndOffset(indentationLineNum) + val text = editor.document.getText(TextRange(lineStart, lineEnd)) + val indentation = text.takeWhile { it == ' ' }.length + val charWidth = editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ') + val leftInset = indentation * charWidth * 2 / 3 + + val inlayRef = Ref() + val customPanelRef = Ref() + + // Create text area, attach key listener + val textArea = makeTextArea() + + // Create diff stream handler + val diffStreamHandler = DiffStreamHandler(project, editor, textArea, startLineNum, endLineNum, { + inlayRef.get().dispose() + }, { + customPanelRef.get().finish() + }) + val diffStreamService = project.service() + diffStreamService.register(diffStreamHandler, editor) + + diffStreamHandler.setup() + + val comboBoxRef = Ref>() + + fun onEnter() { + customPanelRef.get().enter() + diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, comboBoxRef.get().selectedItem as String) + } + + val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, { + diffStreamService.reject(editor) + selectionModel.setSelection(start, end) + }, { + diffStreamService.accept(editor) + inlayRef.get().dispose() + }, { + diffStreamService.reject(editor) + inlayRef.get().dispose() + }) + val inlay = manager.insertAfter(lineNumber, panel) + panel.revalidate() + inlayRef.set(inlay) + val viewport = (editor as? EditorImpl)?.scrollPane?.viewport + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + + // Add key listener to text area + textArea.addKeyListener(object : KeyAdapter() { + override fun keyPressed(e: KeyEvent) { + if (e.keyCode == KeyEvent.VK_ESCAPE) { + diffStreamService.reject(editor) + + // Re-highlight the selected text + selectionModel.setSelection(start, end) + } else if (e.keyCode == KeyEvent.VK_ENTER) { + if (e.modifiersEx == KeyEvent.SHIFT_DOWN_MASK) { + textArea.document.insertString(textArea.caretPosition, "\n", null) + } else if (e.modifiersEx == 0) { + onEnter() + e.consume() + } + } + } + }) + + // Listen for changes to textarea line count + textArea.document.addDocumentListener(object : DocumentListener { + private var lastNumLines: Int = 0 + private fun updateSize() { + val numLines = textArea.text.lines().size + if (numLines != lastNumLines) { + lastNumLines = numLines + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + } + } + override fun insertUpdate(e: DocumentEvent?) { + updateSize() + } + + override fun removeUpdate(e: DocumentEvent?) { + updateSize() + } + + override fun changedUpdate(e: DocumentEvent?) { + updateSize() + } + }) + + + textArea.requestFocus() +} + /** * Adapted from https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt */ @@ -55,192 +240,9 @@ class InlineEditAction : AnAction(), DumbAware { } override fun actionPerformed(e: AnActionEvent) { - if (e.project == null) return - val editor = e.getData(PlatformDataKeys.EDITOR) ?: return val project = e.getData(PlatformDataKeys.PROJECT) ?: return - val manager = EditorComponentInlaysManager.from(editor) - - // Get list of model titles - val continuePluginService = project.service() - val modelTitles = mutableListOf() - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val config = response as Map - val models = (config["config"] as Map)["models"] as List> - modelTitles.addAll(models.map { it["title"] as String }) - } - val maxWaitTime = 200 - val startTime = System.currentTimeMillis() - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { - Thread.sleep(20) - } - - // Get highlighted range - val selectionModel = editor.selectionModel - val startLineNumber = editor.document.getLineNumber(selectionModel.selectionStart) - val endLineNumber = editor.document.getLineNumber(selectionModel.selectionEnd) - val start = editor.document.getLineStartOffset(startLineNumber) - val end = editor.document.getLineEndOffset(endLineNumber) - val prefix = editor.document.getText(TextRange(0, start)) - val highlighted = editor.document.getText(TextRange(start, end)) - val suffix = editor.document.getText(TextRange(end, editor.document.textLength)) - - val startLineNum = editor.document.getLineNumber(start) - val endLineNum = editor.document.getLineNumber(end) - val lineNumber = max(0, startLineNum - 1) - - // Un-highlight the selected text - selectionModel.removeSelection() - - // Get indentation width in pixels - val indentationLineNum = lineNumber + 1 - val lineStart = editor.document.getLineStartOffset(indentationLineNum) - val lineEnd = editor.document.getLineEndOffset(indentationLineNum) - val text = editor.document.getText(TextRange(lineStart, lineEnd)) - val indentation = text.takeWhile { it == ' ' }.length - val charWidth = editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ') - val leftInset = indentation * charWidth * 2 / 3 - - val inlayRef = Ref() - val customPanelRef = Ref() - - // Create text area, attach key listener - val textArea = makeTextArea() - - // Create diff stream handler - val diffStreamHandler = DiffStreamHandler(project, editor, textArea, startLineNum, endLineNum, { - inlayRef.get().dispose() - }, { - customPanelRef.get().finish() - }) - val diffStreamService = project.service() - diffStreamService.register(diffStreamHandler, editor) - - diffStreamHandler.setup() - - val comboBoxRef = Ref>() - - fun onEnter() { - customPanelRef.get().enter() - diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, comboBoxRef.get().selectedItem as String) - } - - val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, { - diffStreamService.reject(editor) - selectionModel.setSelection(start, end) - }, { - diffStreamService.accept(editor) - inlayRef.get().dispose() - }, { - diffStreamService.reject(editor) - inlayRef.get().dispose() - }) - val inlay = manager.insertAfter(lineNumber, panel) - panel.revalidate() - inlayRef.set(inlay) - val viewport = (editor as? EditorImpl)?.scrollPane?.viewport - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - - // Add key listener to text area - textArea.addKeyListener(object : KeyAdapter() { - override fun keyPressed(e: KeyEvent) { - if (e.keyCode == KeyEvent.VK_ESCAPE) { - diffStreamService.reject(editor) - - // Re-highlight the selected text - selectionModel.setSelection(start, end) - } else if (e.keyCode == KeyEvent.VK_ENTER) { - if (e.modifiersEx == KeyEvent.SHIFT_DOWN_MASK) { - textArea.document.insertString(textArea.caretPosition, "\n", null) - } else if (e.modifiersEx == 0) { - onEnter() - e.consume() - } - } - } - }) - - // Listen for changes to textarea line count - textArea.document.addDocumentListener(object : DocumentListener { - private var lastNumLines: Int = 0 - private fun updateSize() { - val numLines = textArea.text.lines().size - if (numLines != lastNumLines) { - lastNumLines = numLines - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - } - } - override fun insertUpdate(e: DocumentEvent?) { - updateSize() - } - - override fun removeUpdate(e: DocumentEvent?) { - updateSize() - } - - override fun changedUpdate(e: DocumentEvent?) { - updateSize() - } - }) - - - textArea.requestFocus() - } - - fun makeTextArea(): JTextArea { - val textArea = CustomTextArea( 2, 40).apply { - lineWrap = true - wrapStyleWord = true - isOpaque = false - background = GetTheme().getSecondaryDark() - maximumSize = Dimension(400, Short.MAX_VALUE.toInt()) - margin = JBUI.insets(8) - font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) - } - textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - - return textArea - } - - fun makePanel(project: Project, customPanelRef: Ref, textArea: JTextArea, inlayRef: Ref, comboBoxRef: Ref>, leftInset: Int, modelTitles: List, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel { - val topPanel = ShadowPanel(MigLayout("wrap 1, insets 4 $leftInset 2 2, gap 0!")).apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground -// background = defaultBackground - background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) - isOpaque = false - } - - val panel = CustomPanel(MigLayout("wrap 1, insets 0, gap 0!, fillx"), project, modelTitles, comboBoxRef, onEnter, onCancel, onAccept, onReject).apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - background = defaultBackground - add(textArea, "grow, gap 0!, height 100%") - - putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - preferredSize = textArea.preferredSize - isOpaque = false - setup() - - val shadow = DropShadowBorder() - shadow.shadowColor = JBColor(0xb0b0b0, 0x505050) - shadow.isShowRightShadow = true - shadow.isShowBottomShadow = true - shadow.shadowSize = SHADOW_SIZE - border = shadow - } - customPanelRef.set(panel) - - textArea.addComponentListener(object : ComponentAdapter() { - override fun componentResized(e: ComponentEvent?) { - panel.revalidate() - panel.repaint() - } - }) - - topPanel.add(panel, "grow, gap 0!") - - return topPanel + openInlineEdit(project, editor) } } @@ -260,7 +262,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -315,7 +317,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List isEditable = true background = defaultBackground foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) isOpaque = false isEditable = false @@ -352,7 +354,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { val leftLabel = JLabel("Enter follow-up instructions").apply { foreground = Color(128, 128, 128, 200) - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) } val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply { @@ -445,7 +447,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { }) // verticalAlignment = CENTER - font = Font("Arial", Font.PLAIN, 11) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) border = EmptyBorder(2, 4, 2, 4) } override fun paintComponent(g: Graphics) { @@ -477,7 +479,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { // Draw placeholder if (text.isEmpty()) { g.color = Color(128, 128, 128, 255) - g.font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE) + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) g.drawString("Enter instructions to edit highlighted code", 8, 20) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt new file mode 100644 index 000000000..7d5ba7c08 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/ToolTipComponent.kt @@ -0,0 +1,121 @@ +import com.github.continuedev.continueintellijextension.actions.focusContinueInput +import com.github.continuedev.continueintellijextension.editor.openInlineEdit +import com.intellij.openapi.editor.Editor +import com.intellij.openapi.editor.LogicalPosition +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.ui.components.JBPanel +import java.awt.* +import java.awt.event.ActionEvent +import java.util.* +import javax.swing.JButton +import java.awt.geom.RoundRectangle2D + +class StyledButton(text: String, foregroundColor: Color) : JButton(text) { + init { + cursor = Cursor(Cursor.HAND_CURSOR) + isOpaque = false + isContentAreaFilled = false + isFocusPainted = false + border = null // Remove the border + foreground = foregroundColor + } + + override fun paintComponent(g: Graphics) { + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + val arc = 24f // Corner radius + val padding = 0f + val x = padding + val y = padding + val w = (width - 2 * padding) + val h = (height - 2 * padding) + + // Draw flat background +// g2.color = if (model.isPressed) Color(70, 70, 70) else Color(100, 100, 100) +// g2.fill(RoundRectangle2D.Float(x, y, w, h, arc, arc)) + + // Draw border +// g2.color = Color(120, 120, 120) +// g2.draw(RoundRectangle2D.Float(x, y, w - 1, h - 1, arc, arc)) + + g2.dispose() + + super.paintComponent(g) + } +} + +class ToolTipComponent(editor: Editor, x: Int, y: Int) : + JBPanel() { + private var addToChatButton: StyledButton + private var editButton: StyledButton + private var backgroundColor: Color + private var foregroundColor: Color + + init { + layout = null // Remove the FlowLayout + + val globalScheme = EditorColorsManager.getInstance().globalScheme + backgroundColor = globalScheme.defaultBackground + foregroundColor = Color( + globalScheme.defaultForeground.red, + globalScheme.defaultForeground.green, + globalScheme.defaultForeground.blue, + 200 + ) + + val cmdCtrlChar = if (System.getProperty("os.name").lowercase(Locale.getDefault()).contains("mac")) "⌘" else "Ctrl" + addToChatButton = StyledButton("${cmdCtrlChar}J Chat", foregroundColor) + editButton = StyledButton("${cmdCtrlChar}I Edit", foregroundColor) + + addToChatButton.addActionListener { e: ActionEvent? -> + focusContinueInput(editor.project) + editor.contentComponent.remove(this) + } + editButton.addActionListener { e: ActionEvent? -> + openInlineEdit(editor.project, editor) + editor.contentComponent.remove(this) + } + + // Set bounds for buttons to remove spacing + addToChatButton.setBounds(0, 0, addToChatButton.preferredSize.width, addToChatButton.preferredSize.height) + editButton.setBounds(addToChatButton.preferredSize.width, 0, editButton.preferredSize.width, editButton.preferredSize.height) + + add(addToChatButton) + add(editButton) + + val totalWidth = addToChatButton.preferredSize.width + editButton.preferredSize.width + val totalHeight = addToChatButton.preferredSize.height + setBounds(x, y, totalWidth, totalHeight) + + // Make the background transparent + isOpaque = false + background = Color(0, 0, 0, 0) + } + + override fun paintComponent(g: Graphics) { + val arc = 12f + + val g2 = g.create() as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + + // Draw rounded rectangle background + g2.color = backgroundColor + g2.fill(RoundRectangle2D.Float(0f, 0f, width.toFloat(), height.toFloat(), arc, arc)) + + // Draw rounded rectangle border + g2.color = Color(120, 120, 120) + val strokeWidth = 1.0f + g2.stroke = BasicStroke(1.0f) + g2.draw(RoundRectangle2D.Float(0f, 0f, width.toFloat() - strokeWidth, height.toFloat() - strokeWidth, arc, arc)) + + // Draw border between buttons + g2.color = Color(120, 120, 120) + g2.stroke = BasicStroke(1.0f) + val middleX = addToChatButton.width.toFloat() + g2.drawLine(middleX.toInt(), 0, middleX.toInt(), height) + + g2.dispose() + super.paintComponent(g) + } +} diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt index e2164b090..55b106790 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt @@ -1,8 +1,12 @@ package com.github.continuedev.continueintellijextension.listeners +import ToolTipComponent import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.Debouncer import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.service +import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.event.SelectionListener @@ -10,6 +14,8 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.vfs.VirtualFile import kotlinx.coroutines.CoroutineScope +import kotlin.math.max +import kotlin.math.min class ContinuePluginSelectionListener( private val ideProtocolClient: IdeProtocolClient, @@ -20,11 +26,31 @@ class ContinuePluginSelectionListener( debouncer.debounce { handleSelection(e) } } + private var toolTipComponent: ToolTipComponent? = null + private fun handleSelection(e: SelectionEvent) { ApplicationManager.getApplication().runReadAction { val editor = e.editor val model: SelectionModel = editor.selectionModel - val selectedText = model.selectedText ?: return@runReadAction + val selectedText = model.selectedText + + // If selected text is empty, remove the tooltip + if (selectedText.isNullOrEmpty()) { + ApplicationManager.getApplication().invokeLater { + toolTipComponent?.let { editor.contentComponent.remove(it) } + toolTipComponent = null + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } + return@runReadAction + } + + // Allow user to disable editor tooltip + // Note that we still check for empty selected text before this + val extensionSettingsService = service() + if (extensionSettingsService.continueState.displayEditorTooltip == false) { + return@runReadAction + } val document = editor.document val startOffset = model.selectionStart @@ -39,14 +65,34 @@ class ContinuePluginSelectionListener( FileDocumentManager.getInstance().getFile(document) val filepath = virtualFile?.path ?: "Unknown path" - ideProtocolClient.onTextSelected( - selectedText, - filepath, - startLine, - startCharacter, - endLine, - endCharacter - ) + ApplicationManager.getApplication().invokeLater { + toolTipComponent?.let { editor.contentComponent.remove(it) } + + editor.contentComponent.layout = null + + val line = startLine - 2 + if (line > 0 && startLine < endLine) { + // Get the text on line number "line" +// val text = document.getText(document.getLineStartOffset(line), document.getLineEndOffset(line)) + + val pos = LogicalPosition(line, selectedText.split("\n")[0].length + 1) + val y: Int = editor.logicalPositionToXY(pos).y + editor.lineHeight + var x: Int = editor.logicalPositionToXY(pos).x + + // Check if x is out of bounds + val maxEditorWidth = editor.contentComponent.width + val maxToolTipWidth = 600 + x = max(0, min(x, maxEditorWidth - maxToolTipWidth)) + + toolTipComponent = ToolTipComponent(editor, x, y) + editor.contentComponent.add(toolTipComponent) + } else { + toolTipComponent = null + } + + editor.contentComponent.revalidate() + editor.contentComponent.repaint() + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 6ff8277a5..81bbbb6af 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -16,6 +16,7 @@ class ContinueSettingsComponent: DumbAware { val userToken: JTextField = JTextField() val enableTabAutocomplete: JCheckBox = JCheckBox("Enable Tab Autocomplete") val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta (requires restart)") + val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip") init { val constraints = GridBagConstraints() @@ -42,6 +43,8 @@ class ContinueSettingsComponent: DumbAware { constraints.gridy++ panel.add(enableContinueTeamsBeta, constraints) constraints.gridy++ + panel.add(displayEditorTooltip, constraints) + constraints.gridy++ // Add a "filler" component that takes up all remaining vertical space constraints.weighty = 1.0 @@ -65,6 +68,7 @@ open class ContinueExtensionSettings : PersistentStateComponent? = null var windowId: String = UUID.randomUUID().toString() diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 2fbe735e9..13924ae82 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -5,6 +5,7 @@ continue-dev com.intellij.modules.platform org.jetbrains.plugins.terminal + diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index f6611bea0..26415a624 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -190,7 +191,8 @@ "azure", "msty", "watsonx", - "openrouter" + "openrouter", + "nvidia" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -198,6 +200,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,8 +219,9 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", + "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)" ], "type": "string" }, @@ -665,6 +669,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "anyOf": [ { @@ -759,6 +766,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": [ "chat-bison-001", @@ -977,6 +987,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] } @@ -1231,13 +1244,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2018,7 +2025,8 @@ "openai", "cohere", "free-trial", - "gemini" + "gemini", + "voyage" ] }, "model": { @@ -2049,7 +2057,7 @@ "if": { "properties": { "provider": { - "enum": ["cohere"] + "enum": ["cohere", "voyage"] } }, "required": ["provider"] @@ -2402,9 +2410,17 @@ "properties": { "inlineEdit": { "type": "string" + }, + "applyCodeBlock": { + "type": "string" } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 844377fb3..a20a75b56 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,6 +5,15 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). +## 0.8.47 - 2024-08-27 +### Added +* Use headless browser for crawling to get better results +* TTS support in the chat window +### Changed +* Improved support for WatsonX models +### Fixed +* Fixed several small indexing bugs + ## 0.8.46 - 2024-08-11 ### Added * new /onboard slash command diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f6611bea0..26415a624 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -171,6 +171,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -190,7 +191,8 @@ "azure", "msty", "watsonx", - "openrouter" + "openrouter", + "nvidia" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -198,6 +200,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -216,8 +219,9 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", + "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)" ], "type": "string" }, @@ -665,6 +669,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "anyOf": [ { @@ -759,6 +766,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": [ "chat-bison-001", @@ -977,6 +987,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] } @@ -1231,13 +1244,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2018,7 +2025,8 @@ "openai", "cohere", "free-trial", - "gemini" + "gemini", + "voyage" ] }, "model": { @@ -2049,7 +2057,7 @@ "if": { "properties": { "provider": { - "enum": ["cohere"] + "enum": ["cohere", "voyage"] } }, "required": ["provider"] @@ -2402,9 +2410,17 @@ "properties": { "inlineEdit": { "type": "string" + }, + "applyCodeBlock": { + "type": "string" } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 5bcfaa05c..6f49ee85e 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -174,6 +174,7 @@ "anthropic", "cohere", "bedrock", + "bedrockimport", "sagemaker", "together", "ollama", @@ -193,7 +194,8 @@ "azure", "msty", "watsonx", - "openrouter" + "openrouter", + "nvidia" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -201,6 +203,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", @@ -219,8 +222,9 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." + "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", + "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)" ], "type": "string" }, @@ -716,6 +720,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "anyOf": [ { @@ -829,6 +836,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": [ "chat-bison-001", @@ -1069,6 +1079,9 @@ }, "then": { "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, "model": { "enum": [ "deepseek-chat", @@ -1366,13 +1379,7 @@ "watsonxApiKey": { "type": "string" }, - "watsonxZenApiKeyBase64": { - "type": "string" - }, - "watsonxUsername": { - "type": "string" - }, - "watsonxPassword": { + "watsonxApiVersion": { "type": "string" }, "watsonxProjectId": { @@ -2245,7 +2252,8 @@ "openai", "cohere", "free-trial", - "gemini" + "gemini", + "voyage" ] }, "model": { @@ -2279,7 +2287,8 @@ "properties": { "provider": { "enum": [ - "cohere" + "cohere", + "voyage" ] } }, @@ -2697,9 +2706,17 @@ "properties": { "inlineEdit": { "type": "string" + }, + "applyCodeBlock": { + "type": "string" } } }, + "readResponseTTS": { + "type": "boolean", + "default": true, + "description": "Automatically read LLM chat responses aloud using system TTS models" + }, "promptPath": { "type": "string" }, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 6af742e21..c3df2a736 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.197", + "version": "0.9.201", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.197", + "version": "0.9.201", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -108,7 +108,6 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", @@ -133,6 +132,8 @@ "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 3dfc6cc2a..27e16410e 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.198", + "version": "0.9.201", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index ad2ba5773..f002e3c50 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -247,6 +247,7 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/llm/llamaTokenizer.mjs", "../../../core/llm/tiktokenWorkerPool.mjs", ]; + for (const f of filesToCopy) { fs.copyFileSync( path.join(__dirname, f), @@ -460,6 +461,7 @@ const exe = os === "win32" ? ".exe" : ""; "@vscode/ripgrep", "workerpool", ]; + fs.mkdirSync("out/node_modules", { recursive: true }); await Promise.all( @@ -507,8 +509,8 @@ const exe = os === "win32" ? ".exe" : ""; os === "darwin" ? "libonnxruntime.1.14.0.dylib" : os === "linux" - ? "libonnxruntime.so.1.14.0" - : "onnxruntime.dll" + ? "libonnxruntime.so.1.14.0" + : "onnxruntime.dll" }`, "builtin-themes/dark_modern.json", @@ -547,8 +549,8 @@ const exe = os === "win32" ? ".exe" : ""; target === "win32-arm64" ? "esbuild.exe" : target === "win32-x64" - ? "win32-x64/esbuild.exe" - : `${target}/bin/esbuild` + ? "win32-x64/esbuild.exe" + : `${target}/bin/esbuild` }`, `out/node_modules/@lancedb/vectordb-${ os === "win32" diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 95f5406f2..7608443ae 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -8,6 +8,8 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { showFreeTrialLoginMessage } from "../util/messages"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { @@ -31,6 +33,15 @@ export class ContinueCompletionProvider if (e.message.includes("https://ollama.ai")) { options.push("Download Ollama"); } + + if (e.message.includes("Please sign in with GitHub")) { + showFreeTrialLoginMessage( + e.message, + this.configHandler.reloadConfig.bind(this.configHandler), + () => this.webviewProtocol.request("openOnboarding", undefined), + ); + return; + } vscode.window.showErrorMessage(e.message, ...options).then((val) => { if (val === "Documentation") { vscode.env.openExternal( @@ -51,6 +62,7 @@ export class ContinueCompletionProvider private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel, + private readonly webviewProtocol: VsCodeWebviewProtocol, ) { this.completionProvider = new CompletionProvider( this.configHandler, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 4226b1328..979c782b0 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -9,6 +9,7 @@ import { CompletionProvider } from "core/autocomplete/completionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; import { Core } from "core/core"; +import { walkDirAsync } from "core/indexing/walkDir"; import { GlobalContext } from "core/util/GlobalContext"; import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; @@ -25,6 +26,7 @@ import { DiffManager } from "./diff/horizontal"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; +import { uriFromFilePath } from "./util/vscode"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -511,14 +513,32 @@ const commandsMap: ( "continue.openConfigJson": () => { ide.openFile(getConfigJsonPath()); }, - "continue.selectFilesAsContext": ( + "continue.selectFilesAsContext": async ( firstUri: vscode.Uri, uris: vscode.Uri[], ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } + vscode.commands.executeCommand("continue.continueGUIView.focus"); for (const uri of uris) { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); + } + } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); + } } }, "continue.logAutocompleteOutcome": ( @@ -594,8 +614,8 @@ const commandsMap: ( currentStatus === StatusBarStatus.Paused ? StatusBarStatus.Enabled : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused - : StatusBarStatus.Disabled; + ? StatusBarStatus.Paused + : StatusBarStatus.Disabled; } else { // Toggle between Disabled and Enabled targetStatus = diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 563c0d068..8323a0d6f 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -177,6 +177,7 @@ export class VsCodeExtension { this.configHandler, this.ide, this.tabAutocompleteModel, + this.sidebar.webviewProtocol, ), ), ); diff --git a/extensions/vscode/src/util/messages.ts b/extensions/vscode/src/util/messages.ts new file mode 100644 index 000000000..2cef9d4b1 --- /dev/null +++ b/extensions/vscode/src/util/messages.ts @@ -0,0 +1,23 @@ +import * as vscode from "vscode"; + +export function showFreeTrialLoginMessage( + message: string, + reloadConfig: () => void, + openOnboarding: () => void, +) { + vscode.window + .showInformationMessage(message, "Sign In", "Use API key / local model") + .then((selection) => { + if (selection === "Sign In") { + vscode.authentication + .getSession("github", [], { + createIfNone: true, + }) + .then(() => { + reloadConfig(); + }); + } else if (selection === "Use API key / local model") { + openOnboarding(); + } + }); +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index eed3d15a0..bfc9cb125 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,4 +1,5 @@ import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; +import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Message } from "core/util/messenger"; import { Telemetry } from "core/util/posthog"; @@ -7,6 +8,7 @@ import path from "path"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; import { IMessenger } from "../../../core/util/messenger"; +import { showFreeTrialLoginMessage } from "./util/messages"; import { getExtensionUri } from "./util/vscode"; export async function showTutorial() { @@ -73,7 +75,7 @@ export class VsCodeWebviewProtocol throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`); } - const respond = (message: any) => + const respond = (message: WebviewMessengerResult) => this.send(msg.messageType, message, msg.messageId); const handlers = this.listeners.get(msg.messageType) || []; @@ -89,12 +91,16 @@ export class VsCodeWebviewProtocol respond(next.value); next = await response.next(); } - respond({ done: true, content: next.value?.content }); + respond({ + done: true, + content: next.value?.content, + status: "success", + }); } else { - respond(response || {}); + respond({ done: true, content: response || {}, status: "success" }); } } catch (e: any) { - respond({ done: true, error: e }); + respond({ done: true, error: e, status: "error" }); console.error( `Error handling webview message: ${JSON.stringify( @@ -135,25 +141,9 @@ export class VsCodeWebviewProtocol } }); } else if (message.includes("Please sign in with GitHub")) { - vscode.window - .showInformationMessage( - message, - "Sign In", - "Use API key / local model", - ) - .then((selection) => { - if (selection === "Sign In") { - vscode.authentication - .getSession("github", [], { - createIfNone: true, - }) - .then(() => { - this.reloadConfig(); - }); - } else if (selection === "Use API key / local model") { - this.request("openOnboarding", undefined); - } - }); + showFreeTrialLoginMessage(message, this.reloadConfig, () => + this.request("openOnboarding", undefined), + ); } else { Telemetry.capture( "webview_protocol_error", diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/c.scm b/extensions/vscode/tree-sitter/code-snippet-queries/c.scm index bb343911e..ff3cb6dc2 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/c.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/c.scm @@ -4,6 +4,6 @@ (declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class -(type_definition declarator: (type_identifier) @name ) @body +(type_definition declarator: (type_identifier) @name ) @definition (enum_specifier name: (type_identifier) @name.definition.type) @definition.type diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/go.scm b/extensions/vscode/tree-sitter/code-snippet-queries/go.scm index 9d2af874d..bac626605 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/go.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/go.scm @@ -1,19 +1,26 @@ ( - (comment)* @doc + (comment)* @comment . (function_declaration - name: (identifier) @name.definition.function) @definition.function - (#strip! @doc "^//\\s*") - (#set-adjacent! @doc @definition.function) + name: (identifier) @name.definition.function + parameters: (_) @parameters + result: (_)? @return_type + ) @definition.function + (#strip! @comment "^//\\s*") + (#set-adjacent! @comment @definition.function) ) ( - (comment)* @doc + (comment)* @comment . (method_declaration - name: (field_identifier) @name.definition.method) @definition.method - (#strip! @doc "^//\\s*") - (#set-adjacent! @doc @definition.method) + receiver: (_) @receiver + name: (field_identifier) @name.definition.method + parameters: (_) @parameters + result: (_)? @return_type + ) @definition.method + (#strip! @comment "^//\\s*") + (#set-adjacent! @comment @definition.method) ) (type_spec diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm index 593a75fc6..0aeccc319 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/java.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/java.scm @@ -1,8 +1,15 @@ (class_declaration - name: (identifier) @name.definition.class) @definition.class + name: (_) @name.definition.class + interfaces: (_) @interfaces +) @definition.class + (method_declaration - name: (identifier) @name.definition.method) @definition.method + type: (_) @return_type + name: (_) @name.definition.method + parameters: (_) @parameters +) @definition.method (interface_declaration - name: (identifier) @name.definition.interface) @definition.interface \ No newline at end of file + name: (_) @name.definition.interface +) @definition.interface \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm index 7be9458f4..3b6153c90 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/javascript.scm @@ -1,8 +1,22 @@ -(class_declaration - name: (_) @name) @body +( + (comment)? @comment + (class_declaration + name: (_) @name + ) @definition +) -(function_declaration - name: (_) @name) @body +( + (comment)? @comment + (function_declaration + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(method_definition - name: (_) @name) @body \ No newline at end of file +( + (comment)? @comment + (method_definition + name: (_) @name + parameters: (_) @parameters + ) @definition +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm b/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm index 9bc034d8e..9040cad33 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/ocaml.scm @@ -1,12 +1,12 @@ (value_definition (let_binding pattern: (_) @name) -) @body +) @definition (module_type_definition - name: (_) @name) @body + name: (_) @name) @definition (class_definition (class_binding name: (_) @name) -) @body \ No newline at end of file +) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm index c95663f3c..124de18ea 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/php.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/php.scm @@ -1,8 +1,8 @@ (class_declaration - name: (name) @name) @body + name: (name) @name) @definition (function_definition - name: (name) @name) @body + name: (name) @name) @definition (method_declaration - name: (name) @name) @body \ No newline at end of file + name: (name) @name) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm index 04289704f..586d738c7 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/python.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/python.scm @@ -1,5 +1,7 @@ (class_definition - name: (_) @name) @body + name: (_) @name) @definition (function_definition - name: (_) @name) @body \ No newline at end of file + name: (_) @name + parameters: (_) @parameters +) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm index e4125cabf..4b10e7c34 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/rust.scm @@ -1,8 +1,11 @@ (function_item - name: (_) @name) @body + name: (_) @name + parameters: (_) @parameters + return_type: (_)? @return_type +) @definition (struct_item - name: (_) @name) @body + name: (_) @name) @definition (impl_item - type: (_) @name) @body \ No newline at end of file + type: (_) @name) @definition \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm index c56cf4fba..d564f406a 100644 --- a/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm +++ b/extensions/vscode/tree-sitter/code-snippet-queries/typescript.scm @@ -1,11 +1,28 @@ -(class_declaration - name: (_) @name) @body +( + (comment)? @comment + (class_declaration + name: (_) @name + ) @definition +) -(function_declaration - name: (_) @name) @body +( + (comment)? @comment + (function_declaration + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(method_definition - name: (_) @name) @body +( + (comment)? @comment + (method_definition + name: (_) @name + parameters: (_) @parameters + ) @definition +) -(interface_declaration - name: (_) @name) @body \ No newline at end of file +( + (comment)? @comment + (interface_declaration + name: (_) @name) @definition +) \ No newline at end of file diff --git a/gui/package-lock.json b/gui/package-lock.json index 3e67abbcc..774db75f8 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -101,7 +101,6 @@ "adf-to-md": "^1.1.0", "async-mutex": "^0.5.0", "axios": "^1.6.7", - "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", "dbinfoz": "^0.1.4", @@ -126,6 +125,8 @@ "p-limit": "^6.1.0", "pg": "^8.11.3", "posthog-node": "^3.6.3", + "puppeteer": "^22.4.0", + "puppeteer-chromium-resolver": "^23.0.0", "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", @@ -6312,40 +6313,6 @@ "node": ">=10" } }, - "../core/node_modules/cheerio": { - "version": "1.0.0-rc.12", - "license": "MIT", - "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" - }, - "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" - } - }, - "../core/node_modules/cheerio-select": { - "version": "2.1.0", - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, "../core/node_modules/chownr": { "version": "2.0.0", "license": "ISC", @@ -8312,23 +8279,6 @@ "dev": true, "license": "MIT" }, - "../core/node_modules/htmlparser2": { - "version": "8.0.2", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "entities": "^4.4.0" - } - }, "../core/node_modules/http-cache-semantics": { "version": "4.1.1", "license": "BSD-2-Clause", @@ -10574,17 +10524,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "../core/node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "license": "MIT", - "dependencies": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "../core/node_modules/path-exists": { "version": "4.0.0", "license": "MIT", diff --git a/gui/public/logos/WatsonX.png b/gui/public/logos/WatsonX.png index 66cf02a03..ba4807267 100644 Binary files a/gui/public/logos/WatsonX.png and b/gui/public/logos/WatsonX.png differ diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 30208b95d..dd9256753 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,7 +12,7 @@ import { } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { shouldBeginOnboarding } from "../pages/onboarding/utils"; +import { isNewUserOnboarding } from "../pages/onboarding/utils"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { setBottomMessage, @@ -30,7 +30,6 @@ import ProgressBar from "./loaders/ProgressBar"; import PostHogPageView from "./PosthogPageView"; import ProfileSwitcher from "./ProfileSwitcher"; -// #region Styled Components const FOOTER_HEIGHT = "1.8em"; const LayoutTopDiv = styled(CustomScrollbarDiv)` @@ -105,8 +104,6 @@ const ProfileDropdownPortalDiv = styled.div` font-size: ${getFontSize() - 2}; `; -// #endregion - const HIDE_FOOTER_ON_PAGES = [ "/onboarding", "/localOnboarding", @@ -127,7 +124,6 @@ const Layout = () => { ); const defaultModel = useSelector(defaultModelSelector); - // #region Selectors const bottomMessage = useSelector( (state: RootState) => state.uiState.bottomMessage, @@ -138,8 +134,6 @@ const Layout = () => { const timeline = useSelector((state: RootState) => state.state.history); - // #endregion - useEffect(() => { const handleKeyDown = (event: any) => { if (isMetaEquivalentKeyPressed(event) && event.code === "KeyC") { @@ -231,7 +225,7 @@ const Layout = () => { useEffect(() => { if ( - shouldBeginOnboarding() && + isNewUserOnboarding() && (location.pathname === "/" || location.pathname === "/index.html") ) { navigate("/onboarding"); diff --git a/gui/src/components/ProfileSwitcher.tsx b/gui/src/components/ProfileSwitcher.tsx index d07ab5d44..4ffa1f085 100644 --- a/gui/src/components/ProfileSwitcher.tsx +++ b/gui/src/components/ProfileSwitcher.tsx @@ -155,7 +155,11 @@ function ProfileSwitcher(props: {}) { }, []); useEffect(() => { - ideMessenger.request("config/listProfiles", undefined).then(setProfiles); + ideMessenger + .request("config/listProfiles", undefined) + .then( + (result) => result.status === "success" && setProfiles(result.content), + ); }, []); useWebviewListener( @@ -174,62 +178,61 @@ function ProfileSwitcher(props: {}) { return ( <> - {controlServerBetaEnabled && - profiles.some((profile) => profile.id !== "local") && ( - { - ideMessenger.request("didChangeSelectedProfile", { id }); - }} - > -
- -
{selectedProfile()?.title}
-
-
-
- {topDiv && - ReactDOM.createPortal( - - - {profiles.map((option, idx) => ( - 1} - /> - ))} -
- {profiles.length === 0 ? ( - No workspaces found - ) : ( - "Select workspace" - )} -
-
-
, - topDiv, - )} -
-
- )} + {controlServerBetaEnabled && session?.account?.id && ( + { + ideMessenger.request("didChangeSelectedProfile", { id }); + }} + > +
+ +
{selectedProfile()?.title}
+
+
+
+ {topDiv && + ReactDOM.createPortal( + + + {profiles.map((option, idx) => ( + 1} + /> + ))} +
+ {profiles.length === 0 ? ( + No workspaces found + ) : ( + "Select workspace" + )} +
+
+
, + topDiv, + )} +
+
+ )} {/* Settings button (either opens config.json or /settings page in control plane) */} (""); const [isOpen, setIsOpen] = useState(false); const ideMessenger = useContext(IdeMessengerContext); @@ -39,18 +35,14 @@ function AddDocsDialog() { const siteIndexingConfig: SiteIndexingConfig = { startUrl, - rootUrl, title, - maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth, - faviconUrl: new URL("/favicon.ico", startUrl).toString(), + faviconUrl, }; ideMessenger.post("context/addDocs", siteIndexingConfig); setTitle(""); setStartUrl(""); - setRootUrl(""); - setMaxDepth(""); setFaviconUrl(""); dispatch(setShowDialog(false)); @@ -126,22 +118,6 @@ function AddDocsDialog() { {isOpen && (
- - - -
)} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 83752c95f..654121fd9 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -14,6 +14,7 @@ import { } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { getBasename, getRelativePath } from "core/util"; +import { debounce } from "lodash"; import { usePostHog } from "posthog-js/react"; import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; @@ -56,7 +57,6 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; -import { debounce } from "lodash"; const InputBoxDiv = styled.div` resize: none; @@ -483,18 +483,18 @@ function TipTapEditor(props: TipTapEditorProps) { if (editor) { const handleFocus = () => { debouncedShouldHideToolbar(false); - } + }; const handleBlur = () => { debouncedShouldHideToolbar(true); }; - editor.on('focus', handleFocus); - editor.on('blur', handleBlur); + editor.on("focus", handleFocus); + editor.on("blur", handleBlur); return () => { - editor.off('focus', handleFocus); - editor.off('blur', handleBlur); + editor.off("focus", handleFocus); + editor.off("blur", handleBlur); }; } }, [editor]); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 7d26faf25..7ede4a42d 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -106,43 +106,48 @@ async function resolveEditorContent( fullInput: stripImages(parts), selectedCode, }; - const resolvedItems = await ideMessenger.request( - "context/getContextItems", - data, - ); - contextItems.push(...resolvedItems); - for (const resolvedItem of resolvedItems) { - contextItemsText += resolvedItem.content + "\n\n"; + const result = await ideMessenger.request("context/getContextItems", data); + if (result.status === "success") { + const resolvedItems = result.content; + contextItems.push(...resolvedItems); + for (const resolvedItem of resolvedItems) { + contextItemsText += resolvedItem.content + "\n\n"; + } } } // cmd+enter to use codebase if (modifiers.useCodebase) { - const codebaseItems = await ideMessenger.request( - "context/getContextItems", - { - name: "codebase", - query: "", - fullInput: stripImages(parts), - selectedCode, - }, - ); - contextItems.push(...codebaseItems); - for (const codebaseItem of codebaseItems) { - contextItemsText += codebaseItem.content + "\n\n"; + const result = await ideMessenger.request("context/getContextItems", { + name: "codebase", + query: "", + fullInput: stripImages(parts), + selectedCode, + }); + + if (result.status === "success") { + const codebaseItems = result.content; + contextItems.push(...codebaseItems); + for (const codebaseItem of codebaseItems) { + contextItemsText += codebaseItem.content + "\n\n"; + } } } // Include default context providers const defaultContextItems = await Promise.all( defaultContextProviders.map(async (provider) => { - const items = await ideMessenger.request("context/getContextItems", { + const result = await ideMessenger.request("context/getContextItems", { name: provider.name, query: provider.query ?? "", fullInput: stripImages(parts), selectedCode, }); - return items; + if (result.status === "success") { + return result.content; + } else { + return []; + } }), ); contextItems.push(...defaultContextItems.flat()); diff --git a/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx b/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx index be0b60c2b..db79a7a9b 100644 --- a/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx +++ b/gui/src/components/modelSelection/quickSetup/GitHubSignInButton.tsx @@ -62,12 +62,14 @@ function GitHubSignInButton(props: GitHubSignInButtonProps) {
{ - const token = await ideMessenger.request( + const result = await ideMessenger.request( "getGitHubAuthToken", undefined, ); - setLocalStorage("signedInToGh", true); - props.onComplete(token); + if (result.status === "success") { + setLocalStorage("signedInToGh", true); + props.onComplete(result.content); + } }} className="grid grid-flow-col items-center gap-2" > diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index fed23e1dc..0b5329c61 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -1,5 +1,6 @@ import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core"; import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; +import { WebviewMessengerResult } from "core/protocol/util"; import { MessageIde } from "core/util/messageIde"; import { Message } from "core/util/messenger"; import { createContext } from "react"; @@ -30,7 +31,7 @@ export interface IIdeMessenger { request( messageType: T, data: FromWebviewProtocol[T][0], - ): Promise; + ): Promise>; streamRequest( messageType: T, @@ -52,7 +53,16 @@ export class IdeMessenger implements IIdeMessenger { ide: IDE; constructor() { - this.ide = new MessageIde(this.request.bind(this), () => {}); + this.ide = new MessageIde( + async (messageType, data) => { + const result = await this.request(messageType, data); + if (result.status === "error") { + throw new Error(result.error); + } + return result.content; + }, + () => {}, + ); } private _postToIde(messageType: string, data: any, messageId?: string) { @@ -121,7 +131,7 @@ export class IdeMessenger implements IIdeMessenger { request( messageType: T, data: FromWebviewProtocol[T][0], - ): Promise { + ): Promise> { const messageId = uuidv4(); return new Promise((resolve) => { diff --git a/gui/src/hooks/useAuth.tsx b/gui/src/hooks/useAuth.tsx index 868b22779..49961df8b 100644 --- a/gui/src/hooks/useAuth.tsx +++ b/gui/src/hooks/useAuth.tsx @@ -25,14 +25,19 @@ export function useAuth(): { useEffect(() => { ideMessenger .request("getControlPlaneSessionInfo", { silent: true }) - .then(setSession); + .then( + (result) => result.status === "success" && setSession(result.content), + ); }, []); const login = () => { - console.log("login"); ideMessenger .request("getControlPlaneSessionInfo", { silent: false }) - .then((session) => { + .then((result) => { + if (result.status === "error") { + return; + } + const session = result.content; setSession(session); // If this is the first time the user has logged in, explain how profiles work diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 4956a6ed3..8e5fe22a2 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -30,7 +30,11 @@ function useHistory(dispatch: Dispatch) { offset?: number, limit?: number, ): Promise { - return await ideMessenger.request("history/list", { offset, limit }); + const result = await ideMessenger.request("history/list", { + offset, + limit, + }); + return result.status === "success" ? result.content : []; } async function saveSession() { @@ -86,11 +90,11 @@ function useHistory(dispatch: Dispatch) { } async function getSession(id: string): Promise { - const json: PersistedSessionInfo = await ideMessenger.request( - "history/load", - { id }, - ); - return json; + const result = await ideMessenger.request("history/load", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + return result.content; } async function updateSession(sessionInfo: PersistedSessionInfo) { @@ -103,10 +107,11 @@ function useHistory(dispatch: Dispatch) { async function loadSession(id: string): Promise { setLocalStorage("lastSessionId", state.sessionId); - const json: PersistedSessionInfo = await ideMessenger.request( - "history/load", - { id }, - ); + const result = await ideMessenger.request("history/load", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + const json = result.content; dispatch(newSession(json)); return json; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 28cd4019b..92fc15fda 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -9,14 +9,15 @@ import { setConfig, setInactive, setSelectedProfileId, + setTTSActive, } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; +import { debounce } from "lodash"; import { isJetBrains } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import useChatHandler from "./useChatHandler"; import { useWebviewListener } from "./useWebviewListener"; -import { debounce } from "lodash"; function useSetup(dispatch: Dispatch) { const [configLoaded, setConfigLoaded] = useState(false); @@ -24,10 +25,14 @@ function useSetup(dispatch: Dispatch) { const ideMessenger = useContext(IdeMessengerContext); const loadConfig = async () => { - const { config, profileId } = await ideMessenger.request( + const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, ); + if (result.status === "error") { + return; + } + const { config, profileId } = result.content; dispatch(setConfig(config)); dispatch(setSelectedProfileId(profileId)); setConfigLoaded(true); @@ -59,7 +64,11 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); // Tell JetBrains the webview is ready - ideMessenger.request("onLoad", undefined).then((msg) => { + ideMessenger.request("onLoad", undefined).then((result) => { + if (result.status === "error") { + return; + } + const msg = result.content; (window as any).windowId = msg.windowId; (window as any).serverUrl = msg.serverUrl; (window as any).workspacePaths = msg.workspacePaths; @@ -81,6 +90,10 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); }); + useWebviewListener("setTTSActive", async (status) => { + dispatch(setTTSActive(status)); + }); + useWebviewListener("setColors", async (colors) => { Object.keys(colors).forEach((key) => { document.body.style.setProperty(key, colors[key]); diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index b41526ce9..1c79fe0c6 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -204,10 +204,15 @@ function useSubmenuContextProviders() { fields: ["title", "description"], storeFields: ["id", "title", "description"], }); - const items = await ideMessenger.request("context/loadSubmenuItems", { + const result = await ideMessenger.request("context/loadSubmenuItems", { title: description.title, }); + if (result.status === "error") { + continue; + } + const items = result.content; + try { minisearch.addAll(items); } catch (itemError) { diff --git a/gui/src/pages/AddNewModel/ConfigureProvider.tsx b/gui/src/pages/AddNewModel/ConfigureProvider.tsx index b46db1931..ae3837c27 100644 --- a/gui/src/pages/AddNewModel/ConfigureProvider.tsx +++ b/gui/src/pages/AddNewModel/ConfigureProvider.tsx @@ -1,6 +1,6 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import _ from "lodash"; -import React, { useCallback, useContext, useEffect, useState } from "react"; +import { useCallback, useContext, useEffect, useState } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { useDispatch } from "react-redux"; import { useNavigate, useParams } from "react-router-dom"; @@ -14,7 +14,6 @@ import { import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; import ModelCard from "../../components/modelSelection/ModelCard"; import ModelProviderTag from "../../components/modelSelection/ModelProviderTag"; -import Toggle from "../../components/modelSelection/Toggle"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { setDefaultModel } from "../../redux/slices/stateSlice"; @@ -65,35 +64,12 @@ function ConfigureProvider() { undefined, ); - // different authentication flow is required for watsonx. This state helps to determine which flow to use for authentication - const [watsonxAuthenticate, setWatsonxAuthenticate] = React.useState(true); - useEffect(() => { if (providerName) { setModelInfo(providers[providerName]); } }, [providerName]); - const handleContinue = () => { - if (!modelInfo) return; - - let formParams: any = {}; - for (const d of modelInfo.collectInputFor || []) { - const val = formMethods.watch(d.key); - if (val === "" || val === undefined || val === null) continue; - formParams = updatedObj(formParams, { - [d.key]: d.inputType === "text" ? val : parseFloat(val), - }); - } - const model = { - ...formParams, - provider: modelInfo.provider, - }; - ideMessenger.post("config/addModel", { model }); - dispatch(setDefaultModel({ title: model.title, force: true })); - navigate("/"); - }; - const disableModelCards = useCallback(() => { return ( modelInfo?.collectInputFor?.some((d) => { @@ -106,17 +82,6 @@ function ConfigureProvider() { ); }, [modelInfo, formMethods]); - const enablecardsForApikey = useCallback(() => { - return modelInfo?.collectInputFor - ?.filter((d) => d.isWatsonxAuthenticatedByApiKey) - .some((d) => !formMethods.watch(d.key)); - }, [modelInfo, formMethods]); - const enablecardsForCredentials = useCallback(() => { - return modelInfo?.collectInputFor - ?.filter((d) => d.isWatsonxAuthenticatedByCredentials) - .some((d) => !formMethods.watch(d.key)); - }, [modelInfo, formMethods]); - return (
@@ -161,112 +126,31 @@ function ConfigureProvider() { />
- {/* The Watsonx Authentication coukd be done by two different ways - 1 ==> Using Api key - 2 ==> Using Credentials */} - {providerName === "watsonx" ? ( + {(modelInfo?.collectInputFor?.filter((d) => d.required).length || 0) > + 0 && ( <> -
- { - setWatsonxAuthenticate((prev) => !prev); - }} - > -
- {watsonxAuthenticate ? ( - <> - {(modelInfo?.collectInputFor?.filter((d) => d.required) - .length || 0) > 0 && ( - <> -

Enter required parameters

+

Enter required parameters

- {modelInfo?.collectInputFor - .filter((d) => d.isWatsonxAuthenticatedByApiKey) - .map((d, idx) => ( -
- - -
- ))} - - )} - - ) : ( - <> - {(modelInfo?.collectInputFor?.filter((d) => d.required) - .length || 0) > 0 && ( - <> -

Enter required parameters

- - {modelInfo?.collectInputFor - .filter((d) => d.isWatsonxAuthenticatedByCredentials) - .map((d, idx) => ( -
- - -
- ))} - - )} - - )} - - ) : ( - <> - {(modelInfo?.collectInputFor?.filter((d) => d.required).length || - 0) > 0 && ( - <> -

Enter required parameters

- - {modelInfo?.collectInputFor - ?.filter((d) => d.required) - .map((d, idx) => ( -
- - -
- ))} - - )} + {modelInfo?.collectInputFor + ?.filter((d) => d.required) + .map((d, idx) => ( +
+ + +
+ ))} )} @@ -276,9 +160,8 @@ function ConfigureProvider() { Advanced (optional) + {modelInfo?.collectInputFor?.map((d, idx) => { - // Check the attribute is only for Watson X - if (d.isWatsonxAttribute) return null; if (d.required) return null; return (
@@ -287,7 +170,7 @@ function ConfigureProvider() { type={d.inputType} id={d.key} className="border-2 border-gray-200 rounded-md p-2 m-2" - placeholder={d.placeholder} + placeholder={d.placeholder ?? d.label} defaultValue={d.defaultValue} min={d.min} max={d.max} @@ -309,11 +192,7 @@ function ConfigureProvider() { return ( { - if ( - disableModelCards() && - enablecardsForApikey() && - enablecardsForCredentials() - ) - return; + if (disableModelCards()) return; let formParams: any = {}; for (const d of modelInfo.collectInputFor || []) { const val = formMethods.watch(d.key); diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 1c7756e3d..4763f77ff 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -722,7 +722,7 @@ export const models: { [key: string]: ModelPackage } = { isOpenSource: false, }, graniteChat: { - title: "Watsonx - Granite Chat", + title: "watsonx - Granite Chat", description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.", params: { @@ -735,38 +735,38 @@ export const models: { [key: string]: ModelPackage } = { isOpenSource: false, }, graniteCode: { - title: "Watsonx - Granite Code", + title: "watsonx - Granite Code 20b", description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.", params: { model: "ibm/granite-20b-code-instruct", contextLength: 20_000, - title: "Granite Code" + title: "watsonx - Granite Code 20b" }, providerOptions: ["watsonx"], - icon: "Watsonx.png", + icon: "watsonx.png", isOpenSource: false, }, MistralLarge: { - title: "Watsonx - Mistral", + title: "watsonx - Mistral Large", description: "Mistral Large, the most advanced Large Language Model (LLM) developed by Mistral Al, is an exceptionally powerful model.", params: { model: "mistralai/mistral-large", contextLength: 20_000, - title: "Watsonx - Mistral", + title: "watsonx - Mistral Large", }, providerOptions: ["watsonx"], icon: "mistral.png", isOpenSource: false, }, MetaLlama3: { - title: "Meta Llama 3", + title: "watsonx - Llama 3.1", description: "Llama 3 is an auto-regressive language model that uses an optimized transformer architecture.", params: { - title: "Meta-llama3-8b", - model: "meta-llama/llama-3-8b-instruct", + title: "watsonx - Llama 3.1 8b", + model: "meta-llama/llama-3-1-8b-instruct", contextLength: 20_000, }, icon: "meta.png", @@ -776,12 +776,12 @@ export const models: { [key: string]: ModelPackage } = { description: "The number of parameters in the model", options: { "8b": { - model: "meta-llama/llama-3-8b-instruct", - title: "Meta-llama3-8b", + model: "meta-llama/llama-3-1-8b-instruct", + title: "watsonx - Llama 3.1 8b", }, "70b": { - model: "meta-llama/llama-3-70b-instruct", - title: "Meta-llama3-70b", + model: "meta-llama/llama-3-1-70b-instruct", + title: "watsonx - Llama 3.1 70b", }, }, }, diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 4d83876ba..e36bd35b4 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -19,11 +19,6 @@ export interface InputDescriptor { required?: boolean; description?: string; [key: string]: any; - // the following are used only for Watsonx provider - // these attributes are used to determine whether the input is used in Api Authentication or Credentials section - isWatsonxAuthenticatedByApiKey?: boolean; - isWatsonxAuthenticatedByCredentials?: boolean; - isWatsonxAttribute?: boolean; } export interface ProviderInfo { @@ -481,69 +476,57 @@ After it's up and running, you can start using Continue.`, ], }, watsonx: { - title: "Watsonx", + title: "IBM watsonx", provider: "watsonx", refPage: "watsonX", description: "Explore foundation models from IBM and other third-parties depending on your use case.", - longDescription: `Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.`, + longDescription: `**watsonx**, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. + +To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx) on watsonx SaaS, create your first project and setup an [API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key).`, collectInputFor: [ { inputType: "text", key: "watsonxUrl", - label: "Watsonx URL", - placeholder: "http://.dataplatform.cloud.ibm.com", - required: true, - isWatsonxAuthenticatedByApiKey: true, - isWatsonxAuthenticatedByCredentials: true, - }, - { - inputType: "text", - key: "watsonxApiKey", - label: "Watsonx API Key", - placeholder: "Enter your API key", - required: true, - isWatsonxAuthenticatedByApiKey: true, + label: "watsonx URL", + placeholder: "e.g. http://us-south.dataplatform.cloud.ibm.com", + required: true }, { inputType: "text", key: "watsonxProjectId", - label: "Watsonx Project Id", - placeholder: "Enter your project Id", - required: true, - isWatsonxAuthenticatedByApiKey: true, - isWatsonxAuthenticatedByCredentials: true, + label: "watsonx Project ID", + placeholder: "Enter your project ID", + required: true }, { inputType: "text", - key: "watsonxUsername", - label: "Watsonx Username", - placeholder: "Enter your Username", - required: true, - isWatsonxAuthenticatedByCredentials: true, + key: "watsonxCreds", + label: "watsonx API key", + placeholder: "Enter your API key (SaaS) or ZenApiKey (Software)", + required: true }, { inputType: "text", - key: "watsonxPassword", - label: "Watsonx Password", - placeholder: "Enter your password", - required: true, - isWatsonxAuthenticatedByCredentials: true, - }, - { - inputType: "text", - key: "title", - label: "Model name", - placeholder: "Granite 13B Chat v2", - isWatsonxAttribute: true, - }, - { - inputType: "text", - key: "model", - label: "Model Id", - placeholder: "ibm/granite-13b-chat-v2", - isWatsonxAttribute: true, + key: "watsonxApiVersion", + label: "watsonx API version", + placeholder: "Enter the API Version", + defaultValue: "2023-05-29" }, + // { + // inputType: "text", + // key: "title", + // label: "Model name", + // placeholder: "Granite 13B Chat v2", + // isWatsonxAttribute: true, + // }, + // { + // inputType: "text", + // key: "model", + // label: "Model Id", + // placeholder: "ibm/granite-13b-chat-v2", + // isWatsonxAttribute: true, + // }, { inputType: "text", key: "watsonxStopToken", @@ -553,7 +536,7 @@ After it's up and running, you can start using Continue.`, ...completionParamsInputsConfigs, ], - icon: "Watsonx.png", + icon: "watsonx.png", tags: [ModelProviderTags.RequiresApiKey], packages: [ models.graniteCode, diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 2de4e5f6b..d38e57dd9 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -163,6 +163,7 @@ function GUI() { const defaultModel = useSelector(defaultModelSelector); + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); const active = useSelector((state: RootState) => state.state.active); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); @@ -492,7 +493,9 @@ function GUI() {
{ - loadLastSession(); + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); }} className="mr-auto flex items-center gap-2" > @@ -517,6 +520,16 @@ function GUI() { trackVisibility={active} /> + {ttsActive && ( + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + )} {active && ( - - - Create a GitHub issue @@ -132,15 +120,6 @@ function HelpPage() { className="no-underline" > - - - Continue Discord diff --git a/gui/src/pages/onboarding/ApiKeysOnboarding.tsx b/gui/src/pages/onboarding/ApiKeysOnboarding.tsx index 2b070960c..95f733ccf 100644 --- a/gui/src/pages/onboarding/ApiKeysOnboarding.tsx +++ b/gui/src/pages/onboarding/ApiKeysOnboarding.tsx @@ -6,7 +6,7 @@ import Toggle from "../../components/modelSelection/Toggle"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { getLocalStorage } from "../../util/localStorage"; import DefaultModelConfigForm from "./DefaultModelConfigForm"; -import { useOnboarding } from "./utils"; +import { useCompleteOnboarding } from "./utils"; function ApiKeysOnboarding() { const ideMessenger = useContext(IdeMessengerContext); @@ -14,7 +14,7 @@ function ApiKeysOnboarding() { const [isBestToggle, setIsBestToggle] = useState(true); - const { completeOnboarding } = useOnboarding(); + const { completeOnboarding } = useCompleteOnboarding(); return (
diff --git a/gui/src/pages/onboarding/DefaultModelConfigForm.tsx b/gui/src/pages/onboarding/DefaultModelConfigForm.tsx index 90e0d56d6..9c3940bec 100644 --- a/gui/src/pages/onboarding/DefaultModelConfigForm.tsx +++ b/gui/src/pages/onboarding/DefaultModelConfigForm.tsx @@ -7,7 +7,7 @@ import { setDefaultModel } from "../../redux/slices/stateSlice"; import { models } from "../AddNewModel/configs/models"; import { providers } from "../AddNewModel/configs/providers"; import { StyledButton } from "./components"; -import { useOnboarding } from "./utils"; +import { useCompleteOnboarding } from "./utils"; const HelperText = styled.p` font-size: 0.8rem; @@ -23,7 +23,7 @@ function DefaultModelConfigForm() { const [mistralApiKey, setMistralApiKey] = useState(""); const [anthropicApiKey, setAnthropicApiKey] = useState(""); - const { completeOnboarding } = useOnboarding(); + const { completeOnboarding } = useCompleteOnboarding(); const isFormComplete = !!mistralApiKey && !!anthropicApiKey; diff --git a/gui/src/pages/onboarding/LocalOnboarding.tsx b/gui/src/pages/onboarding/LocalOnboarding.tsx index ea0b03143..04611c553 100644 --- a/gui/src/pages/onboarding/LocalOnboarding.tsx +++ b/gui/src/pages/onboarding/LocalOnboarding.tsx @@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckMarkHeader } from "./CheckMarkHeader"; import { StyledButton } from "./components"; import { CopyToTerminalButton } from "./CopyToTerminalButton"; -import { useOnboarding } from "./utils"; +import { useCompleteOnboarding } from "./utils"; type OllamaConnectionStatuses = | "waiting_to_download" @@ -35,7 +35,7 @@ function LocalOnboarding() { const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); - const { completeOnboarding } = useOnboarding(); + const { completeOnboarding } = useCompleteOnboarding(); const isOllamaConnected = ollamaConnectionStatus === "verified"; diff --git a/gui/src/pages/onboarding/Onboarding.tsx b/gui/src/pages/onboarding/Onboarding.tsx index 827fec0f0..a1de9a528 100644 --- a/gui/src/pages/onboarding/Onboarding.tsx +++ b/gui/src/pages/onboarding/Onboarding.tsx @@ -5,7 +5,7 @@ import { GiftIcon, } from "@heroicons/react/24/outline"; import { ToCoreFromIdeOrWebviewProtocol } from "core/protocol/core"; -import { useContext, useState } from "react"; +import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { lightGray } from "../../components"; @@ -19,7 +19,9 @@ import { import { isJetBrains } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS, hasPassedFTL } from "../../util/freeTrial"; import { Div, StyledButton } from "./components"; -import { useOnboarding } from "./utils"; +import { isNewUserOnboarding, useCompleteOnboarding } from "./utils"; +import { setLocalStorage } from "../../util/localStorage"; +import { usePostHog } from "posthog-js/react"; type OnboardingMode = ToCoreFromIdeOrWebviewProtocol["completeOnboarding"][0]["mode"]; @@ -27,6 +29,7 @@ type OnboardingMode = function Onboarding() { const navigate = useNavigate(); const dispatch = useDispatch(); + const posthog = usePostHog(); const ideMessenger = useContext(IdeMessengerContext); const [hasSignedIntoGh, setHasSignedIntoGh] = useState(false); @@ -34,7 +37,7 @@ function Onboarding() { OnboardingMode | undefined >(undefined); - const { completeOnboarding } = useOnboarding(); + const { completeOnboarding } = useCompleteOnboarding(); function onSubmit() { ideMessenger.post("completeOnboarding", { @@ -68,8 +71,15 @@ function Onboarding() { } } + useEffect(() => { + if (isNewUserOnboarding()) { + posthog.capture("Onboarding Step", { status: "Started" }); + setLocalStorage("onboardingStatus", "Started"); + } + }, []); + return ( -
+

Welcome to Continue

diff --git a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx b/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx index 0bff4deab..45f667182 100644 --- a/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx +++ b/gui/src/pages/onboarding/apiKeyAutocompleteOnboarding.tsx @@ -13,7 +13,7 @@ import { StyledListboxOptions, } from "../../components/modelSelection/quickSetup/StyledListbox"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useOnboarding } from "./utils"; +import { useCompleteOnboarding } from "./utils"; interface AutocompleteOption { provider: ModelProvider; @@ -124,7 +124,7 @@ function ApiKeyAutocompleteOnboarding() { const [apiKeyValue, setApiKeyValue] = useState(""); - const { completeOnboarding } = useOnboarding(); + const { completeOnboarding } = useCompleteOnboarding(); return (

diff --git a/gui/src/pages/onboarding/utils.ts b/gui/src/pages/onboarding/utils.ts index 0c978a41e..48c15a28b 100644 --- a/gui/src/pages/onboarding/utils.ts +++ b/gui/src/pages/onboarding/utils.ts @@ -1,5 +1,4 @@ import { usePostHog } from "posthog-js/react"; -import { useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; @@ -9,15 +8,16 @@ export type OnboardingStatus = "Started" | "Completed"; // If there is no value in local storage for "onboardingStatus", // it implies that the user has not begun or completed onboarding. -export function shouldBeginOnboarding() { +export function isNewUserOnboarding() { // We used to use "onboardingComplete", but switched to "onboardingStatus" const onboardingCompleteLegacyValue = localStorage.getItem("onboardingComplete"); + if (onboardingCompleteLegacyValue === "true") { setLocalStorage("onboardingStatus", "Completed"); localStorage.removeItem("onboardingComplete"); - return false; } + const onboardingStatus = getLocalStorage("onboardingStatus"); return onboardingStatus === undefined; @@ -26,11 +26,11 @@ export function shouldBeginOnboarding() { /** * Telemetry, status tracking, and routing logic for new user onboarding. */ -export function useOnboarding() { +export function useCompleteOnboarding() { const posthog = usePostHog(); const navigate = useNavigate(); - const completeOnboarding = () => { + function completeOnboarding() { const onboardingStatus = getLocalStorage("onboardingStatus"); if (onboardingStatus === "Started") { @@ -40,14 +40,7 @@ export function useOnboarding() { } navigate("/"); - }; - - useEffect(() => { - if (shouldBeginOnboarding()) { - setLocalStorage("onboardingStatus", "Started"); - posthog.capture("Onboarding Step", { status: "Started" }); - } - }, []); + } return { completeOnboarding, diff --git a/gui/src/pages/stats.tsx b/gui/src/pages/stats.tsx index c07adc864..aed0bf91f 100644 --- a/gui/src/pages/stats.tsx +++ b/gui/src/pages/stats.tsx @@ -46,21 +46,25 @@ function Stats() { >([]); useEffect(() => { - ideMessenger.request("stats/getTokensPerDay", undefined).then((days) => { - setDays(days); + ideMessenger.request("stats/getTokensPerDay", undefined).then((result) => { + result.status === "success" && setDays(result.content); }); }, []); useEffect(() => { ideMessenger .request("stats/getTokensPerModel", undefined) - .then((models) => { - setModels(models); + .then((result) => { + result.status === "success" && setModels(result.content); }); }, []); return ( -
+
My Usage
-
-

Tokens per Day

- [ - day.day, - day.generatedTokens, - day.promptTokens, - ]), - ), - )} - /> -
- - - - - - - - - - {days.map((day) => ( - - - - +
+
+

Tokens per Day

+ [ + day.day, + day.generatedTokens, + day.promptTokens, + ]), + ), + )} + /> +
+
DayGenerated TokensPrompt Tokens
{day.day}{day.generatedTokens}{day.promptTokens}
+ + + + + - ))} - -
DayGenerated TokensPrompt Tokens
+ + + {days.map((day) => ( + + {day.day} + {day.generatedTokens.toLocaleString()} + {day.promptTokens.toLocaleString()} + + ))} + + -
-

Tokens per Model

- [ - model.model, - model.generatedTokens, - model.promptTokens, - ]), - ), - )} - /> -
- - - - - - - - - - {models.map((model) => ( - - - - +
+

Tokens per Model

+ [ + model.model, + model.generatedTokens.toLocaleString(), + model.promptTokens.toLocaleString(), + ]), + ), + )} + /> +
+
ModelGenerated TokensPrompt Tokens
{model.model}{model.generatedTokens}{model.promptTokens}
+ + + + + - ))} - -
ModelGenerated TokensPrompt Tokens
+ + + {models.map((model) => ( + + {model.model} + {model.generatedTokens.toLocaleString()} + {model.promptTokens.toLocaleString()} + + ))} + + +
); } diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 69b0450c8..7534d9b85 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -98,6 +98,7 @@ fn bubble_sort(values: &mut[T]) { type State = { history: ChatHistory; contextItems: ContextItemWithId[]; + ttsActive: boolean; active: boolean; config: BrowserSerializedContinueConfig; title: string; @@ -110,6 +111,7 @@ type State = { const initialState: State = { history: [], contextItems: [], + ttsActive: false, active: false, config: { slashCommands: [ @@ -168,6 +170,9 @@ export const stateSlice = createSlice({ ? lastHistory.promptLogs.concat(payload) : payload; }, + setTTSActive: (state, { payload }: PayloadAction) => { + state.ttsActive = payload; + }, setActive: (state) => { state.active = true; }, @@ -510,6 +515,7 @@ export const { setDefaultModel, setConfig, addPromptCompletionPair, + setTTSActive, setActive, setEditingContextItemAtIndex, initNewActiveMessage, diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 8882ad42a..3a47980bc 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -53,6 +53,11 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { ...config, apiBase: "https://api.groq.com/openai/v1/", }); + case "nvidia": + return new OpenAIApi({ + ...config, + apiBase: "https://integrate.api.nvidia.com/v1/", + }); case "fireworks": return new OpenAIApi({ ...config, diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index 6fe6e1fce..9f3fbe2e9 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -7,6 +7,8 @@ set -e echo "Installing Core extension dependencies..." pushd core +## This flag is set because we pull down Chromium at runtime +export PUPPETEER_SKIP_DOWNLOAD='true' npm install npm link