Merge branch 'dev' into terminal-context-provider
This commit is contained in:
commit
cb61850417
139 changed files with 3687 additions and 1792 deletions
8
.changes/extensions/vscode/0.8.47.md
Normal file
8
.changes/extensions/vscode/0.8.47.md
Normal file
|
|
@ -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
|
||||
12
.github/workflows/main.yaml
vendored
12
.github/workflows/main.yaml
vendored
|
|
@ -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
|
||||
|
|
|
|||
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -165,7 +165,8 @@ Icon?
|
|||
|
||||
.continue
|
||||
|
||||
# Sandbox env default file
|
||||
extensions/vscode/manual-testing-sandbox/example.ts
|
||||
|
||||
.prompts/
|
||||
.prompts/
|
||||
.aider*
|
||||
|
||||
notes.md
|
||||
2
.vscode/tasks.json
vendored
2
.vscode/tasks.json
vendored
|
|
@ -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",
|
||||
|
|
|
|||
4
binary/package-lock.json
generated
4
binary/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)[] = [];
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
this.workspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<void>,
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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, string>,
|
||||
) => 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<string, string>;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
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<string>;
|
||||
|
||||
|
||||
streamComplete(
|
||||
prompt: string,
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<string, LLMReturnValue>;
|
||||
|
||||
): AsyncGenerator<string, PromptLog>;
|
||||
|
||||
streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<string, PromptLog>;
|
||||
|
||||
streamChat(
|
||||
messages: ChatMessage[],
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue>;
|
||||
|
||||
): AsyncGenerator<ChatMessage, PromptLog>;
|
||||
|
||||
chat(
|
||||
messages: ChatMessage[],
|
||||
options?: LLMFullCompletionOptions,
|
||||
): Promise<ChatMessage>;
|
||||
|
||||
|
||||
countTokens(text: string): number;
|
||||
|
||||
|
||||
supportsImages(): boolean;
|
||||
|
||||
|
||||
supportsCompletions(): boolean;
|
||||
|
||||
|
||||
supportsPrefill(): boolean;
|
||||
|
||||
|
||||
supportsFim(): boolean;
|
||||
|
||||
listModels(): Promise<string[]>;
|
||||
|
||||
|
||||
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<any>;
|
||||
|
||||
|
||||
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<ContextSubmenuItem[]>;
|
||||
}
|
||||
|
||||
|
||||
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<ContextItem[]>;
|
||||
|
||||
|
||||
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
|
||||
}
|
||||
|
||||
|
||||
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<string, string>;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
writeLog?: (str: string) => Promise<void>;
|
||||
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<T, Keys extends keyof T = keyof T> = Pick<
|
||||
T,
|
||||
|
|
@ -288,7 +351,7 @@ declare global {
|
|||
{
|
||||
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
|
||||
}[Keys];
|
||||
|
||||
|
||||
export interface CustomLLMWithOptionals {
|
||||
options: LLMOptions;
|
||||
streamCompletion?: (
|
||||
|
|
@ -305,7 +368,7 @@ declare global {
|
|||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => Promise<string[]>;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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<IdeInfo>;
|
||||
getIdeSettings(): Promise<IdeSettings>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
|
|
@ -365,6 +447,7 @@ declare global {
|
|||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
fileExists(filepath: string): Promise<boolean>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -384,6 +467,7 @@ declare global {
|
|||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getCurrentFile(): Promise<string | undefined>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
|
|
@ -391,10 +475,24 @@ declare global {
|
|||
getBranch(dir: string): Promise<string>;
|
||||
getTags(artifactId: string): Promise<IndexTag[]>;
|
||||
getRepoName(dir: string): Promise<string | undefined>;
|
||||
errorPopup(message: string): Promise<void>;
|
||||
infoPopup(message: string): Promise<void>;
|
||||
|
||||
getGitRootPath(dir: string): Promise<string | undefined>;
|
||||
listDir(dir: string): Promise<[string, FileType][]>;
|
||||
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
|
||||
getGitHubAuthToken(): Promise<string | undefined>;
|
||||
|
||||
// LSP
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
|
||||
pathSep(): Promise<string>;
|
||||
}
|
||||
|
||||
|
||||
// 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<string | undefined>;
|
||||
}
|
||||
|
||||
|
||||
// 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<number[][]>;
|
||||
}
|
||||
|
||||
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<number[]>;
|
||||
}
|
||||
|
||||
|
||||
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<TabAutocompleteOptions>;
|
||||
ui?: ContinueUIConfig;
|
||||
reranker?: RerankerDescription;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
}
|
||||
|
||||
|
||||
export type ConfigMergeType = "merge" | "overwrite";
|
||||
|
||||
|
||||
export type ContinueRcJson = Partial<SerializedContinueConfig> & {
|
||||
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<TabAutocompleteOptions>;
|
||||
/** 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<TabAutocompleteOptions>;
|
||||
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 {};
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ class CodeContextProvider extends BaseContextProvider {
|
|||
);
|
||||
|
||||
const submenuItems: ContextSubmenuItem[] = [];
|
||||
|
||||
for (const snippetList of snippets.slice(-MAX_SUBMENU_ITEMS)) {
|
||||
submenuItems.push(...snippetList);
|
||||
}
|
||||
|
|
|
|||
125
core/context/providers/RepoMapContextProvider.ts
Normal file
125
core/context/providers/RepoMapContextProvider.ts
Normal file
|
|
@ -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<ContextItem[]> {
|
||||
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;
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
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<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void> {
|
||||
this.uniqueId = uniqueId;
|
||||
this.addOnId = config.url?.split("/").slice(-1)[0];
|
||||
this.workspaceId = workspaceId;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ export interface AnalyticsMetadata {
|
|||
|
||||
export interface IAnalyticsProvider {
|
||||
capture(event: string, properties: { [key: string]: any }): Promise<void>;
|
||||
setup(config: Analytics, uniqueId: string): Promise<void>;
|
||||
setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,11 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
|
|||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void> {
|
||||
if (!config.url) {
|
||||
console.warn("LogStashAnalyticsProvider is missing a URL");
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,11 @@ export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
|
|||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
async setup(
|
||||
config: Analytics,
|
||||
uniqueId: string,
|
||||
workspaceId?: string,
|
||||
): Promise<void> {
|
||||
if (!config || !config.clientKey || !config.url) {
|
||||
this.client = undefined;
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
42
core/core.ts
42
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<string>,
|
||||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
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<string>,
|
||||
|
|
@ -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",
|
||||
{
|
||||
|
|
|
|||
32
core/index.d.ts
vendored
32
core/index.d.ts
vendored
|
|
@ -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<T, Keys extends keyof T = keyof T> = 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 {
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ describe("CodeSnippetsCodebaseIndex", () => {
|
|||
const mockSnippet = {
|
||||
title: "",
|
||||
content: "",
|
||||
signature: "",
|
||||
startLine: 0,
|
||||
endLine: 1,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<SnippetChunk[]> {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
130
core/indexing/docs/DocsCrawler.test.ts
Normal file
130
core/indexing/docs/DocsCrawler.test.ts
Normal file
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
248
core/indexing/docs/DocsCrawler.ts
Normal file
248
core/indexing/docs/DocsCrawler.ts
Normal file
|
|
@ -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<PageData> {
|
||||
if (this.startUrl.host === this.GITHUB_HOST) {
|
||||
yield* this.crawlGithubRepo();
|
||||
} else {
|
||||
yield* this.crawlSite();
|
||||
}
|
||||
}
|
||||
|
||||
private async getGithubRepoDefaultBranch(
|
||||
owner: string,
|
||||
repo: string,
|
||||
): Promise<string> {
|
||||
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<string> = new Set(),
|
||||
curRequestCount: number = 0,
|
||||
): AsyncGenerator<PageData> {
|
||||
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<PageData> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
|
|
@ -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<string> {
|
||||
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<PageData> {
|
||||
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");
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { SiteIndexingConfig } from "../../index.js";
|
||||
import { SiteIndexingConfig } from "../../";
|
||||
|
||||
const preIndexedDocs: Record<
|
||||
SiteIndexingConfig["startUrl"],
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
13
core/indexing/embeddings/VoyageEmbeddingsProvider.ts
Normal file
13
core/indexing/embeddings/VoyageEmbeddingsProvider.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "voyage";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.voyageai.com/v1/",
|
||||
model: "voyage-code-2",
|
||||
};
|
||||
}
|
||||
|
||||
export default VoyageEmbeddingsProvider;
|
||||
|
|
@ -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,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export enum IndexResultType {
|
|||
Delete = "del",
|
||||
AddTag = "addTag",
|
||||
RemoveTag = "removeTag",
|
||||
UpdateLastUpdated = "updateLastUpdated"
|
||||
UpdateLastUpdated = "updateLastUpdated",
|
||||
}
|
||||
|
||||
export type MarkCompleteCallback = (
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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}/`;
|
||||
|
|
|
|||
|
|
@ -75,6 +75,9 @@ class Anthropic extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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<LLMOptions> = {
|
||||
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()();
|
||||
}
|
||||
|
|
|
|||
96
core/llm/llms/BedrockImport.ts
Normal file
96
core/llm/llms/BedrockImport.ts
Normal file
|
|
@ -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<LLMOptions> = {
|
||||
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<string> {
|
||||
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;
|
||||
16
core/llm/llms/Kindo.ts
Normal file
16
core/llm/llms/Kindo.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { LLMOptions, ModelProvider } from "../..";
|
||||
import OpenAI from "./OpenAI";
|
||||
|
||||
class Kindo extends OpenAI {
|
||||
static providerName: ModelProvider = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE"
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default Kindo;
|
||||
33
core/llm/llms/Nvidia.ts
Normal file
33
core/llm/llms/Nvidia.ts
Normal file
|
|
@ -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<LLMOptions> = {
|
||||
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;
|
||||
|
|
@ -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+/, ""));
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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 ? "<STOP EDITING HERE>" : "";
|
||||
const suffixExplanation = isSuffix
|
||||
? " When you get to \"<STOP EDITING HERE>\", end your response."
|
||||
? ' When you get to "<STOP EDITING HERE>", 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
|
||||
|
|
|
|||
655
core/package-lock.json
generated
655
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
|
|
|
|||
|
|
@ -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[] },
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
];
|
||||
|
|
|
|||
17
core/protocol/util.ts
Normal file
17
core/protocol/util.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { FromWebviewProtocol } from ".";
|
||||
|
||||
interface ErrorWebviewMessengerResult {
|
||||
done: boolean;
|
||||
status: "error";
|
||||
error: string;
|
||||
}
|
||||
|
||||
interface SuccessWebviewMessengerResult<T extends keyof FromWebviewProtocol> {
|
||||
done: boolean;
|
||||
status: "success";
|
||||
content: FromWebviewProtocol[T][1];
|
||||
}
|
||||
|
||||
export type WebviewMessengerResult<T extends keyof FromWebviewProtocol> =
|
||||
| ErrorWebviewMessengerResult
|
||||
| SuccessWebviewMessengerResult<T>;
|
||||
|
|
@ -13,4 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
setTTSActive: [boolean, void];
|
||||
};
|
||||
|
|
|
|||
131
core/test/util/history.test.ts
Normal file
131
core/test/util/history.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
117
core/util/tts.ts
Normal file
117
core/util/tts.ts
Normal file
|
|
@ -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<ToCoreProtocol, FromCoreProtocol>;
|
||||
|
||||
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<void> {
|
||||
return new Promise<void>((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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
|
|
|||
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 858 KiB |
|
|
@ -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 <https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview>
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
```
|
||||
|
|
|
|||
28
docs/docs/reference/Model Providers/bedrockimport.md
Normal file
28
docs/docs/reference/Model Providers/bedrockimport.md
Normal file
|
|
@ -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.
|
||||
```
|
||||
42
docs/docs/reference/Model Providers/kindo.md
Normal file
42
docs/docs/reference/Model Providers/kindo.md
Normal file
|
|
@ -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": "<KINDO_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Tab Autocomplete Config Example
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"tabAutocompleteModel": [
|
||||
{
|
||||
"title": "WhiteRabbitNeo",
|
||||
"provider": "kindo",
|
||||
"model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder",
|
||||
"apiKey": "<KINDO_API_KEY>"
|
||||
},
|
||||
{
|
||||
"title": "DeepSeek",
|
||||
"provider": "kindo",
|
||||
"model": "deepseek-ai/deepseek-coder-33b-instruct",
|
||||
"apiKey": "<KINDO_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings).
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 "<username>:<apikey>" | base64`, replacing `<username>` with your CPD username and `<apikey>` 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
|
||||

|
||||

|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
40
docs/static/schemas/config.json
vendored
40
docs/static/schemas/config.json
vendored
|
|
@ -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 <MODEL_NAME>`. 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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<String, Any>
|
||||
val profileInfo = data?.get("config") as? Map<String, Any>
|
||||
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
}
|
||||
}
|
||||
}
|
||||
val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient)
|
||||
continuePluginService.coreMessengerManager = coreMessengerManager
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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<String, Any>
|
||||
val profileInfo = data?.get("config") as? Map<String, Any>
|
||||
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
|
||||
val telemetryService = service<TelemetryService>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<String?> {
|
||||
|
|
|
|||
|
|
@ -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<CustomPanel>, textArea: JTextArea, inlayRef: Ref<Disposable>, comboBoxRef: Ref<JComboBox<String>>, leftInset: Int, modelTitles: List<String>, 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<ContinuePluginService>()
|
||||
val modelTitles = mutableListOf<String>()
|
||||
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val config = response as Map<String, Any>
|
||||
val models = (config["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
|
||||
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<Disposable>()
|
||||
val customPanelRef = Ref<CustomPanel>()
|
||||
|
||||
// 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>()
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
diffStreamHandler.setup()
|
||||
|
||||
val comboBoxRef = Ref<JComboBox<String>>()
|
||||
|
||||
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<ContinuePluginService>()
|
||||
val modelTitles = mutableListOf<String>()
|
||||
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val config = response as Map<String, Any>
|
||||
val models = (config["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
|
||||
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<Disposable>()
|
||||
val customPanelRef = Ref<CustomPanel>()
|
||||
|
||||
// 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>()
|
||||
diffStreamService.register(diffStreamHandler, editor)
|
||||
|
||||
diffStreamHandler.setup()
|
||||
|
||||
val comboBoxRef = Ref<JComboBox<String>>()
|
||||
|
||||
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<CustomPanel>, textArea: JTextArea, inlayRef: Ref<Disposable>, comboBoxRef: Ref<JComboBox<String>>, leftInset: Int, modelTitles: List<String>, 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<String>
|
|||
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<String>
|
|||
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<String>
|
|||
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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<ToolTipComponent>() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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<ContinueExtensionSettings>()
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<ContinueExtensio
|
|||
var enableTabAutocomplete: Boolean = true
|
||||
var ghAuthToken: String? = null
|
||||
var enableContinueTeamsBeta: Boolean = false
|
||||
var displayEditorTooltip: Boolean = true
|
||||
}
|
||||
|
||||
var continueState: ContinueState = ContinueState()
|
||||
|
|
@ -105,8 +109,9 @@ class ContinueExtensionConfigurable : Configurable {
|
|||
mySettingsComponent?.remoteConfigSyncPeriod?.text?.toInt() != settings.continueState.remoteConfigSyncPeriod ||
|
||||
mySettingsComponent?.userToken?.text != settings.continueState.userToken ||
|
||||
mySettingsComponent?.enableTabAutocomplete?.isSelected != settings.continueState.enableTabAutocomplete ||
|
||||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected != settings.continueState.enableContinueTeamsBeta
|
||||
return modified;
|
||||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected != settings.continueState.enableContinueTeamsBeta ||
|
||||
mySettingsComponent?.displayEditorTooltip?.isSelected != settings.continueState.displayEditorTooltip
|
||||
return modified
|
||||
}
|
||||
|
||||
override fun apply() {
|
||||
|
|
@ -116,6 +121,7 @@ class ContinueExtensionConfigurable : Configurable {
|
|||
settings.continueState.userToken = mySettingsComponent?.userToken?.text
|
||||
settings.continueState.enableTabAutocomplete = mySettingsComponent?.enableTabAutocomplete?.isSelected ?: false
|
||||
settings.continueState.enableContinueTeamsBeta = mySettingsComponent?.enableContinueTeamsBeta?.isSelected ?: false
|
||||
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
|
||||
|
||||
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC).settingsUpdated(settings.continueState)
|
||||
}
|
||||
|
|
@ -127,6 +133,7 @@ class ContinueExtensionConfigurable : Configurable {
|
|||
mySettingsComponent?.userToken?.text = settings.continueState.userToken
|
||||
mySettingsComponent?.enableTabAutocomplete?.isSelected = settings.continueState.enableTabAutocomplete
|
||||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
|
||||
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
|
||||
}
|
||||
|
||||
override fun disposeUIResources() {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.services
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.`continue`.uuid
|
||||
import com.github.continuedev.continueintellijextension.toolWindow.ContinueBrowser
|
||||
|
|
@ -23,7 +24,11 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
|
|||
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
|
||||
|
||||
var ideProtocolClient: IdeProtocolClient? = null
|
||||
var coreMessenger: CoreMessenger? = null
|
||||
|
||||
var coreMessengerManager: CoreMessengerManager? = null
|
||||
val coreMessenger: CoreMessenger?
|
||||
get() = coreMessengerManager?.coreMessenger
|
||||
|
||||
var workspacePaths: Array<String>? = null
|
||||
var windowId: String = UUID.randomUUID().toString()
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
<vendor>continue-dev</vendor>
|
||||
<depends>com.intellij.modules.platform</depends>
|
||||
<depends>org.jetbrains.plugins.terminal</depends>
|
||||
<!-- <depends>com.intellij.modules.json</depends>-->
|
||||
<idea-version since-build="223.0"/>
|
||||
|
||||
<extensions defaultExtensionNs="JavaScript.JsonSchema">
|
||||
|
|
|
|||
|
|
@ -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 <MODEL_NAME>`. 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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 <MODEL_NAME>`. 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"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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 <MODEL_NAME>`. 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"
|
||||
},
|
||||
|
|
|
|||
7
extensions/vscode/package-lock.json
generated
7
extensions/vscode/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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 =
|
||||
|
|
|
|||
|
|
@ -177,6 +177,7 @@ export class VsCodeExtension {
|
|||
this.configHandler,
|
||||
this.ide,
|
||||
this.tabAutocompleteModel,
|
||||
this.sidebar.webviewProtocol,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue